Re: static immutable that has no initialiser - should this raise an error?

2023-05-31 Thread Dom DiSc via Digitalmars-d-learn

On Tuesday, 30 May 2023 at 04:11:00 UTC, Cecil Ward wrote:

static immutable T foo;

T bar() {
return foo;
}

Should we get an error from the D compiler here as the 
initialiser has been forgotten? What do you think ?

No.
There are no un-initialized values in D.
It gets its default value, if no explicit value is given.
That's intended, not an error.
If you need an un-initialized value, set it =void.
Of course, for immutable values that makes no sense at all.
But I think, this already gives you an error.



Re: SumType! seemingly results in cryptic error, with dub suggesting to make an issue ticket

2023-05-30 Thread Gimbles via Digitalmars-d-learn

On Tuesday, 30 May 2023 at 08:54:33 UTC, Gimbles wrote:

On Tuesday, 30 May 2023 at 08:47:16 UTC, user456 wrote:

On Tuesday, 30 May 2023 at 08:42:38 UTC, Gimbles wrote:

My code is this
[...]
Should I make an issue for this as it suggests?


100% yes. This an "Internal Compiler Error" (ICE), meaning the 
compiler has crashed.
Open a ticket here : 
https://issues.dlang.org/show_bug.cgi?id=23935


with a title like "ICE caused by std.sumtype", and paste the 
test case.


Alright, thanks! Opening a ticket :)


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

For reference ^^^


Re: SumType! seemingly results in cryptic error, with dub suggesting to make an issue ticket

2023-05-30 Thread Gimbles via Digitalmars-d-learn

On Tuesday, 30 May 2023 at 08:47:16 UTC, user456 wrote:

On Tuesday, 30 May 2023 at 08:42:38 UTC, Gimbles wrote:

My code is this
[...]
Should I make an issue for this as it suggests?


100% yes. This an "Internal Compiler Error" (ICE), meaning the 
compiler has crashed.
Open a ticket here : 
https://issues.dlang.org/show_bug.cgi?id=23935


with a title like "ICE caused by std.sumtype", and paste the 
test case.


Alright, thanks! Opening a ticket :)


Re: SumType! seemingly results in cryptic error, with dub suggesting to make an issue ticket

2023-05-30 Thread user456 via Digitalmars-d-learn

On Tuesday, 30 May 2023 at 08:42:38 UTC, Gimbles wrote:

My code is this
[...]
Should I make an issue for this as it suggests?


100% yes. This an "Internal Compiler Error" (ICE), meaning the 
compiler has crashed.
Open a ticket here : 
https://issues.dlang.org/show_bug.cgi?id=23935


with a title like "ICE caused by std.sumtype", and paste the test 
case.


Re: SumType! seemingly results in cryptic error, with dub suggesting to make an issue ticket

2023-05-30 Thread Gimbles via Digitalmars-d-learn

On Tuesday, 30 May 2023 at 08:42:38 UTC, Gimbles wrote:

My code is this
```d
struct ConstValueIndex
{
ushort const_value_index;
}

[...]


https://gist.github.com/run-dlang/5dd783c750f04329405af1b1e4a83cde

Here's the full source


SumType! seemingly results in cryptic error, with dub suggesting to make an issue ticket

2023-05-30 Thread Gimbles via Digitalmars-d-learn

My code is this
```d
struct ConstValueIndex
{
ushort const_value_index;
}

struct EnumConstValue
{
ushort type_name_index;
ushort const_name_index;
}

struct ClassInfoIndex
{
ushort class_info_index;
}

struct AnnotationValue
{
Annotation annotation_value;
}

struct ArrayValue
{
ElementValue[] values;
}

alias ElementValue = SumType!(
ConstValueIndex,
EnumConstValue,
ClassInfoIndex,
AnnotationValue,
ArrayValue,
);
```

It results in quite a cryptic error
```d
Error: unknown, please file report on issues.dlang.org
/usr/include/dlang/dmd/std/meta.d(632,42): Error: template 
instance `std.sumtype.matchImpl!(Flag.yes, 
destroyIfOwner).matchImpl!(SumType!(ConstValueIndex, 
EnumConstValue, ClassInfoIndex, AnnotationValue, 
ArrayValue)).matchImpl.valueTypes!4LU.fun!0LU` error instantiating
/usr/include/dlang/dmd/std/sumtype.d(1931,32):
instantiated from here: `Map!(getType, 0LU)`
/usr/include/dlang/dmd/std/sumtype.d(1967,51):
instantiated from here: `valueTypes!4LU`
/usr/include/dlang/dmd/std/sumtype.d(1649,52):
instantiated from here: `matchImpl!(SumType!(ConstValueIndex, 
EnumConstValue, ClassInfoIndex, AnnotationValue, ArrayValue))`
/usr/include/dlang/dmd/std/sumtype.d(752,17):instantiated 
from here: `match!(SumType!(ConstValueIndex, EnumConstValue, 
ClassInfoIndex, AnnotationValue, ArrayValue))`
source/parser/definitions/attributes.d(262,22):
instantiated from here: `SumType!(ConstValueIndex, 
EnumConstValue, ClassInfoIndex, AnnotationValue, ArrayValue)`
/usr/include/dlang/dmd/std/sumtype.d(1985,13):while 
evaluating: `static assert((__error)(hid))`

Error /usr/bin/dmd failed with exit code 1.
```

(I tried all three compilers, happens in all)

Should I make an issue for this as it suggests?


Re: Lockstep iteration in parallel: Error: cannot have parameter of type `void`

2023-05-23 Thread kdevel via Digitalmars-d-learn

On Saturday, 20 May 2023 at 18:27:47 UTC, Ali Çehreli wrote:

[...]
And I've just discovered something.


Me2! The serial version using array indexing

   void vec_op_naive0 (double [] outp, const double [] inp,
  double function (double) fp)
   {
  enforce (inp.length == outp.length);
  auto i = inp.length;
  while (i--)
 outp [i] = fp (inp [i]);
   }

is nearly thrice as fast as the one using lockstep

   void vec_op (double [] outp, const double [] inp,
  double function (double) fp)
   {
  foreach (ref a, b; lockstep (outp, inp))
 a = fp (b);
   }

I wonder if under this circumstances (lack of speed, lack of 
parallelism out-of-the-box) it makes any sense to prefer lockstep 
over

the indexed array access.


Re: Lockstep iteration in parallel: Error: cannot have parameter of type `void`

2023-05-20 Thread Sergey via Digitalmars-d-learn

On Saturday, 20 May 2023 at 18:27:47 UTC, Ali Çehreli wrote:

On 5/20/23 04:21, kdevel wrote:
And I've just discovered something. Which one of the following 
is the expected documentation?


  https://dlang.org/library/std/parallelism.html

  https://dlang.org/phobos/std_parallelism.html

What paths did I take to get to those? I hope I will soon be 
motivated enough to fix such quality issues.


Ali


They both. Different versions of documentation generator afaik



Re: Lockstep iteration in parallel: Error: cannot have parameter of type `void`

2023-05-20 Thread Ali Çehreli via Digitalmars-d-learn

On 5/20/23 04:21, kdevel wrote:
> Thanks for your explications!
>
> On Friday, 19 May 2023 at 21:18:28 UTC, Ali Çehreli wrote:
>> [...]
>> - std.range.zip can be used instead but it does not provide 'ref'
>> access to its elements.
>
> How/why does sort [1] work with zipped arrays?

I don't know but wholesale assignment to zip's elements do transfer the 
effect, which sort does while swapping elements. However, copies of 
those range elements do not carry that effect:


import std;

void main() {
auto a = [ 0, 1 ];
auto z = zip(a);
z[0] = z[1];
writeln("worked: ", a);

zip(a).each!(e => e = 42);
writeln("  nope: ", a);
}

And each does not take (ref e) as a parameter at least in that  use case.

>> The following amap example there may be useful for your case but I
>> could not make the types work:
>
> Do you mean using the function pointer does not work?

I simply copied the example code bet there were mismatches between 
float, real, etc.


And I've just discovered something. Which one of the following is the 
expected documentation?


  https://dlang.org/library/std/parallelism.html

  https://dlang.org/phobos/std_parallelism.html

What paths did I take to get to those? I hope I will soon be motivated 
enough to fix such quality issues.


Ali



Re: Lockstep iteration in parallel: Error: cannot have parameter of type `void`

2023-05-20 Thread kdevel via Digitalmars-d-learn

Thanks for your explications!

On Friday, 19 May 2023 at 21:18:28 UTC, Ali Çehreli wrote:

[...]
- std.range.zip can be used instead but it does not provide 
'ref' access to its elements.


How/why does sort [1] work with zipped arrays?


[...]

The following amap example there may be useful for your case 
but I could not make the types work:


Do you mean using the function pointer does not work?


// Same thing, but explicitly allocate an array
// to return the results in.  The element type
// of the array may be either the exact type
// returned by functions or an implicit conversion
// target.
auto squareRoots = new float[numbers.length];
taskPool.amap!sqrt(numbers, squareRoots);


This even seems to work with a static function pointer:

   int main ()
   {
  import std.stdio;
  import std.math;
  import std.parallelism;

  const double [] a = [1., 2., 3., 4.];
  double [] b = [0., 0., 0., 0.];

  writeln (a);
  writeln (b);

  double function (double) fp = 
  taskPool.amap!fp (a, b);

  writeln (a);
  writeln (b);
  return 0;
   }

Using an automatic variable gives a deprecation warning

   main.amap!(const(double)[], double[]).amap` function requires a
   dual-context, which is deprecated

[1] https://dlang.org/library/std/range/zip.html


Re: Lockstep iteration in parallel: Error: cannot have parameter of type `void`

2023-05-19 Thread Ali Çehreli via Digitalmars-d-learn

On 5/19/23 02:17, kdevel wrote:


Should this compile? dmd says


Multiple points:

- lockstep works only with foreach loops but it's not a range.

- std.range.zip can be used instead but it does not provide 'ref' access 
to its elements.


- However, since slices are already references to groups of elements, 
you don't need 'ref' anyway.


- You seem to want to assign to elements in parallel; such functionality 
already exists in std.parallelism.


- Phobos documentation is not very useful these days as it's not clear 
from the following page that there are goodies like amap, asyncBuf, etc. 
It just shows parallel() and a few friends at the top:


  https://dlang.org/phobos/std_parallelism.html

One needs to know to click TaskPool:

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

The following amap example there may be useful for your case but I could 
not make the types work:


// Same thing, but explicitly allocate an array
// to return the results in.  The element type
// of the array may be either the exact type
// returned by functions or an implicit conversion
// target.
auto squareRoots = new float[numbers.length];
taskPool.amap!sqrt(numbers, squareRoots);

// Multiple functions, explicit output range, and
// explicit work unit size.
auto results = new Tuple!(float, real)[numbers.length];
taskPool.amap!(sqrt, log)(numbers, 100, results);
https://dlang.org/phobos/std_parallelism.html#.TaskPool.amap

Ali



Lockstep iteration in parallel: Error: cannot have parameter of type `void`

2023-05-19 Thread kdevel via Digitalmars-d-learn

```
import std.range;
import std.parallelism;

void vec_op (double [] outp, const double [] inp,
   double function (double) f)
{
   foreach (ref a, b; parallel (lockstep (outp, inp)))
  a = f (b);
}
```

Should this compile? dmd says

```
[...]/src/phobos/std/parallelism.d(4094): Error: cannot have 
parameter of type `void`
[...]/src/phobos/std/parallelism.d(4095): Error: cannot have 
parameter of type `void`
[...]/src/phobos/std/parallelism.d(3619): Error: template 
instance `std.parallelism.ParallelForeach!(Lockstep!(double[], 
const(double)[]))` error instantiating
lspar.d(7):instantiated from here: 
`parallel!(Lockstep!(double[], const(double)[]))`

```


Re: vibe.d mongo updateOne error

2023-04-23 Thread Ben Jones via Digitalmars-d-learn

On Friday, 21 April 2023 at 20:46:36 UTC, Ben Jones wrote:
I'm trying to update an app from an older version of Vibe.d to 
a newer version that supports modern Mongo (0.9.7-alpha2)


[...]


Update: https://github.com/vibe-d/vibe.d/pull/2729


vibe.d mongo updateOne error

2023-04-21 Thread Ben Jones via Digitalmars-d-learn
I'm trying to update an app from an older version of Vibe.d to a 
newer version that supports modern Mongo (0.9.7-alpha2)


I'm replacing an older call to collection.update() to 
collection.updateOne() instead.  I had to change the options 
parameter to an updated struct, and it now compiles, but I'm 
getting a runtime error:


```Passed in a regular document into a place where only updates 
are expected. Maybe you want to call replaceOne instead? (this 
update call would otherwise replace the entire matched object 
with the passed in update object)```


On this command

 _reviews.updateOne(["name" : reviewee], ["$push" : ["reviews" : 
ins]], options);


The code 
(https://github.com/vibe-d/vibe.d/blob/a1122a0d5c2e1a19ab6fe318cb47784b76d29336/mongodb/vibe/db/mongo/collection.d#L319) looks like it's checking the query part (the first parameter) to find a dollar sign to tell that it's an update, not a document, but I don't understand why.  This looks like the queries I see in the mongo doc as well as the mongo session store in vibe: https://github.com/vibe-d/vibe.d/blob/83208ee8d824e28f3e35042e0425026765e47d12/mongodb/vibe/db/mongo/sessionstore.d#L101


Any idea what's going wrong?


Re: alias Error: need 'this'

2023-03-19 Thread Ali Çehreli via Digitalmars-d-learn

On 3/19/23 06:49, bomat wrote:

> I can live with the `static`
> solution, I guess.

If you could, you would define it 'static' anyway. :) Because you highly 
likely needed a distinct 'variableWithALongName' member for each 
MyStruct object, that wouldn't work.


> Shouldn't it be the exact same underlying mechanism?

I don't know the answer. Luckily, what you describe is available in 
another form in the language:


ref alias2() {
return myStruct.memberWithALongName;
}

Ali

Unrelated: I find 'myObject' a more correct name for a variable because 
if 'struct' is the definition of a type, 'myStruct' attempts to convey a 
misleading meaning.




Re: alias Error: need 'this'

2023-03-19 Thread Basile B. via Digitalmars-d-learn

On Sunday, 19 March 2023 at 13:49:36 UTC, bomat wrote:
Thanks for the suggested workaround, I can live with the 
`static` solution, I guess.


I still don't understand why it's necessary, though.
Since a `struct` is a value type and, as I understand it, stack 
allocated, what difference does it make to the compiler whether 
I alias `variableWithALongName` or 
`myStruct.memberWithALongName`?

Shouldn't it be the exact same underlying mechanism?

Thanks and regards
bomat


D aliases are for symbols, but what you try to alias is an 
expression.


You might feel that what  you request may work, but that's only a 
very particular case. Generally expressions cannot be aliased 
because without context they become polymorphic (or erather 
polysemous).


Re: alias Error: need 'this'

2023-03-19 Thread bomat via Digitalmars-d-learn

On Sunday, 19 March 2023 at 12:29:19 UTC, Salih Dincer wrote:
It is possible to achieve the convenience you want to achieve 
in 2 ways. One of them is to use a static member but if not, to 
use an alias inside the container.


Thanks for the suggested workaround, I can live with the `static` 
solution, I guess.


I still don't understand why it's necessary, though.
Since a `struct` is a value type and, as I understand it, stack 
allocated, what difference does it make to the compiler whether I 
alias `variableWithALongName` or `myStruct.memberWithALongName`?

Shouldn't it be the exact same underlying mechanism?

Thanks and regards
bomat


Re: alias Error: need 'this'

2023-03-19 Thread Salih Dincer via Digitalmars-d-learn

On Sunday, 19 March 2023 at 11:52:50 UTC, bomat wrote:
It works fine with the `int` variable, but with the struct 
member I get a compilation error:

```
Error: need `this` for `memberWithALongName` of type `int`
```

What is that supposed to mean?


It is possible to achieve the convenience you want to achieve in 
2 ways. One of them is to use a static member but if not, to use 
an alias inside the container. For example:


```d
struct MyStruct
{
  int memberWithALongName;
  alias ln = memberWithALongName;

  static string str;
}

void main()
{
  auto myStruct = MyStruct(1);
   myStruct.ln = 2;
  alias alias2 =  MyStruct.str;
  alias2 = "2";

  import std.conv : text;
  assert(myStruct.ln.text == alias2);
}
```
SDB@79


alias Error: need 'this'

2023-03-19 Thread bomat via Digitalmars-d-learn

Hi,

I read about aliases today and thought it would be handy for 
shortening repeated access to struct members.

However, I'm clearly missing something.
Here's some example code:

```
int variableWithALongName = 42;
alias alias1 = variableWithALongName;
alias1 = 43;
assert(variableWithALongName == 43);

struct MyStruct
{
int memberWithALongName;
}
MyStruct myStruct;
myStruct.memberWithALongName = 42;
alias alias2 = myStruct.memberWithALongName;
alias2 = 43; // does not compile, see below
assert(myStruct.memberWithALongName == 43);
```

It works fine with the `int` variable, but with the struct member 
I get a compilation error:

```
Error: need `this` for `memberWithALongName` of type `int`
```

What is that supposed to mean?

Thanks
bomat


Re: Template alias parameter: error: need 'this' for ...

2023-02-24 Thread Elfstone via Digitalmars-d-learn
On Friday, 24 February 2023 at 15:28:18 UTC, Steven Schveighoffer 
wrote:

On 2/24/23 7:00 AM, Elfstone wrote:


Seems like the same bug is still there after ten years.



`static` should not affect module-level functions, but also, 
this code should work without `static`.


Reported, not sure if there's a previous bug, it was hard to 
come up with a good description:


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

-Steve


It was marked duplicate. I read the comments to the previous 
issue and felt like reading C++ discussions, except C++ is a lot 
better documented.


Anyway surely `__traits(getAttributes, Bar.t)` compiles. The 
compiler should "need 'this'" when it actually need 'this' - 
unless there are attributes that can be bound to 'this'.




Re: Template alias parameter: error: need 'this' for ...

2023-02-24 Thread Paul Backus via Digitalmars-d-learn

On Friday, 24 February 2023 at 14:22:17 UTC, user1234 wrote:
you can break using `goto`, restore `static` everywhere, and 
using local introspection determine whether the result exists.


```d
struct Bar
{
@("hello") int t;
}

static bool hasAttribute(alias F, T)()
{
static foreach (a; __traits(getAttributes, F))
{
static if (is(typeof(a) : T))
{
enum result = true;
goto L0;
}
}
L0:
static if (is(typeof(result)))
return result;
else
return false;
}

void main()
{
import std.stdio;

writeln(hasAttribute!(Bar.t, string));
}
```


Unfortunately there is a serious bug in this code. Take a look at 
what happens when you try it with this `struct Bar`:


```d
struct Bar
{
@("hello") @("goodbye") int t;
}
```


Re: Template alias parameter: error: need 'this' for ...

2023-02-24 Thread Steven Schveighoffer via Digitalmars-d-learn

On 2/24/23 7:00 AM, Elfstone wrote:


Seems like the same bug is still there after ten years.



`static` should not affect module-level functions, but also, this code 
should work without `static`.


Reported, not sure if there's a previous bug, it was hard to come up 
with a good description:


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

-Steve


Re: Template alias parameter: error: need 'this' for ...

2023-02-24 Thread user1234 via Digitalmars-d-learn

On Friday, 24 February 2023 at 12:00:41 UTC, Elfstone wrote:

Seems like the same bug is still there after ten years.

```d
struct Bar
{
@("hello") int t;
}

static bool hasAttribute(alias F, T)()
{
bool result = false;
foreach (a; __traits(getAttributes, F))
{
static if (is(typeof(a) : T))
{
result = true; // couldn't simply return true, 'cause the 
compiler complains about "unreachable code".

}
}
return result;
}

void main()
{
import std.stdio;

writeln(hasAttribute!(Bar.t, string));
}
```


you can break using `goto`, restore `static` everywhere, and 
using local introspection determine whether the result exists.


```d
struct Bar
{
@("hello") int t;
}

static bool hasAttribute(alias F, T)()
{
static foreach (a; __traits(getAttributes, F))
{
static if (is(typeof(a) : T))
{
enum result = true;
goto L0;
}
}
L0:
static if (is(typeof(result)))
return result;
else
return false;
}

void main()
{
import std.stdio;

writeln(hasAttribute!(Bar.t, string));
}
```


Template alias parameter: error: need 'this' for ...

2023-02-24 Thread Elfstone via Digitalmars-d-learn

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

On Saturday, 24 August 2013 at 11:47:43 UTC, Matej Nanut wrote:
On Friday, 23 August 2013 at 22:54:33 UTC, Jonathan M Davis 
wrote:
Because without static it's a member variable, which means 
that you have to
have a constructed object to access it (since it's part of the 
object). When
you declare a variable in a class or struct static, then 
there's only one for
the entire class or struct, so it can be accessed without an 
object. And when
you do StructName.var or ClassName.var your accessing the 
variable via the
struct or class rather than an object, so the variable must be 
static.


- Jonathan M Davis


But I declared the template static, not the variable.

Is there a better way to pass a ‘member get’ expression to a 
template?


I need this for calling ‘.offsetof’ on it, and for checking if 
the member's parent is a certain struct type.


Seems like the same bug is still there after ten years.


struct Bar
{
@("hello") int t;
}

static bool hasAttribute(alias F, T)()
{
bool result = false;
foreach (a; __traits(getAttributes, F))
{
static if (is(typeof(a) : T))
{
result = true; // couldn't simply return true, 'cause the 
compiler complains about "unreachable code".

}
}
return result;
}

void main()
{
import std.stdio;

writeln(hasAttribute!(Bar.t, string));
}


Wrong compiler error message regarding overload sets

2023-02-07 Thread Andre Pany via Digitalmars-d-learn

Hi,

for the source code below, the compiler says:

app.d(26): constructor `app.TObject.this` hides base class 
function `app.DelphiObject.this`
app.d(26): add `alias this = app.DelphiObject.this` to 
`app.TObject`'s body to merge the overload sets


But if I add `alias this = app.DelphiObject.this` then the 
compiler says, the syntax is wrong:


Error: identifier or `new` expected following `.`, not `this`
app.d(20): Error: cannot use syntax `alias this = 
app.DelphiObject`, use `alias app.DelphiObject this` instead


But If I use `alias app.DelphiObject this` then another error is 
shown:

app.d(22): Error: no identifier for declarator `app.DelphiObject`
app.d(22):`this` is a keyword, perhaps append `_` to make 
it an identifier


What is the correct "alias this" syntax to be able to access the 
super constructor (DelphiObjectReference)?


``` d
struct DelphiObjectReference
{
ptrdiff_t reference;
}

mixin template PascalClass(string name)
{
this (DelphiObjectReference r){}
}

class DelphiObject
{
this(){}
this (DelphiObjectReference r){}
}

class TObject : DelphiObject
{
mixin PascalClass!("System.TObject");

this(TObject AOwner){}
}

void main()
{
new TObject(DelphiObjectReference(123));
}
```

Kind regards
André


Re: Error "Outer Function Context is Needed" when class declared in unittest

2023-01-05 Thread Vijay Nayar via Digitalmars-d-learn

On Thursday, 5 January 2023 at 16:41:32 UTC, Adam D Ruppe wrote:

On Thursday, 5 January 2023 at 16:38:49 UTC, Vijay Nayar wrote:
Does that class inherit the scope of the function it is 
inside, similar to how an inner class does with an outer class?


yup. They can see the local variables from the function.


Glad to learn that. Having worked many years in the Java world, 
where basically "class" and "scope" are nearly synonymous, I just 
assumed that classes could only get the scope of other classes, 
it never occurred to me that it could get a scope from a function.


Thanks for the explanation!


Re: Error "Outer Function Context is Needed" when class declared in unittest

2023-01-05 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 5 January 2023 at 16:38:49 UTC, Vijay Nayar wrote:
Does that class inherit the scope of the function it is inside, 
similar to how an inner class does with an outer class?


yup. They can see the local variables from the function.




Re: Error "Outer Function Context is Needed" when class declared in unittest

2023-01-05 Thread Vijay Nayar via Digitalmars-d-learn

On Thursday, 5 January 2023 at 13:47:24 UTC, Adam D Ruppe wrote:

On Thursday, 5 January 2023 at 13:27:23 UTC, Vijay Nayar wrote:
Why is this error only found when declaring a class in the 
unittest?


A unittest is just a special function, it can run code and have 
local variables.


classes and structs declared inside it have access to those 
local contexts, which it calls the outer function context.


Make the outer class `static` too to lift it out of this and 
your error should go away.


That's very informative, I didn't realize that `unittest` is 
actually a function.


It raises another question one step deeper, what does it mean to 
define a non-static class within a function? Does that class 
inherit the scope of the function it is inside, similar to how an 
inner class does with an outer class?


Re: Error "Outer Function Context is Needed" when class declared in unittest

2023-01-05 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 5 January 2023 at 13:27:23 UTC, Vijay Nayar wrote:
Why is this error only found when declaring a class in the 
unittest?


A unittest is just a special function, it can run code and have 
local variables.


classes and structs declared inside it have access to those local 
contexts, which it calls the outer function context.


Make the outer class `static` too to lift it out of this and your 
error should go away.


Error "Outer Function Context is Needed" when class declared in unittest

2023-01-05 Thread Vijay Nayar via Digitalmars-d-learn
I've run into an unexpected problem that only seems to happen in 
unittests, but not outside of them. Consider the following 
example:


```
unittest {
  class Ab {
int a;
string b;

static class Builder {
  int _a;
  string _b;
  Builder a(int a) {
_a = a;
return this;
  }
  Builder b(string b) {
_b = b;
return this;
  }
  Ab build() {
Ab t = new Ab();
t.a = _a;
t.b = _b;
return t;
  }
}
  }

  Ab ab = new Ab.Builder()
  .a(1)
  .b("ham")
  .build();
  assert(ab.a == 1);
  assert(ab.b == "ham");
}
```

This fails to compile with the following error:
```
Generating test runner configuration 'builder-test-library' for 
'library' (library).
Starting Performing "unittest" build using /usr/bin/dmd for 
x86_64.
Building builder ~master: building configuration 
[builder-test-library]
source/builder.d(58,16): Error: outer function context of 
`builder.__unittest_L41_C1` is needed to `new` nested class 
`builder.__unittest_L41_C1.Ab`

Error /usr/bin/dmd failed with exit code 1.
```

However, if I move the class definition outside of the unittest 
block, then everything works fine:

```
class Ab {
  int a;
  string b;

  static class Builder {
int _a;
string _b;
Builder a(int a) {
  _a = a;
  return this;
}
Builder b(string b) {
  _b = b;
  return this;
}
Ab build() {
  Ab t = new Ab();
  t.a = _a;
  t.b = _b;
  return t;
}
  }
}

unittest {
  Ab ab = new Ab.Builder()
  .a(1)
  .b("ham")
  .build();
  assert(ab.a == 1);
  assert(ab.b == "ham");
}
```

```
 Generating test runner configuration 
'builder-test-library' for 'library' (library).
Starting Performing "unittest" build using /usr/bin/dmd for 
x86_64.
Building builder ~master: building configuration 
[builder-test-library]

 Linking builder-test-library
 Running builder-test-library
2 modules passed unittests
```

Why is this error only found when declaring a class in the 
unittest?


Re: dChar Error

2022-12-30 Thread Salih Dincer via Digitalmars-d-learn

On Saturday, 31 December 2022 at 02:15:56 UTC, Ali Çehreli wrote:

On 12/30/22 17:22, Salih Dincer wrote:

> I guess there is no other way but to overload.

Since the bodies of all three overloads are the same except 
some types, they can easily be templatized.


You took the trouble, thanks, but there is a special reason why I 
use union.  If we want, we can write dynamic version without 
using std.traits:


```d
struct Values(T, size_t len = 1)
{
  union
  {
T[len] data;
ubyte[T.sizeof * len] bytes;
  }

  string toString()
  {
import std.format;
return format("%s: %(%02X-%)", data, bytes);
  }
}

  alias Char = Values!char;
  alias Wchar = Values!wchar;
  alias Dchar = Values!dchar;

void main()
{
  import std.stdio : writeln;

  Char[] str1;
  str1 ~= Char('B');
  str1 ~= Char('E');
  str1 ~= Char('$');
  str1.writeln;

  Wchar[] str2;
  str2 ~= Wchar('β');
  str2 ~= Wchar('€');
  str2 ~= Wchar('Ş');
  str2.writeln;

  Dchar[] str3;
  str3 ~= Dchar('β');
  str3 ~= Dchar('€');
  str3 ~= Dchar('$');
  str3.writeln("\n");

  Fun!"β€$".writeln;
}
/*
  [B: 42, E: 45, $: 24]
  [β: B2-03, €: AC-20, Ş: 5E-01]
  [β: B2-03-00-00, €: AC-20-00-00, $: 24-00-00-00]

  β€$: CE-B2-E2-82-AC-24
*/
```
However, I would like to draw your attention to the last line.  
Yeah, I won't be able to do that because it's New Year's Eve.  
But the line is like mixed mode because of the non-char data it 
contains, right?


Happy New Year...



Re: dChar Error

2022-12-30 Thread Ali Çehreli via Digitalmars-d-learn

On 12/30/22 17:22, Salih Dincer wrote:

> I guess there is no other way but to overload.

Since the bodies of all three overloads are the same except some types, 
they can easily be templatized.


> This is both the safest and the fastest.

I didn't think Values is fast with string copies that it makes. ;) I 
think it was only for showing the byte values but you can do the same by 
casting to ubyte[] as well.


Also, your Fun could work only with string literals; so I used function 
parameters.


import std.traits : isSomeString;

// isSomeString may or may not be useful below. (?)

auto Fun(S)(S str)
if (isSomeString!S) {
import std.traits : Unqual;
import std.conv : to;

alias T = Unqual!S;

// Note: The following may or may not copy the string
//   depending on whether S is the same as T.
return str.to!T;
}

void printBytes(S)(S str) {
import std.stdio : writefln;
import std.conv  : to;

// The following cast does not copy anything.
writefln!"%(%02X-%)"(cast(ubyte[])str);
}

void main()
{
printBytes(Fun("β€Ş"));  // CE-B2-E2-82-AC-C5-9E
printBytes(Fun("β€Ş"w)); // B2-03-AC-20-5E-01
printBytes(Fun("β€Ş"d)); // B2-03-00-00-AC-20-00-00-5E-01-00-00
}

Ali



Re: dChar Error

2022-12-30 Thread Salih Dincer via Digitalmars-d-learn

On Saturday, 31 December 2022 at 00:42:50 UTC, Salih Dincer wrote:

... it possible to infer


Let me save you the torment of code duplication 

Thanks everyone.  Yes, I guess there is no other way but to 
overload.  This is both the safest and the fastest.  It's also 
short enough like this:


```d
  // D 2.0.83 or higher

  import std.stdio : writeln;
  import std.conv  : to;

auto Fun(string str)() {
  auto result = Values!(char, str.length)();
  result.data = str.to!(char[]);
  return result;
}

auto Fun(wstring str)() {
  auto result = Values!(wchar, str.length)();
  result.data = str.to!(wchar[]);
  return result;
}

auto Fun(dstring str)() {
  auto result = Values!(dchar, str.length)();
  result.data = str.to!(dchar[]);
  return result;
}

struct Values(T, size_t len) {
  union {
T[len] data;
ubyte[T.sizeof * len] bytes;
  }
  string toString() {
import std.format;
return format("%s: %(%02X-%)", data, bytes);
  }
}

void main()
{
  Fun!"β€Ş".writeln;  // β€Ş: CE-B2-E2-82-AC-C5-9E
  Fun!"β€Ş"w.writeln; // β€Ş: B2-03-AC-20-5E-01
  Fun!"β€Ş"d.writeln; // B2-03-00-00-AC-20-00-00-5E-01-00-00
}
```

SDB@79




Re: dChar Error

2022-12-30 Thread Salih Dincer via Digitalmars-d-learn

On Friday, 30 December 2022 at 22:02:41 UTC, Ali Çehreli wrote:

> But I couldn't find if the target will be mutable, but I
think it will
> be,

The target will always be the type the programmer specifies 
explicitly. (dchar[] in this case.)


I have one more little question! Is it possible to infer the 
string without the type the programmer specifies explicitly in 
the template below?


```d

template Fun(dstring str)/*
template Fun(T)(T str)/* like this */
{
  import std.traits : Unconst;
  alias T = Unconst!(typeof(str[0]));

  auto Fun()
  {
import std.conv : to;

auto result = Result();
    result.data = str.to!(T[]);

    return result;
  }
  
  struct Result
  {
union
{
  T[str.length] data;
  ubyte[T.sizeof * str.length] bytes;
}
string toString()
{
  import std.format;
  return format("%s: %(%02X-%)", data, bytes);
}
  }
}

void main()
{
  import std.stdio : writeln;
  Fun!"β€Ş"w.writeln; // type1: wstring
  Fun!"β€Ş"d.writeln; // type2: dstring
}
```
That is, the compiler can/must infer between type 1-2 or type 
3(string) that it knows at compile time, right?


SDB@79


Re: dChar Error

2022-12-30 Thread matheus via Digitalmars-d-learn

On Friday, 30 December 2022 at 22:02:41 UTC, Ali Çehreli wrote:

On 12/30/22 13:54, matheus wrote:

> But yes I think it will generate a copy (mutable) based on
this test:

In this case it does copy but in the case of dchar[] to 
dchar[], there will be no copy. Similarly, there is no copy 
from immutable to immutable.


Very interesting I did some testing and you are right. So better 
to stick with .dup!


Thanks for the info,

Matheus.



Re: dChar Error

2022-12-30 Thread Ali Çehreli via Digitalmars-d-learn

On 12/30/22 13:54, matheus wrote:

> But yes I think it will generate a copy (mutable) based on this test:

In this case it does copy but in the case of dchar[] to dchar[], there 
will be no copy. Similarly, there is no copy from immutable to immutable.


> the address is different

Good test. :)

> But I couldn't find if the target will be mutable, but I think it will
> be,

The target will always be the type the programmer specifies explicitly. 
(dchar[] in this case.)


Ali



Re: dChar Error

2022-12-30 Thread matheus via Digitalmars-d-learn

On Friday, 30 December 2022 at 15:28:05 UTC, Salih Dincer wrote:
... In this case, std.conv.to can be used for mutable dchars, 
right? For example, is this solution the right approach?


```d
auto toDchar(S)(inout S str) {
  import std.conv : to;
  return str.to!(dchar[]);
}

void main() {
  auto str3 = "ÜÇ ON "d;
  auto str4 = "BİR İKİ BEŞ "d.dup;
  auto str5 = "DÖRT ALTI YEDİ ".toDchar;

  //str5.fun(5);
}
```


Unfortunately I can't say because I'm not a skilled D programmer, 
I use mostly as a C on steroids.


But yes I think it will generate a copy (mutable) based on this 
test:


void main(){
import std.stdio;
import std.conv;

auto str1 = "BİR İKİ BEŞ ";
auto str2 = str1;
auto str3 = str2.to!(dchar[]);

writeln(str1, ", ", str1.ptr);
writeln(str2, ", ", str2.ptr);
writeln(str3, ", ", str3.ptr);
str3[0] = 'A';
writeln(str3, ", ", str3.ptr);

}

It prints:

BİR İKİ BEŞ , 5641226D8200
BİR İKİ BEŞ , 5641226D8200
BİR İKİ BEŞ , 7FB466EAE000
AİR İKİ BEŞ , 7FB466EAE000

So for str2 = str1 it is just a case of passing the reference, 
and both are pointing to the same address, while in the case of: 
"str3 = str2.to!(dchar[]);", the address is different, and 
accepts changing its content (str3[0] = 'A').


In the docs: https://dlang.org/phobos/std_conv.html#to

"String to string conversion works for any two string types 
having (char, wchar, dchar) character widths and any combination 
of qualifiers (mutable, const, or immutable)."


But I couldn't find if the target will be mutable, but I think it 
will be, unless explicitly otherwise with a cast I believe.


Anyway I would wait and see if someone more skilled could shed a 
light.


Matheus.


Re: dChar Error

2022-12-30 Thread Salih Dincer via Digitalmars-d-learn

On Friday, 30 December 2022 at 11:05:07 UTC, matheus wrote:

Are you sure about that?


Thank you for your answer. You contributed to the project I was 
working on. In this case, std.conv.to can be used for mutable 
dchars, right? For example, is this solution the right approach?


```d
auto toDchar(S)(inout S str) {
  import std.conv : to;
  return str.to!(dchar[]);
}

void main() {
  auto str3 = "ÜÇ ON "d;
  auto str4 = "BİR İKİ BEŞ "d.dup;
  auto str5 = "DÖRT ALTI YEDİ ".toDchar;

  //str5.fun(5);
}
```

SDB@79


Re: dChar Error

2022-12-30 Thread matheus via Digitalmars-d-learn

On Friday, 30 December 2022 at 10:03:20 UTC, Salih Dincer wrote:

On Friday, 30 December 2022 at 09:29:16 UTC, novice2 wrote:
On Friday, 30 December 2022 at 04:43:48 UTC, Salih Dincer 
wrote:

  ...
  // example one:
  char[] str1 = "cur:€_".dup;
  ...
  // example two:
  dchar[] str2 = cast(dchar[])"cur:€_"d;
  ...
SDB@79


why you use .dup it example one, but not use in example two?

dchar[] str2 = cast(dchar[])"cur:€_"d.dup;


If I do not use .dup in the 1st example and convert as 
cast(char[]), it gives an error. However, in the 2nd example 
using .dup does nothing. It's not working anyway!

...


Are you sure about that?

Because replacing this:

dchar[] str2 = cast(dchar[])"cur:€_"d;

with this:

dchar[] str2 = (cast(dchar[])"cur:€_").dup;

Worked for me:

8: [€_]
[cur:$  _]
6: [€_]
[cur$ _]

A small example of the problem:

import std.stdio;

void main(){
  dchar[] str1 = (cast(dchar[])"cur:€_").dup;
  dchar[] str2 = (cast(dchar[])"cur:€_");

  str1[0] = '1';
  //str2[0] = '1'; // this will give: Error: program killed by 
signal 11

}

Matheus.


Re: dChar Error

2022-12-30 Thread Salih Dincer via Digitalmars-d-learn

On Friday, 30 December 2022 at 09:29:16 UTC, novice2 wrote:

On Friday, 30 December 2022 at 04:43:48 UTC, Salih Dincer wrote:

  ...
  // example one:
  char[] str1 = "cur:€_".dup;
  ...
  // example two:
  dchar[] str2 = cast(dchar[])"cur:€_"d;
  ...
SDB@79


why you use .dup it example one, but not use in example two?

dchar[] str2 = cast(dchar[])"cur:€_"d.dup;


If I do not use .dup in the 1st example and convert as 
cast(char[]), it gives an error. However, in the 2nd example 
using .dup does nothing. It's not working anyway!


On Friday, 30 December 2022 at 05:46:32 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
Of course; I cannot see anything else that could cause this in 
the assembly either.


I'm not sure I understand this issue.

SDB@79



Re: dChar Error

2022-12-30 Thread novice2 via Digitalmars-d-learn

On Friday, 30 December 2022 at 04:43:48 UTC, Salih Dincer wrote:

  ...
  // example one:
  char[] str1 = "cur:€_".dup;
  ...
  // example two:
  dchar[] str2 = cast(dchar[])"cur:€_"d;
  ...
SDB@79


why you use .dup it example one, but not use in example two?

dchar[] str2 = cast(dchar[])"cur:€_"d.dup;


Re: dChar Error

2022-12-29 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 30/12/2022 6:37 PM, Salih Dincer wrote:
On Friday, 30 December 2022 at 04:54:39 UTC, Richard (Rikki) Andrew 
Cattermole wrote:


So when you duplicated it, it was no longer in ROM, and therefore 
writable.


There is no such thing as a ROM within a function.


But a function can reference things in ROM, and a function itself can 
and should be held within ROM.


Because str is a 
reference and slc is a local copy, right?


It is a reference to memory that is in ROM. No, it is not a copy of the 
memory, only of the reference.


You shouldn't be casting away immutable btw, (which is what string is!).

Have you tried running the 
code?  Okay, no string literals:


Of course; I cannot see anything else that could cause this in the 
assembly either.


Re: dChar Error

2022-12-29 Thread Salih Dincer via Digitalmars-d-learn
On Friday, 30 December 2022 at 04:54:39 UTC, Richard (Rikki) 
Andrew Cattermole wrote:


So when you duplicated it, it was no longer in ROM, and 
therefore writable.


There is no such thing as a ROM within a function.  Because str 
is a reference and slc is a local copy, right?  Have you tried 
running the code?  Okay, no string literals:


```d
void main()
{
  // example one:
  char[] str1 = "cur:€_".dup;
  str1.length.write(": "); // 8:
  str1[4..$].writefln!"[%s]"; // [€_]
    
  char[] slc1 = "$  _".dup;
  str1.replaceRight(slc1);
  str1.writefln!"[%s]"; // [cur:$  _]

  // example two:
  dchar[] str2 = cast(dchar[])"cur:€_"d;
  str2.length.write(": "); // 6:
  str2[4..$].writefln!"[%s]"; // [€_]
  
  dchar[] slc2 = cast(dchar[])"$ _"d;
  str2.replaceRight(slc2);
  str2.writefln!"[%s]";
}
```

SDB@79


Re: dChar Error

2022-12-29 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

Because, string literals are in Read Only Memory (or should be anyway).

If you write to ROM, it'll of course error by the CPU.

So when you duplicated it, it was no longer in ROM, and therefore writable.


dChar Error

2022-12-29 Thread Salih Dincer via Digitalmars-d-learn

Hi All,

What is causing the error in the code snippet below?

```d
void replaceRight(S)(ref S[] str, S[] slc)
{
  size_t len1 = slc.length,
         len2 = str[len1..$].length;
  assert(len1 == len2);
  str[len1..$] = slc;
}

import std.stdio;

void main()
{
  // example one:
  char[] str1 = "cur:€_".dup;
  str1.length.write(": "); // 8:
  str1[4..$].writefln!"[%s]"; // [€_]
    
  str1.replaceRight("$  _".dup);
  str1.writefln!"[%s]"; // [cur:$  _]

  // example two:
  dchar[] str2 = cast(dchar[])"cur:€_"d;
  str2.length.write(": "); // 6:
  str2[4..$].writefln!"[%s]"; // [€_]
  
  str2.replaceRight(cast(dchar[])"$ _"d);
  str2.writefln!"[%s]"; // Error--^
} /* Prints:
  8: [€_]
  [cur:$  _]
  6: [€_]
  Error: program killed by signal 11
*/
```
Why does replaceRight() work fine with a char array, but not a 
dchar array?  Whereas, rvalue and lvalue lengths are equal to 
each other!


SDB@79


Re: A strange DMD error

2022-11-02 Thread Keivan Shah via Digitalmars-d-learn

On Tuesday, 1 November 2022 at 17:05:03 UTC, ryuukk_ wrote:

This reminds me of an issue i reported last year...

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


This seems to be very similar to the bug I am facing, mostly the 
same underlying issue. Should we somehow link the 2 issues and 
escalate?


Link to my issue: 
[#23450](https://issues.dlang.org/show_bug.cgi?id=23450)


Re: A strange DMD error

2022-11-02 Thread Keivan Shah via Digitalmars-d-learn
On Tuesday, 1 November 2022 at 16:39:57 UTC, Steven Schveighoffer 
wrote:

100% this is a bug in DMD. It should be filed.

I ran some more tests, removing almost any of the parameters or 
changing their types seems to avoid the problem.


I also added a parameter name for the second parameter, and DMD 
appears to be in this case passing the parameters in the wrong 
order (t1 is actually tt, t2 is null)


You can also remove the `import std`, just the assert is enough.

Please file if you can: https://issues.dlang.org

-Steve


Hey, have already filled an issue: 
[#23450](https://issues.dlang.org/show_bug.cgi?id=23450)





Re: A strange DMD error

2022-11-01 Thread ryuukk_ via Digitalmars-d-learn

This reminds me of an issue i reported last year...

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




Re: A strange DMD error

2022-11-01 Thread Steven Schveighoffer via Digitalmars-d-learn

On 11/1/22 11:40 AM, Keivan Shah wrote:

Hello,

Today I came across a strange bug while using D with `dmd`. I have still 
not been able to figure out under what conditions does it happen but it 
seems to be a DMD related bug to me. Here is a reproducible snippet of 
the code


```D
import std;

alias DG = void delegate();

class TType
{
}

class MyClass
{
     this(TType t1, TType, double, double[2], double, double, DG, TType, 
TType,
     DG, DG, DG, double, double, double, double, double, ulong, 
bool)

     {
     assert(t1 is null); // I am passing null so should be null!
     // NOTE: Seems to work in LDC but fails in DMD.
     writeln("No Bug!");
     }
}

void main()
{
     auto tt = new TType;

     new MyClass(null, tt, 0, [0, 0], 0, 0, null, null, null, null, 
null, null,

     0, 0, 0, 0, 0, 0, false);
}
```
The code gives an assertion failure on the current versions of dmd 
(reproducible on [run.dlang.io](https://run.dlang.io) as well) and does 
not happen when using LDC. The bug seems to be sensitive to the number 
of arguments and their types making it reproducible only in very limited 
cases. I have tried my best to reduce it to minimum but still does 
require these many arguments. The end results seems to me like variables 
are shifted i.e. variable 1 gets value of variable 2 and so on, but 
don't have enough proof to support this.


100% this is a bug in DMD. It should be filed.

I ran some more tests, removing almost any of the parameters or changing 
their types seems to avoid the problem.


I also added a parameter name for the second parameter, and DMD appears 
to be in this case passing the parameters in the wrong order (t1 is 
actually tt, t2 is null)


You can also remove the `import std`, just the assert is enough.

Please file if you can: https://issues.dlang.org

-Steve



Re: A strange DMD error

2022-11-01 Thread Tejas via Digitalmars-d-learn

On Tuesday, 1 November 2022 at 15:49:54 UTC, Keivan Shah wrote:

On Tuesday, 1 November 2022 at 15:42:43 UTC, Imperatorn wrote:

On Tuesday, 1 November 2022 at 15:40:04 UTC, Keivan Shah wrote:

Hello,

Today I came across a strange bug while using D with `dmd`. I 
have still not been able to figure out under what conditions 
does it happen but it seems to be a DMD related bug to me. 
Here is a reproducible snippet of the code


[...]


Could be there's some restriction in DMD on number of 
arguments.


May I ask if this was just an experiment? I hope you're not 
having code like that in the wild 


Possible, but I think I have had code with more arguments than 
this and it has worked 


Unfortunately, not an experiment. Although have replaced the 
types so seems silly now, this is part of my constructor for a 
huge co-coordinator class that takes too many configurable 
start time parameters and so need to pass these many arguments.


Keivan


Regarding the too many configurable parameters, the general 
advice is to group all of the params into a `struct` and pass 
that instead as argument to constructor



Pretty wild bug though, definitely a backend thing




Re: A strange DMD error

2022-11-01 Thread Keivan Shah via Digitalmars-d-learn

On Tuesday, 1 November 2022 at 16:06:44 UTC, Imperatorn wrote:


Hehe.

One simple thing you could do is to create a struct instead for 
you params and pass that


Yeah, can do, thanks for the suggestion. But anyways still want 
to see if anyone else has seen this issue, or has a clue about 
what could be happening here. Seems like a rare issue and took up 
too much of my time so better if it's solved or at least 
documented somewhere in the meantime. I have filed an issue for 
this now: https://issues.dlang.org/show_bug.cgi?id=23450


Re: A strange DMD error

2022-11-01 Thread Imperatorn via Digitalmars-d-learn

On Tuesday, 1 November 2022 at 15:49:54 UTC, Keivan Shah wrote:

On Tuesday, 1 November 2022 at 15:42:43 UTC, Imperatorn wrote:

On Tuesday, 1 November 2022 at 15:40:04 UTC, Keivan Shah wrote:

[...]


Could be there's some restriction in DMD on number of 
arguments.


May I ask if this was just an experiment? I hope you're not 
having code like that in the wild 


Possible, but I think I have had code with more arguments than 
this and it has worked 


Unfortunately, not an experiment. Although have replaced the 
types so seems silly now, this is part of my constructor for a 
huge co-coordinator class that takes too many configurable 
start time parameters and so need to pass these many arguments.


Keivan


Hehe.

One simple thing you could do is to create a struct instead for 
you params and pass that


Re: A strange DMD error

2022-11-01 Thread Keivan Shah via Digitalmars-d-learn

On Tuesday, 1 November 2022 at 15:42:43 UTC, Imperatorn wrote:

On Tuesday, 1 November 2022 at 15:40:04 UTC, Keivan Shah wrote:

Hello,

Today I came across a strange bug while using D with `dmd`. I 
have still not been able to figure out under what conditions 
does it happen but it seems to be a DMD related bug to me. 
Here is a reproducible snippet of the code


[...]


Could be there's some restriction in DMD on number of arguments.

May I ask if this was just an experiment? I hope you're not 
having code like that in the wild 


Possible, but I think I have had code with more arguments than 
this and it has worked 


Unfortunately, not an experiment. Although have replaced the 
types so seems silly now, this is part of my constructor for a 
huge co-coordinator class that takes too many configurable start 
time parameters and so need to pass these many arguments.


Keivan


Re: A strange DMD error

2022-11-01 Thread Imperatorn via Digitalmars-d-learn

On Tuesday, 1 November 2022 at 15:40:04 UTC, Keivan Shah wrote:

Hello,

Today I came across a strange bug while using D with `dmd`. I 
have still not been able to figure out under what conditions 
does it happen but it seems to be a DMD related bug to me. Here 
is a reproducible snippet of the code


[...]


Could be there's some restriction in DMD on number of arguments.

May I ask if this was just an experiment? I hope you're not 
having code like that in the wild 


A strange DMD error

2022-11-01 Thread Keivan Shah via Digitalmars-d-learn

Hello,

Today I came across a strange bug while using D with `dmd`. I 
have still not been able to figure out under what conditions does 
it happen but it seems to be a DMD related bug to me. Here is a 
reproducible snippet of the code


```D
import std;

alias DG = void delegate();

class TType
{
}

class MyClass
{
this(TType t1, TType, double, double[2], double, double, DG, 
TType, TType,
DG, DG, DG, double, double, double, double, double, 
ulong, bool)

{
assert(t1 is null); // I am passing null so should be 
null!

// NOTE: Seems to work in LDC but fails in DMD.
writeln("No Bug!");
}
}

void main()
{
auto tt = new TType;

new MyClass(null, tt, 0, [0, 0], 0, 0, null, null, null, 
null, null, null,

0, 0, 0, 0, 0, 0, false);
}
```
The code gives an assertion failure on the current versions of 
dmd (reproducible on [run.dlang.io](https://run.dlang.io) as 
well) and does not happen when using LDC. The bug seems to be 
sensitive to the number of arguments and their types making it 
reproducible only in very limited cases. I have tried my best to 
reduce it to minimum but still does require these many arguments. 
The end results seems to me like variables are shifted i.e. 
variable 1 gets value of variable 2 and so on, but don't have 
enough proof to support this.


I just wanted some help on the best way to avoid this bug in my 
code and maybe some clue on what causes the error in the first 
place and how should I go about reporting this.


Keivan


Re: Error

2022-10-31 Thread Johann via Digitalmars-d-learn

```d
writeln (getSize(rom))
```
reports 478 bytes but since you work with ushorts (why? as far as 
I can see, this is a 8 bit machine) you convert the read(rom) 
into ushorts, which is only half in size:


```d
writeln (cast(ushort[])read(rom));
```

gives you 478/2 = 239 bytes

```d
this.memory[memStart..memStart + romSize] = 
cast(ushort[])read(rom);

```

fails because both ranges have different sizes.


Error

2022-10-30 Thread Decabytes via Digitalmars-d-learn
I'm trying to write a chip8 emulator. I'm at the step where I 
load the rom into the memory. According to the 
[documentation](http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#3.0) each instruction is 2 bytes and max memory addressed is 4K. So I define the memory as an array of ushorts.


```D
struct Chip8
{
ushort[4096] memory;
...
```

To load in the rom I do this

```D
void read(string rom)
{
import std.file : exists, getSize, read;

if (exists(rom))
{
writeln("Loading the Rom");
auto romSize = getSize(rom);
writeln("The Rom size is : ", romSize);
if (romSize > this.memory.length - memStart)
writefln("Rom Size is too big! romSize = %s MemSize = %s", 
romSize,

this.memory.length - memStart);

else
{

// is it possible to to!int[] or do I have to 
use a cast here?
this.memory[memStart..memStart + romSize] = 
cast(ushort[])read(rom);


}
}
else
{
writeln("Cannot read ", rom);
}

    }
```

But I get a range violation error.

`core.exception.RangeError@source\chip.d(85): Range violation`


I don't understand why? According to Windows [the file is 478 
bytes](https://github.com/corax89/chip8-test-rom/blob/master/test_opcode.ch8). memStart is 0x200. 0x200 + 478 = 990 which is well within the 4096Kb array which I created.


Re: Compiler Error while using Validation in the hunt-framework

2022-10-20 Thread Steven Schveighoffer via Digitalmars-d-learn

On 10/19/22 3:00 PM, Roman Funk wrote:

Hello,

I started playing with D and the hunt-framework. But I bumped into an 
error using Validation.


```d
module app.forms.LoginForm;
import hunt.validation;
import hunt.framework.http.Form;

class LoginForm : Form {
     mixin MakeForm;
     @Email
     string name;
     @Length(3,8)
     string password;
}

```
The error looks like that:

`../hunt/validation/DeclDef.d-mixin-41(54,108): Error: undefined 
identifier arg`


When I remove the parameters from `@Length`, it compiles.

I tried the `dicoth` example application, but I get the same error for 
the validation used there.


I use this compiler: DMD64 D Compiler v2.100.2
under Linux.

My current D knowledge is not sufficient to fix the bug. No idea how the 
annotation and mixin templates work together here. I didn't find any 
documentation, how to write custom annotations.


Can somebody give me a hint?


Just a thought, this may be nothing as I've never used the hunt 
framework, but try putting the mixin at the end of the class. Sometimes 
mixins can introspect the type they are being mixed into, which means 
the compiler has to build the rest of the type *first*. Although D 
should be able to forward reference all of this, at some point you have 
to have some kind of ordering in order to properly introspect a partly 
built type.


-Steve


Compiler Error while using Validation in the hunt-framework

2022-10-19 Thread Roman Funk via Digitalmars-d-learn

Hello,

I started playing with D and the hunt-framework. But I bumped 
into an error using Validation.


```d
module app.forms.LoginForm;
import hunt.validation;
import hunt.framework.http.Form;

class LoginForm : Form {
mixin MakeForm;
@Email
string name;
@Length(3,8)
string password;
}

```
The error looks like that:

`../hunt/validation/DeclDef.d-mixin-41(54,108): Error: undefined 
identifier arg`


When I remove the parameters from `@Length`, it compiles.

I tried the `dicoth` example application, but I get the same 
error for the validation used there.


I use this compiler: DMD64 D Compiler v2.100.2
under Linux.

My current D knowledge is not sufficient to fix the bug. No idea 
how the annotation and mixin templates work together here. I 
didn't find any documentation, how to write custom annotations.


Can somebody give me a hint?

BR Roman


Re: Linker Error with Template Function

2022-10-15 Thread Kyle Ingraham via Digitalmars-d-learn

On Saturday, 1 October 2022 at 21:18:05 UTC, Ali Çehreli wrote:

On 10/1/22 11:15, Kyle Ingraham wrote:

> storing structs as
> `void*` in a wrapper struct with information about their
module and
> identifier saved elsewhere.

Perhaps unrelated but that part reminded me of the following 
discussion:


  https://forum.dlang.org/post/tfbn10$19nv$1...@digitalmars.com

Ali


Thanks for this Ali. I found it useful to see another way to 
solve this problem. Seems like it would be great to have a `Type` 
type that can store a type at compile-time for use at run-time.


Re: Linker Error with Template Function

2022-10-01 Thread Ali Çehreli via Digitalmars-d-learn

On 10/1/22 11:15, Kyle Ingraham wrote:

> storing structs as
> `void*` in a wrapper struct with information about their module and
> identifier saved elsewhere.

Perhaps unrelated but that part reminded me of the following discussion:

  https://forum.dlang.org/post/tfbn10$19nv$1...@digitalmars.com

Ali




Re: Linker Error with Template Function

2022-10-01 Thread Kyle Ingraham via Digitalmars-d-learn
On Tuesday, 13 September 2022 at 08:43:45 UTC, Nick Treleaven 
wrote:
On Tuesday, 13 September 2022 at 03:00:17 UTC, Kyle Ingraham 
wrote:
Any suggestions for being able to call one function for any 
instance given but maintain flexible return types?


Not sure if it helps, but you can define final methods in an 
interface, which can call virtual interface methods:

```d
interface PathConverter
{
string getValue();

final T toD(T)()
{
import std.conv : to;

return to!T(getValue());
}
}
```
Not tested as AFK.


Thanks for the suggestion Nick. I solved this by storing structs 
as `void*` in a wrapper struct with information about their 
module and identifier saved elsewhere. I use that information to 
setup casts to the appropriate type then call `toD`. That way I 
can call the same method for functions that return different 
types and store disparate structs to the same wrapper struct. The 
wrapper struct gets used in function signatures.


Re: Linker Error with Template Function

2022-09-13 Thread Nick Treleaven via Digitalmars-d-learn
On Tuesday, 13 September 2022 at 03:00:17 UTC, Kyle Ingraham 
wrote:
Any suggestions for being able to call one function for any 
instance given but maintain flexible return types?


Not sure if it helps, but you can define final methods in an 
interface, which can call virtual interface methods:

```d
interface PathConverter
{
string getValue();

final T toD(T)()
{
import std.conv : to;

return to!T(getValue());
}
}
```
Not tested as AFK.


Re: Linker Error with Template Function

2022-09-12 Thread Kyle Ingraham via Digitalmars-d-learn

On Tuesday, 13 September 2022 at 01:46:14 UTC, Paul Backus wrote:
On Tuesday, 13 September 2022 at 00:57:58 UTC, Kyle Ingraham 
wrote:
I am writing a library where I would like to be able to store 
instances of a type of class to an associative array for later 
usage. Each class stored has to implement a function as part 
of the required interface. The argument given is always the 
same type but the return value should be flexible. I solved 
this with an interface:


```d
interface PathConverter
{
T toD(T)(const string value) @safe;
}
```


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

Templates cannot be used to add non-static fields or virtual 
functions to classes or interfaces.


You *should* get an error from the compiler for trying to do 
this, instead of just a linker error somewhere else down the 
line, but either way it's not going to work. You'll have to 
find another solution.


Thanks for the spec help Paul. I must've skirted around the 
compiler somehow. This is a minimal example that triggers the 
linker error:


```d
interface PathConverter
{
T toD(T)(string value);
}

class NumberConverter(T) : PathConverter
{
T toD(T)(string value)
{
import std.conv : to;

return to!T(value);
}
}

alias IntConverter = NumberConverter!int;

void main()
{
PathConverter[string] allConverters;
allConverters["int"] = new IntConverter;
int converted = allConverters["int"].toD!int("9");
}
```

Any suggestions for being able to call one function for any 
instance given but maintain flexible return types?


Re: Linker Error with Template Function

2022-09-12 Thread Paul Backus via Digitalmars-d-learn
On Tuesday, 13 September 2022 at 00:57:58 UTC, Kyle Ingraham 
wrote:
I am writing a library where I would like to be able to store 
instances of a type of class to an associative array for later 
usage. Each class stored has to implement a function as part of 
the required interface. The argument given is always the same 
type but the return value should be flexible. I solved this 
with an interface:


```d
interface PathConverter
{
T toD(T)(const string value) @safe;
}
```


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

Templates cannot be used to add non-static fields or virtual 
functions to classes or interfaces.


You *should* get an error from the compiler for trying to do 
this, instead of just a linker error somewhere else down the 
line, but either way it's not going to work. You'll have to find 
another solution.




Linker Error with Template Function

2022-09-12 Thread Kyle Ingraham via Digitalmars-d-learn
I am writing a library where I would like to be able to store 
instances of a type of class to an associative array for later 
usage. Each class stored has to implement a function as part of 
the required interface. The argument given is always the same 
type but the return value should be flexible. I solved this with 
an interface:


```d
interface PathConverter
{
T toD(T)(const string value) @safe;
}
```

That interface lets me type the associative array and any other 
part of the library that needs to use implementers of that 
interface e.g.


```d
PathConverter[string] converters;
```

The problem I'm running into is that when compile the library I 
receive the following error during linking:


```
error LNK2019: unresolved external symbol 
_D3app13PathConverter__T3toDTAyaZQjMFNfxAyaZQp referenced in 
function 
_D3app14TypedURLRouter__T10setHandlerTPFNfC4vibe4http6server17HTTPServerRequestCQBlQBjQBh18HTTPServerResponseAyaZvZQDmMFEQDaQCy6common10HTTPMethodQBlQEhZ__T9__lambda4TQEvTQDoTASQGt16PathCaptureGroupZQBrMFNfQGiQFaQBlZv


fatal error LNK1120: 1 unresolved externals

Error: linker exited with status 1120
```

The call is within a delegate to a function that returns a class 
instance from the associative array. At runtime I fill the 
associative array. The call looks like this:


```d
tailArgs[i] = getPathConverter("id 
string").toD!(Parameters!(handler)[i])("string to convert");

```

Am I running into this error because the linker can't find the 
instantiation of the template method? How would I give the linker 
the information it needs? Is there a better way to have an 
interface with flexible return values?


Re: neovim dcd-server error : ncm2_yarp dcd-server didn't cache any symbols ! Double check dcd include paths -I flag!

2022-09-10 Thread Alain De Vos via Digitalmars-d-learn

I seem to have found a solution.
Before starting neovim i do a,
dcd-server -I/usr/lib/ldc2/1.29/include/d
Automatic would be better.


neovim dcd-server error : ncm2_yarp dcd-server didn't cache any symbols ! Double check dcd include paths -I flag!

2022-09-10 Thread Alain De Vos via Digitalmars-d-learn
I try neovim editor with the language server DCD but it seems no 
symbols our found.

Could you guide me to solution ?


Re: Error "Unexpected '\n' when converting from type LockingTextReader to type int"

2022-09-07 Thread Ali Çehreli via Digitalmars-d-learn

On 9/7/22 16:24, Synopsis wrote:

> a- What is the difference with this syntax with the exclamation mark?
> ```readf!"%s\n"(f1.num);```

That's the templated version, which is safer because it checks at 
compile time (important distinction) that the arguments and the format 
specifiers do match.


> b- Do I need to put ```/n``` in every readf statement?

Another option is to use a space character, which reads and skips any 
number of any whitespace character. I have written something about that 
here:


  http://ddili.org/ders/d.en/input.html

And this one talks about readln, which may be more suitable in some cases:

  http://ddili.org/ders/d.en/strings.html

And there is formattedRead:

  http://ddili.org/ders/d.en/strings.html#ix_strings.formattedRead

> Forgive me if I'm asking silly questions.

There is never a silly question. If a question came up, it is as 
legitimate as it gets.


And welcome to programming! :)

Ali



Re: Error "Unexpected '\n' when converting from type LockingTextReader to type int"

2022-09-07 Thread rikki cattermole via Digitalmars-d-learn

On 08/09/2022 11:24 AM, Synopsis wrote:

On Wednesday, 7 September 2022 at 23:06:44 UTC, rikki cattermole wrote:

Text in buffer: "123\n"

Read: "123"
Text in buffer: "\n"

Read: exception, expecting number for "\n"

Changing your readf format specifier to include the new line should work.

https://dlang.org/phobos/std_stdio.html#.File.readf



Thank you!
Adding the \n seems to solve my problem: ```readf("%s\n", )```

I have two further questions about this!

a- What is the difference with this syntax with the exclamation mark? 
```readf!"%s\n"(f1.num);```


That is a template.

It'll type check that the format specifier matches your arguments.

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

b- Do I need to put ```/n``` in every readf statement? I mean, 
considering that every input gets entered after pressing intro key (and 
I guess this is what introduce the \n)


Yes.



Re: Error "Unexpected '\n' when converting from type LockingTextReader to type int"

2022-09-07 Thread Synopsis via Digitalmars-d-learn
On Wednesday, 7 September 2022 at 23:06:44 UTC, rikki cattermole 
wrote:

Text in buffer: "123\n"

Read: "123"
Text in buffer: "\n"

Read: exception, expecting number for "\n"

Changing your readf format specifier to include the new line 
should work.


https://dlang.org/phobos/std_stdio.html#.File.readf



Thank you!
Adding the \n seems to solve my problem: ```readf("%s\n", 
)```


I have two further questions about this!

a- What is the difference with this syntax with the exclamation 
mark? ```readf!"%s\n"(f1.num);```


b- Do I need to put ```/n``` in every readf statement? I mean, 
considering that every input gets entered after pressing intro 
key (and I guess this is what introduce the \n)



Forgive me if I'm asking silly questions.


Re: Error "Unexpected '\n' when converting from type LockingTextReader to type int"

2022-09-07 Thread rikki cattermole via Digitalmars-d-learn

Text in buffer: "123\n"

Read: "123"
Text in buffer: "\n"

Read: exception, expecting number for "\n"

Changing your readf format specifier to include the new line should work.

https://dlang.org/phobos/std_stdio.html#.File.readf


Error "Unexpected '\n' when converting from type LockingTextReader to type int"

2022-09-07 Thread Synopsis via Digitalmars-d-learn
Hi! I'm new at programming, just discovered D and I'm loving it 
so far!


I'm learning the basics, so please forgive my noob mistakes and 
questions (as well as my Engrish...).


I'm trying to make this program print both numbers entered by the 
user, it works with the first number (num):


```d
import std.stdio;

void main(){
  struct Fraction
  {
int num;
int den;
  }

  Fraction f1;

  write("Num: ");
  readf("%s", );

  writef("Num is: %s", f1.num);
}
```


But when I try the same with the second one, I get an error after 
entering the first number:


```d
import std.stdio;

void main(){
  struct Fraction
  {
int num;
int den;
  }

  Fraction f1;

  write("Num: ");
  readf("%s", );

  write("Den: ");
  readf("%s", );

  writef("Num is: %s", f1.num);
  writef("Den is: %s", f1.den);
}
```


*std.conv.ConvException@C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(2526):
 Unexpected '\n' when converting from type LockingTextReader to type int
0x00C80D74
0x00C80A77
0x00C80559
0x00C8047D
0x00C7FEDB
0x00C7FE4F
0x00C71045
0x00C8CE23
0x00C8CD8F
0x00C8CC0C
0x00C81D6C
0x00C7107F
0x75ADFA29 in BaseThreadInitThunk
0x77957A9E in RtlGetAppContainerNamedObjectPath
0x77957A6E in RtlGetAppContainerNamedObjectPath*


May someone tell me what am I doing wrong? Thank you in advance! 
:)


Re: synchronized/shared associative array .require error

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

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

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


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


Hmm.. LDC does the same to me.

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




Re: synchronized/shared associative array .require error

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

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


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





Re: synchronized/shared associative array .require error

2022-09-05 Thread Steven Schveighoffer via Digitalmars-d-learn

On 9/4/22 11:24 PM, cc wrote:

On Saturday, 3 September 2022 at 14:37:16 UTC, Steven Schveighoffer wrote:

On 9/2/22 3:15 PM, cc wrote:

Tried casting away shared as a workaround but I assume that will 
cause some kind of TLS catastrophe.




I think it will be fine, but you may have an issue. You are returning 
a non-shared `VAL`, but your class is `shared`, which means `table`, 
and all the `VAL` and `KEY` inside must also be `shared`.


If you cast away `shared` you have to put it back upon return.

TLS should not be involved here at all, so there is no problem there.



Alright, so this is safe then?
```d
alias VAL[KEY] T;
auto require(KEY key) {
 auto unsharedT = cast(T) table;
 auto r = unsharedT.require(key);
 table = cast(shared) unsharedT;
 return cast(shared) r;
}
```


I think that is fine-ish. You still don't have a shared `KEY` there. But 
it really depends on what KEY is. Most likely it's fine (e.g. if `KEY` 
is string). If you don't ever really fetch anything out of the key, and 
just use it to map to your values, I think it should be fine.


Was a bit surprised to see mutating `unsharedT` left `table` unchanged 
and needed reassigning.


Yes, because before an AA contains an element, it is a `null` AA. When 
you add the first element, it's allocated. When you make a copy of a 
`null` AA, it doesn't affect the original.


You can fix this by reinterpret casting the AA instead of copying it:

```d
auto r = .require(*(cast(T*)), key);
// I think this might also work:
auto r = (cast()table).require(key);
```

-Steve


Re: Tracing out error that causes compiler crash

2022-09-05 Thread Nick Treleaven via Digitalmars-d-learn

On Sunday, 4 September 2022 at 20:48:52 UTC, solidstate1991 wrote:

What do I pass as the tester?


You can use a script as described here:
https://github.com/CyberShadow/DustMite/wiki/Detecting-a-segfault-in-dmd-itself


Re: synchronized/shared associative array .require error

2022-09-04 Thread cc via Digitalmars-d-learn
On Saturday, 3 September 2022 at 14:37:16 UTC, Steven 
Schveighoffer wrote:

On 9/2/22 3:15 PM, cc wrote:

Tried casting away shared as a workaround but I assume that 
will cause some kind of TLS catastrophe.




I think it will be fine, but you may have an issue. You are 
returning a non-shared `VAL`, but your class is `shared`, which 
means `table`, and all the `VAL` and `KEY` inside must also be 
`shared`.


If you cast away `shared` you have to put it back upon return.

TLS should not be involved here at all, so there is no problem 
there.


-Steve


Alright, so this is safe then?
```d
alias VAL[KEY] T;
auto require(KEY key) {
auto unsharedT = cast(T) table;
auto r = unsharedT.require(key);
table = cast(shared) unsharedT;
return cast(shared) r;
}
```
Was a bit surprised to see mutating `unsharedT` left `table` 
unchanged and needed reassigning.


Re: Tracing out error that causes compiler crash

2022-09-04 Thread solidstate1991 via Digitalmars-d-learn
I tried to compile on the Raspberry Pi 400, now I'm getting 
segmentation fault during compilation with LDC. Still no idea 
what causes it, nor how to reduce it. Moved the codebase to a new 
repository, gave it a proper DOMString implementation instead of 
using it as a template name, and I'm still getting no luck 
compiling it. Current link: https://github.com/ZILtoid1991/newxml


I might try to comment out the bodies of the functions and force 
them to return an initial value, to see if there's something 
wrong with the insides of the functions.


Re: Tracing out error that causes compiler crash

2022-09-04 Thread solidstate1991 via Digitalmars-d-learn

On Sunday, 4 September 2022 at 08:17:13 UTC, Nick Treleaven wrote:
You may be able to use dustmite to automatically reduce the 
code to a minimal test case:

https://dlang.org/blog/2020/04/13/dustmite-the-general-purpose-data-reduction-tool/

Send my regards to the planet smasher.


What do I pass as the tester?


Re: Tracing out error that causes compiler crash

2022-09-04 Thread Nick Treleaven via Digitalmars-d-learn
On Saturday, 3 September 2022 at 21:20:01 UTC, solidstate1991 
wrote:
During unittest in my own fork of std.experimental.xml (link: 
https://github.com/ZILtoid1991/experimental.xml ), potentially 
an error so severe is present, that it causes to crash the 
compiler (both DMD and LDC2, on Windows). I was able to 
separate the issue by commenting out all unittests, then 
re-enabling them one-by-one seeing when it crashes the 
compiler, but wasn't able to track down the issues. However, 
`domimpl.d` is a 2000+ line monster, with a huge templated 
class that nests multiple other classes.


You may be able to use dustmite to automatically reduce the code 
to a minimal test case:

https://dlang.org/blog/2020/04/13/dustmite-the-general-purpose-data-reduction-tool/

Send my regards to the planet smasher.


Re: Error while generate DNA with uniform()

2022-09-03 Thread Ali Çehreli via Digitalmars-d-learn

On 9/3/22 14:18, Salih Dincer wrote:

>uniform!"[]"(DNA.min, DNA.max);

Even cleaner:

  uniform!DNA()

:)

Ali



Re: Error while generate DNA with uniform()

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

On 9/3/22 23:18, Salih Dincer via Digitalmars-d-learn wrote:

Clean-cut, thank you!
It's very clear to me...


Nothing major, but instead of `uniform!"[]"(DNA.min, DNA.max)`, you can simply 
use `uniform!DNA`.

`uniform` considers the whole enum: 
https://github.com/dlang/phobos/blob/v2.100.1/std/random.d#L2561

"Random variate drawn from the uniform distribution across all possible values of the [...] enum 
type T."


Re: Error while generate DNA with uniform()

2022-09-03 Thread Salih Dincer via Digitalmars-d-learn

On Saturday, 3 September 2022 at 21:09:09 UTC, Ali Çehreli wrote:

Salih had asked:

>> Can we solve this issue with our own `generate()` structure?

Yes, I did the following to determine that adding Unqual was a 
solution:


- Copy generate() functions to your source file,

- Copy the Generator struct to your source file,

- Edit the definition of Generator's elem_ member as I hinted 
in the bug.


But the bug may be in the templates, not in the structure. Maybe `
template functionTypeOf(alias func)`

For example:

```d
auto gen(alias fun)() {
auto gen = Gen!fun();
gen.popFront();
return gen;
}

struct Gen(alias fn)
{
  import std.traits:
  ReturnType!fn func;

  enum empty = false;
  auto front() { return func; }
  void popFront() { func = fn(); }
}

unittest
{
  import std.random : uniform;
  import std.range : takeExactly;

  enum E {
O = '0', P, Q, R, S, T, U, V, W, X,
A = 'A', B, C, D, E, F
  }
  auto range = gen!(function char()  =>
   uniform!"[]"(E.min, E.max))
   .takeExactly(15);
  assert(range.to!long(15) < long.max);
}
```
SDB@79



Tracing out error that causes compiler crash

2022-09-03 Thread solidstate1991 via Digitalmars-d-learn
During unittest in my own fork of std.experimental.xml (link: 
https://github.com/ZILtoid1991/experimental.xml ), potentially an 
error so severe is present, that it causes to crash the compiler 
(both DMD and LDC2, on Windows). I was able to separate the issue 
by commenting out all unittests, then re-enabling them one-by-one 
seeing when it crashes the compiler, but wasn't able to track 
down the issues. However, `domimpl.d` is a 2000+ line monster, 
with a huge templated class that nests multiple other classes. I 
suspect that there's some leftover from the stripped configurable 
allocator and/or error handler, that causes the issue.


At worst-case scenario, I can just manually rewrite the whole 
part (I already planned to write a more linear cursor for speed 
reasons), but that will consume a lot of my time. A lot of part 
of the code is already undocumented (especially anything 
non-public), so it's a question whether reimplementing stuff from 
almost zero, or trying to decipher a legacy code is the easier 
stuff.


Re: Error while generate DNA with uniform()

2022-09-03 Thread Salih Dincer via Digitalmars-d-learn
On Saturday, 3 September 2022 at 14:25:48 UTC, Steven 
Schveighoffer wrote:
 [...] what you need anyway is a `char`, so just return a 
`char`. [...]


Clean-cut, thank you!

It's very clear to me...

```d
import std;
void main()
{
  alias fp = char function() @system;
  enum DNA : char
  {
  timin = 'T',
sitozin = 'C',
 guanin = 'G',
 adenin = 'A'
  }
  fp getDNA = () => uniform!"[]"(DNA.min,
 DNA.max);
  enum n = 30;
  auto genes = generate!getDNA.take(n).array;
  auto unique = genes.uniq.array;
  // CATCATGGTAGGCCTTTCATGCGCTA
  assert(unique.length < n, "no repeat");
  unique.writeln; // ACATCATGTAGCTCATGCGCTA
}
```
SDB@79


Re: Error while generate DNA with uniform()

2022-09-03 Thread Ali Çehreli via Digitalmars-d-learn

On 9/3/22 07:25, Steven Schveighoffer wrote:

> There is probably a bug in generate when the element type is an `enum`
> which somehow makes it const.

Yes, Generator is missing an Unqual:

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

Salih had asked:

>> Can we solve this issue with our own `generate()` structure?

Yes, I did the following to determine that adding Unqual was a solution:

- Copy generate() functions to your source file,

- Copy the Generator struct to your source file,

- Edit the definition of Generator's elem_ member as I hinted in the bug.

Ali



Re: synchronized/shared associative array .require error

2022-09-03 Thread Steven Schveighoffer via Digitalmars-d-learn

On 9/2/22 3:15 PM, cc wrote:

Tried casting away shared as a workaround but I assume that will cause 
some kind of TLS catastrophe.




I think it will be fine, but you may have an issue. You are returning a 
non-shared `VAL`, but your class is `shared`, which means `table`, and 
all the `VAL` and `KEY` inside must also be `shared`.


If you cast away `shared` you have to put it back upon return.

TLS should not be involved here at all, so there is no problem there.

-Steve


Re: Error while generate DNA with uniform()

2022-09-03 Thread Steven Schveighoffer via Digitalmars-d-learn

On 9/3/22 8:09 AM, Salih Dincer wrote:

Hi All,

We discovered a bug yesterday and reported it:

https://forum.dlang.org/thread/mailman.1386.1662137084.31357.digitalmars-d-b...@puremagic.com 



You know, there is `generate()` depend to `std.range`. It created the 
error when we use it with the value of an enum. Which get their values 
from an `enum DNA`, we have 4 members that we want to generate 32 pieces 
randomly like this:


```d
import std;
void main()
{
   enum DNA { timin = 84,
  sitozin = 67,
  guanin = 71,
  adenin = 65
    }
   char[] gene;
   enum n = 32;
   auto range = generate!(() => uniform(DNA.min, DNA.max)).take(n);/*
   auto preferred = generate!(() =>
    uniform!"[]"(DNA.min,
     DNA.max)).take(n);//*/


I'm not sure why this doesn't work. First, I would change your enum to 
this (for correctness and readability):


```d
  enum DNA : char { timin = 'T',
 sitozin = 'C',
 guanin = 'G',
 adenin = 'A'
   }
```

There is probably a bug in generate when the element type is an `enum` 
which somehow makes it const. But what you need anyway is a `char`, so 
just return a `char`. For that, you need to specify the return type, 
which requires a different kind of function literal:


```d
   auto preferred = generate!(function char() =>
uniform!"[]"(DNA.min,
 DNA.max)).take(n);
```

That works.

-Steve


Re: synchronized/shared associative array .require error

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

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

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


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


Error while generate DNA with uniform()

2022-09-03 Thread Salih Dincer via Digitalmars-d-learn

Hi All,

We discovered a bug yesterday and reported it:

https://forum.dlang.org/thread/mailman.1386.1662137084.31357.digitalmars-d-b...@puremagic.com

You know, there is `generate()` depend to `std.range`. It created 
the error when we use it with the value of an enum. Which get 
their values from an `enum DNA`, we have 4 members that we want 
to generate 32 pieces randomly like this:


```d
import std;
void main()
{
  enum DNA { timin = 84,
 sitozin = 67,
 guanin = 71,
 adenin = 65
   }
  char[] gene;
  enum n = 32;
  auto range = generate!(() => uniform(DNA.min, 
DNA.max)).take(n);/*

  auto preferred = generate!(() =>
   uniform!"[]"(DNA.min,
DNA.max)).take(n);//*/
  // # Alternative Solution:
  foreach (_; 0..n)
  {
gene ~= uniform!"[]"(DNA.min, DNA.max);
  }
  gene.writeln; // CGACGTGCTTCATCGATAGGAGCACGAGGAGC
  // If the ASCII table matches (capital group 64-95) there 
should be no problem...

}
```

If there was no alternative solution, we would generate random 
numbers between 65 and 84 that have no equivalent in DNA. We want 
to use "[]" ( closed to the left and right)  but preferred 
version doesn't compile.


Can we solve this issue with our own `generate()` structure?

SDB@79



Re: synchronized/shared associative array .require error

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

On Friday, 2 September 2022 at 19:15:45 UTC, cc wrote:

```d
synchronized class SyncTable(KEY, VAL) {
private VAL[KEY] table;
auto require(KEY key) {
return table.require(key);
}
}

auto table = new shared SyncTable!(string, string);
table.require("abc");
```

Fails to compile:
```
// Error: none of the overloads of template `object.require` 
are callable using argument types `!()(shared(string[string]), 
string)`

```

Tried casting away shared as a workaround but I assume that 
will cause some kind of TLS catastrophe.


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


Anyway if you must send a reference of a `synchronized` class to 
a different thread then it's safe to cast `shared` and then 
remove it later:


```d
synchronized class A{
...
}

void sendTo(Tid to, A a){
  to.send(cast(shared A) a);
}

A receiveA(){
  A a;
  receive( (shared A sa) { a = cast(A) sa; });
  return a;
}
```

Unfortunately there isn't any traits that tells you if a class is 
`synchronized` or not, so you can't do a safe template function 
for this.


synchronized/shared associative array .require error

2022-09-02 Thread cc via Digitalmars-d-learn

```d
synchronized class SyncTable(KEY, VAL) {
private VAL[KEY] table;
auto require(KEY key) {
return table.require(key);
}
}

auto table = new shared SyncTable!(string, string);
table.require("abc");
```

Fails to compile:
```
// Error: none of the overloads of template `object.require` are 
callable using argument types `!()(shared(string[string]), 
string)`

```

Tried casting away shared as a workaround but I assume that will 
cause some kind of TLS catastrophe.




Re: freebsd dub linker error

2022-09-01 Thread Alain De Vos via Digitalmars-d-learn

On Wednesday, 1 June 2022 at 15:23:14 UTC, Kagamin wrote:

Try to run clang with -v option and compare with gcc.


I've tracked down the problem to the solution where i specify as 
linker to use gcc12 instead of a clang/llvm.

The following works.
```
export CC=clang14
ldc2 --link-defaultlib-shared --gcc=gcc12 ...
```
But i have no explanation.


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

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

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

Hi,

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


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


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


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


Thanks.


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


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


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

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

Hi,

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


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


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


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


Thanks.



Re: "Error: no property `offsetof` for type `char*`"

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

On Friday, 19 August 2022 at 16:36:24 UTC, MyNameHere wrote:

On Friday, 19 August 2022 at 14:30:50 UTC, kinke wrote:
Oh and `DevicePath()` is a convenience member returning a 
pointer to the 'dynamic array' (as the array decays to a 
pointer in C too), so no need to fiddle with `.offsetof` and 
computing the pointer manually.


I am using ```-BetterC```, so that path is closed to me, I 
think.


I believe you aren't allowed to _append_ to dynamic 
arrays/slices; otherwise you can use them


Re: "Error: no property `offsetof` for type `char*`"

2022-08-19 Thread Steven Schveighoffer via Digitalmars-d-learn

On 8/19/22 12:36 PM, MyNameHere wrote:

On Friday, 19 August 2022 at 14:30:50 UTC, kinke wrote:
Oh and `DevicePath()` is a convenience member returning a pointer to 
the 'dynamic array' (as the array decays to a pointer in C too), so no 
need to fiddle with `.offsetof` and computing the pointer manually.


I am using ```-BetterC```, so that path is closed to me, I think.


dynamic arrays are really slices, and they are allowed in betterC.

-Steve


Re: "Error: no property `offsetof` for type `char*`"

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

On Friday, 19 August 2022 at 14:30:50 UTC, kinke wrote:
Oh and `DevicePath()` is a convenience member returning a 
pointer to the 'dynamic array' (as the array decays to a 
pointer in C too), so no need to fiddle with `.offsetof` and 
computing the pointer manually.


I am using ```-BetterC```, so that path is closed to me, I think.




Re: "Error: no property `offsetof` for type `char*`"

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

On Friday, 19 August 2022 at 13:49:08 UTC, MyNameHere wrote:
Thank you, that seems to have resolved the issue, though I wish 
these sorts of problems would stop cropping up, they are 
souring the experience with the language.


Oh and `DevicePath()` is a convenience member returning a pointer 
to the 'dynamic array' (as the array decays to a pointer in C 
too), so no need to fiddle with `.offsetof` and computing the 
pointer manually.


  1   2   3   4   5   6   7   8   9   10   >