interrupting a function

2018-11-16 Thread Alex via Digitalmars-d-learn
I wished I never come across the nightmare of such a question. 
And maybe, there is still a bug in my code, which I'm not aware 
of (which I strongly suppose :/ ).
But nevertheless, and for learning purposes, assume I have 
something like this:


´´´
auto foo(/*input params*/)
{
//some long calculations, depending on input params.
}

void main()
{
foo;
}
´´´

It can happen, that the input params are correct, however, the 
calculation lasts too long. Is there a way, to measure the 
execution time of foo (á la benchmark) and then, if some 
execution time limit is exceeded to interrupt the calculation? At 
best, with a flag, whether foo ended normally or because of the 
interruption.


Re: Fields with the same name not causing a warning?

2018-11-16 Thread Dennis via Digitalmars-d-learn

On Friday, 16 November 2018 at 20:13:42 UTC, Vinay Sajip wrote:
More complicated for the compiler writers, or users of 
mixins/generics?


For users of generics. It's hard to come up with an actual 
example because I don't know why one would ever use this, but in 
this concocted scenario:


```
mixin template initRange() {
  typeof(this) front = typeof(this).init;
  enum empty = true;
  void popFront() {}
}

class A {
  mixin initRange;
}

class B : A {
  mixin initRange;
}
```

The initRange template would need a static if to decide whether 
to add `override` or not.


On Friday, 16 November 2018 at 20:13:42 UTC, Vinay Sajip wrote:
But presumably making it an error would potentially be a 
breaking change?


It would be breaking. The question is how much breakage there is 
of 'correct' hiding vs. how often unintended hiding leads to 
problems.




Re: Fields with the same name not causing a warning?

2018-11-16 Thread Norm via Digitalmars-d-learn

On Friday, 16 November 2018 at 15:59:14 UTC, Vinay Sajip wrote:

This code should IMO give at least a warning, but it doesn't:

abstract class A {
int kind;
}

[...]



This is not unique to D you can do the same in Java or C++.

bye,
Norm


Re: what are the rules for @nogc and @safe attributes inference?

2018-11-16 Thread ikod via Digitalmars-d-learn

On Friday, 16 November 2018 at 12:12:12 UTC, Alex wrote:

=
This code compiles as long as `lazy` is commented out. But I'd 
like to have
both lazy parameter and @nogc inferrence for `library_func` so 
that user is not locked to code @nogc or not.


Aha, aha... Interesting!
I had a similar problem with passing a delegate. And it was 
solved:

https://forum.dlang.org/thread/erznqknpyxzxqivaw...@forum.dlang.org

For your problem, there is a bug report:
https://forum.dlang.org/post/wedwfooqdxbwxttpm...@forum.dlang.org
https://issues.dlang.org/show_bug.cgi?id=12664
https://issues.dlang.org/show_bug.cgi?id=12647


Thanks for these links.
And yes, I have workaround with handmade delegate. It compiles 
and it is lazy, but also ugly.


import std.traits;

T library_func(T)(/*not lazy*/ T i) if (!isCallable!T)
{
return i;
}
ReturnType!T library_func(T)(/*lazy*/ T i) if (isCallable!T)
{
return i();
}
void user_function_nogc() @nogc
{
int x = 1;
library_func(x+1);
}
void user_function_gc()
{
library_func(()=>[1]);
}
void main()
{
}


Re: Fields with the same name not causing a warning?

2018-11-16 Thread Vinay Sajip via Digitalmars-d-learn

On Friday, 16 November 2018 at 19:12:42 UTC, Dennis wrote:
If something is definitively wrong, then it should be an error. 
If it's not definitively wrong, then the compiler shouldn't say 
anything about it, and it should be left up to a linter tool of 
some kind like dcd."


https://forum.dlang.org/post/mailman.3986.1537881312.29801.digitalmar...@puremagic.com



Thanks for that link, it helps to understand the thinking behind 
the way things are.


The language design could be fixed by requiring the use of the 
`override` keyword  like in C#. However, in D it *might* make 
generic code (with mixins) more complicated, though I 
personally have never found a use for hiding member variables 
so I don't know the rationale.


More complicated for the compiler writers, or users of 
mixins/generics? In any case, the example I showed was more 
commonplace than mixins and templates. Perhaps the default should 
be to fail compilation with an error, and allow `override` when 
someone actually wants to hide/shadow members in base classes, 
for whatever reason. I suggested "warning" rather than "error" in 
the OP, because I didn't know the philosophy behind warnings in D 
that you've now made me aware of. But presumably making it an 
error would potentially be a breaking change?


Re: Not able to load classes defined in archive file in Mac OSX using Object.factory

2018-11-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 16 November 2018 at 14:55:52 UTC, Aditya wrote:

How can one write own factory function ? Any pointers to this ?


Something like

Interface delegate()[string] factories;

Interface create(string className) {
if(className in factories)
   return factories[classname];
else
   return null; // or throw if you prefer
}



In every module in which you create a class, you will want to add 
code like this:


class Class : Interface {}

// register with the factory in a module constructor
static this() {
   factories["Class"] = Interface delegate() {
   return new Class();
   }
}


And it should work.


Re: Fields with the same name not causing a warning?

2018-11-16 Thread Dennis via Digitalmars-d-learn

On Friday, 16 November 2018 at 18:37:00 UTC, Vinay Sajip wrote:

Design flaws in what?


Design flaws in the language.

Quoting Jonathan M Davis:
"Honestly, in general, warnings are a terrible idea. Anything 
that's a warning in your code has to be fixed, because it's bad 
practice to leave warnings in your code, meaning that ultimately, 
there's not much difference between a warning and an error. To 
make matters worse, there's a compiler flag that turns warnings 
into errors. And when you combine that with stuff like 
is(typeof(...)) and template constraints, whether you use that 
compiler flag or not could actually change the resulting program. 
So, as it stands, warnings are an even worse idea in D than they 
are in other languages. Walter likes to talk about how warnings 
in C/C++ are there simply because folks couldn't agree on what 
should or shouldn't be an error in the language.


If something is definitively wrong, then it should be an error. 
If it's not definitively wrong, then the compiler shouldn't say 
anything about it, and it should be left up to a linter tool of 
some kind like dcd."


https://forum.dlang.org/post/mailman.3986.1537881312.29801.digitalmar...@puremagic.com

The language design could be fixed by requiring the use of the 
`override` keyword  like in C#. However, in D it *might* make 
generic code (with mixins) more complicated, though I personally 
have never found a use for hiding member variables so I don't 
know the rationale.


Re: Fields with the same name not causing a warning?

2018-11-16 Thread Vinay Sajip via Digitalmars-d-learn

On Friday, 16 November 2018 at 17:35:13 UTC, Basile B. wrote:
D is not a compiler that warns much. You can still open an 
issue asking for this (and the warning must be easy to add at 
first glance), but the policy applied to warnings is "compilers 
warnings are a sign of design flaws so instead of emitting one 
we should rather fix the flaw".


Design flaws in what? In this case, the flaw was in my code, but 
I would expect some help from the compiler in catching such an 
ambiguity, and so fixing the flaw in my code. That it didn't try 
to help me might itself be considered a design flaw in the 
compiler ;-)




Re: Compile time code generation

2018-11-16 Thread Steven Schveighoffer via Digitalmars-d-learn

On 11/16/18 12:10 PM, boolangery wrote:

Hi,

Is something like this is doable ?

---
// all compile time
MapperGen.Create!(A, B)
     .Map!("p1", "p2")
     .Map!("myprop", "otherprop")
     .Gen();

// The code above must generate something like
//
// class Mapper {
// B map(A value) {
// B ret = new B();
// ret.p1 = value.p2;
// ret.myprop = p2.otherprop;
// return ret;
// }
// }

// runtime use
auto b = new Mapper().map(new A());
---

I can't figure out how to concatenate string at runtime and the mixin 
the resulting string?.


I'm not understanding what you are trying to do, but to answer your 
question, you can only mixin a string generated at compile time.


However, you can concatenate a string at runtime inside a CTFE-able 
function, and then mixin the result.


Example:

string foo(string[] fields...)
{
   string result = "struct Foo {";
   foreach(f; fields)
   result ~= "int " ~ f ~ ";";
   return result ~ "}";
}

mixin(foo()); // generate the struct

-Steve


Re: subsystem:windows and writeln

2018-11-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 16 November 2018 at 17:49:06 UTC, Domain wrote:

But I cannot control the 3rd library!


Hmm, I see.

So one possibility would be to reopen stdout (and maybe stderr) 
to a different file.


stdout.reopen("log.txt", "wt");

when you start your program and before you call the library and 
it should no longer error - unless it can't create the file. Then 
you can look at the file if you do need the output.


Re: subsystem:windows and writeln

2018-11-16 Thread Adam D. Ruppe via Digitalmars-d-learn
BTW if you just want to ditch the output, you might be able to 
use "NUL" as the file name. I havent' tried tho.


Re: subsystem:windows and writeln

2018-11-16 Thread Domain via Digitalmars-d-learn

On Friday, 16 November 2018 at 17:46:20 UTC, Adam D. Ruppe wrote:

On Friday, 16 November 2018 at 17:36:01 UTC, Domain wrote:

I think this is unacceptable.


Why?

You are asking it to write to a file that doesn't exist... you 
probably shouldn't be doing that...


But I cannot control the 3rd library!


Re: subsystem:windows and writeln

2018-11-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 16 November 2018 at 17:36:01 UTC, Domain wrote:

I think this is unacceptable.


Why?

You are asking it to write to a file that doesn't exist... you 
probably shouldn't be doing that...


subsystem:windows and writeln

2018-11-16 Thread Domain via Digitalmars-d-learn
When I link the app with /subsystem:windows, and all writeln and 
writefln will cause a enforcement failed (stdio.d:2889).

I think this is unacceptable.


Re: Fields with the same name not causing a warning?

2018-11-16 Thread Basile B. via Digitalmars-d-learn

On Friday, 16 November 2018 at 17:28:15 UTC, Vinay Sajip wrote:

On Friday, 16 November 2018 at 17:08:00 UTC, Basile B. wrote:

I agree that this is almost a case of shadowing but i don't 
know the exact rationale for allowing this.


I'm not saying it shouldn't be allowed - just that the compiler 
could warn you about what might very well be a mistake (as it 
was in my case) - hard to debug with printf debugging, and 
source level debug for D is a bit thin on the ground, ISTM.


D is not a compiler that warns much. You can still open an issue 
asking for this (and the warning must be easy to add at first 
glance), but the policy applied to warnings is "compilers 
warnings are a sign of design flaws so instead of emitting one we 
should rather fix the flaw".


Re: Fields with the same name not causing a warning?

2018-11-16 Thread Vinay Sajip via Digitalmars-d-learn

On Friday, 16 November 2018 at 17:08:00 UTC, Basile B. wrote:

I agree that this is almost a case of shadowing but i don't 
know the exact rationale for allowing this.


I'm not saying it shouldn't be allowed - just that the compiler 
could warn you about what might very well be a mistake (as it was 
in my case) - hard to debug with printf debugging, and source 
level debug for D is a bit thin on the ground, ISTM.


Compile time code generation

2018-11-16 Thread boolangery via Digitalmars-d-learn

Hi,

Is something like this is doable ?

---
// all compile time
MapperGen.Create!(A, B)
.Map!("p1", "p2")
.Map!("myprop", "otherprop")
.Gen();

// The code above must generate something like
//
// class Mapper {
// B map(A value) {
// B ret = new B();
// ret.p1 = value.p2;
// ret.myprop = p2.otherprop;
// return ret;
// }
// }

// runtime use
auto b = new Mapper().map(new A());
---

I can't figure out how to concatenate string at runtime and the 
mixin the resulting string?.



Thanks in advance !


Re: Fields with the same name not causing a warning?

2018-11-16 Thread Basile B. via Digitalmars-d-learn

On Friday, 16 November 2018 at 15:59:14 UTC, Vinay Sajip wrote:

This code should IMO give at least a warning, but it doesn't:

abstract class A {
int kind;
}

class B : A {
int kind;

this(int k) {
kind = k;
}
}

In my actual code, the declaration of field "kind" in B was 
left in accidentally. Surprisingly, however, no warning was 
emitted when I compiled this, leading to B having two fields 
called kind which are distinct from one another. The complete 
program


import std.stdio;

abstract class A {
int kind;
}

class B : A {
int kind;

this(int k) {
kind = k;
}
}

void main()
{
auto b = new B(4);
A a = b;

writeln(b.kind);
writeln(a.kind);
}

prints

4
0

Given that this is the kind of thing that is easily done, 
surely the default behaviour should be for the compiler to emit 
at least a warning that field "kind" is ambiguous in B? This 
behaviour occurs even when the field is declared as "public" or 
"protected" in both classes. What am I missing?


When you re declare with the same name in a sub class each 
generation has its own variable. To distinguish you can use the 
type for which you want "kind":


writeln(b.A.kind); // the one from A
writeln(b.B.kind); // the one from B

I agree that this is almost a case of shadowing but i don't know 
the exact rationale for allowing this.


Re: Not able to load classes defined in archive file in Mac OSX using Object.factory

2018-11-16 Thread Basile B. via Digitalmars-d-learn

On Friday, 16 November 2018 at 14:55:52 UTC, Aditya wrote:
On Friday, 16 November 2018 at 14:30:02 UTC, Adam D. Ruppe 
wrote:
PS object.factory sucks and I hope it is removed some day. 
There's no plan to do so, but I still wouldn't actually rely 
on it... instead, I'd write your own factory function and 
registration system, so you control it and will have 
reliability to your specific needs.


but still if the factory works for you, eh, you can use it.


How can one write own factory function ? Any pointers to this ?

Thanx


for learning purpose you can make very simply a factory function 
based on string comparison.


Object simpleFactory(string className)
{
   import the_module_where_stuff_is_declared;
   import the_module_where_thing_is_declared;

   if (className == "Stuff")
   return new Stuff;
   else if if (className == "Thing")
  return new Thing;
   // and so on
   else return null;
}

although this requires imports so the command line for building 
should include more path using the "-I" cmd line switch.


I propose this solution because making a true factory might be 
too complicated if you just start learning D.


Re: Not able to load classes defined in archive file in Mac OSX using Object.factory

2018-11-16 Thread Steven Schveighoffer via Digitalmars-d-learn

On 11/16/18 9:51 AM, Aditya wrote:

On Friday, 16 November 2018 at 14:28:22 UTC, Adam D. Ruppe wrote:

On Friday, 16 November 2018 at 14:24:10 UTC, Aditya wrote:

./ss/Stat.d  (defines interface named 'Stat')
./ss/Min.d   (defines class named 'Min' that implements Stat)


Did you put a module declaration at the top of those files? Like

module ss.Stat;


That ought to be required; the compiler lets you skip it, but it 
doesn't work reliably without it once you start importing the module 
or other similar things.




But once you have that, the name of your class will be the full name 
with module, so like if min has


module ss.Min;

class Min {}


the full class name will be

ss.Min.Min

the full module name dot the full class name.


Module Names were not added. But after adding the same, still same result.

// Following still doesn't work
ss.Min.Min
ss.ss.Min
ss.ss.Min.Min
stats.ss.Min.Min
stats.Min


So to let you know, Object.factory is not a maintained function. The 
ability to instantiate classes based on the ModuleInfo was overruled by 
the fact that we don't want to generate ModuleInfo if we don't have to, 
and it should be as small as possible. Therefore, you need some triggers 
to make sure the module info is included, and even then, I think, it's 
not guaranteed to include the classinfo in that moduleinfo.


The better path is to use a registration system to add the desired 
classes for reflection. Not a trivial thing, but that's probably the 
path you want. I'd suggest looking at serialization libraries like 
orange (http://code.dlang.org/packages/orange) or cereald 
(http://code.dlang.org/packages/cerealed) for ideas, or maybe just use 
one of them.


-Steve


Fields with the same name not causing a warning?

2018-11-16 Thread Vinay Sajip via Digitalmars-d-learn

This code should IMO give at least a warning, but it doesn't:

abstract class A {
int kind;
}

class B : A {
int kind;

this(int k) {
kind = k;
}
}

In my actual code, the declaration of field "kind" in B was left 
in accidentally. Surprisingly, however, no warning was emitted 
when I compiled this, leading to B having two fields called kind 
which are distinct from one another. The complete program


import std.stdio;

abstract class A {
int kind;
}

class B : A {
int kind;

this(int k) {
kind = k;
}
}

void main()
{
auto b = new B(4);
A a = b;

writeln(b.kind);
writeln(a.kind);
}

prints

4
0

Given that this is the kind of thing that is easily done, surely 
the default behaviour should be for the compiler to emit at least 
a warning that field "kind" is ambiguous in B? This behaviour 
occurs even when the field is declared as "public" or "protected" 
in both classes. What am I missing?


Re: Not able to load classes defined in archive file in Mac OSX using Object.factory

2018-11-16 Thread Aditya via Digitalmars-d-learn

On Friday, 16 November 2018 at 14:30:02 UTC, Adam D. Ruppe wrote:
PS object.factory sucks and I hope it is removed some day. 
There's no plan to do so, but I still wouldn't actually rely on 
it... instead, I'd write your own factory function and 
registration system, so you control it and will have 
reliability to your specific needs.


but still if the factory works for you, eh, you can use it.


How can one write own factory function ? Any pointers to this ?

Thanx


Re: Not able to load classes defined in archive file in Mac OSX using Object.factory

2018-11-16 Thread Aditya via Digitalmars-d-learn

On Friday, 16 November 2018 at 14:28:22 UTC, Adam D. Ruppe wrote:

On Friday, 16 November 2018 at 14:24:10 UTC, Aditya wrote:

./ss/Stat.d  (defines interface named 'Stat')
./ss/Min.d   (defines class named 'Min' that implements Stat)


Did you put a module declaration at the top of those files? Like

module ss.Stat;


That ought to be required; the compiler lets you skip it, but 
it doesn't work reliably without it once you start importing 
the module or other similar things.




But once you have that, the name of your class will be the full 
name with module, so like if min has


module ss.Min;

class Min {}


the full class name will be

ss.Min.Min

the full module name dot the full class name.


Module Names were not added. But after adding the same, still 
same result.


// Following still doesn't work
ss.Min.Min
ss.ss.Min
ss.ss.Min.Min
stats.ss.Min.Min
stats.Min


Re: Not able to load classes defined in archive file in Mac OSX using Object.factory

2018-11-16 Thread Adam D. Ruppe via Digitalmars-d-learn
PS object.factory sucks and I hope it is removed some day. 
There's no plan to do so, but I still wouldn't actually rely on 
it... instead, I'd write your own factory function and 
registration system, so you control it and will have reliability 
to your specific needs.


but still if the factory works for you, eh, you can use it.


Re: Not able to load classes defined in archive file in Mac OSX using Object.factory

2018-11-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 16 November 2018 at 14:24:10 UTC, Aditya wrote:

./ss/Stat.d  (defines interface named 'Stat')
./ss/Min.d   (defines class named 'Min' that implements Stat)


Did you put a module declaration at the top of those files? Like

module ss.Stat;


That ought to be required; the compiler lets you skip it, but it 
doesn't work reliably without it once you start importing the 
module or other similar things.




But once you have that, the name of your class will be the full 
name with module, so like if min has


module ss.Min;

class Min {}


the full class name will be

ss.Min.Min

the full module name dot the full class name.


Not able to load classes defined in archive file in Mac OSX using Object.factory

2018-11-16 Thread Aditya via Digitalmars-d-learn

Hello !

I am trying to work out "The D programming Language" chapter 1.6 
problem on Interfaces and Classes.


folder
./stats.d(takes argument "Min/Max" on command line and loads 
them)

./ss/Stat.d  (defines interface named 'Stat')
./ss/Min.d   (defines class named 'Min' that implements Stat)

$ dmd -lib -g ss/*.d -of=ss.a
$ dmd -g stats.d ss.a
$ echo 3 5 1.3 4 10 4.5 1 5 | stats Min
object.Exception@stats.d(19): Invalid statistics function: Min

Code for stats.d -

import std.exception, std.stdio;
import ss.Stat;  // works !!

void main(string[] args){
Stat[] stats;

foreach (arg; args[1 .. $]) {

// Doesn't work
// string path = "stats." ~ arg ~ "." ~ arg;
// string path = "stats." ~ arg;
// string path = "stats.ss." ~ arg;
// string path = "stats.ss." ~ arg ~ "." ~ arg;
// string path = "ss." ~ arg;
// string path = "ss." ~ arg ~ "." ~ arg;
// string path = arg ~ "." ~ arg;
// string path = arg;
// string path = "stats.ss." ~ arg ~ "." ~ arg;

 string path = arg;

auto newStat = cast(Stat) Object.factory(path);
enforce(newStat, "Invalid statistics function: " ~ path);
stats ~= newStat;
}
}

What is the path for Min class defined in Min.d inside ./ss 
folder that is compiled into ss.a ?


Thanks
Aditya



Re: Sorting a subrange

2018-11-16 Thread Per Nordlöw via Digitalmars-d-learn
On Friday, 16 November 2018 at 12:08:33 UTC, Stanislav Blinov 
wrote:

import std.range.primitives : isRandomAccessRange;

auto sortSubRange(R)(R range, size_t i, size_t j) if 
(isRandomAccessRange!R) {

import std.algorithm.sorting : topN, partialSort;
size_t start = i;
if (i != 0) {
topN(range, i);
start++;
}
partialSort(range[start .. $], j-start);
return range[i .. j];
}


Wonderful!


Re: How do you debug @safe @nogc code? Can't figure out how to print.

2018-11-16 Thread Stanislav Blinov via Digitalmars-d-learn

On Friday, 16 November 2018 at 12:59:22 UTC, aliak wrote:

Adding @trusted to declaration of opDispatch gets rid of @safe 
error but I still get "Error: @nogc function D main cannot call 
non-@nogc function". And going through the codebase and 
figuring out where to add @trusted is *very* cumbersome.


I can't figure out how to make this work. The ideal way would 
be just a debug_print() function that works in nogc and safe 
code. I.e. does not affect the attribute inference of templates.


As Zoadian points out, you can now (since 2.079: 
https://dlang.org/changelog/2.079.0.html#bugfix-list) shamelessly 
call @nogc inside debug blocks.


To get at where the problematic areas were in the code in 
question though, it's as follows:



auto assumeNoGC(T)(T t) {  // point 1
import std.traits;
enum attrs = functionAttributes!T | FunctionAttribute.nogc;
// point 2:
return cast(SetFunctionAttributes!(T, functionLinkage!T, 
attrs)) t;

}


At 'point 1', you just take by value. If `t` ends up being a 
closure, D will allocate. That's where it breaks the @nogc. 
Solution:


auto assumeNoGC(T)(return scope T t) { /* ... */ }

Now you take (and return) a `scope` t, in that case when `t` is a 
closure D won't allocate it on the GC heap.


At 'point 2' you make an un-@safe cast, that's where it breaks 
@safe. Given that the whole deal is just a debugging hack, you 
could mark the whole function @trusted:


auto assumeNoGC(T)(return scope T t) @trusted { /* ... */ }


Re: How do you debug @safe @nogc code? Can't figure out how to print.

2018-11-16 Thread Zoadian via Digitalmars-d-learn

debug {
import std.stdio;
writeln(args);
}


How do you debug @safe @nogc code? Can't figure out how to print.

2018-11-16 Thread aliak via Digitalmars-d-learn
Hi, I previously had trouble trying to get print statements 
working while debugging in nogc. And that was hackishly solved 
[0], but I can't figure out how to do the same if I have @safe 
involved. Here's a cut down sample:


// This is the function from the thread referenced
auto assumeNoGC(T)(T t) {
import std.traits;
enum attrs = functionAttributes!T | FunctionAttribute.nogc;
return cast(SetFunctionAttributes!(T, functionLinkage!T, 
attrs)) t;

}

private struct Dispatcher {
public template opDispatch(string name){
auto ref opDispatch(Args...)(auto ref Args args) {
import std.stdio;
// Print args here for debugging purposes
assumeNoGC({ writeln(args); })();
return 3;
}
}
}

@safe @nogc void main() {
auto i = Dispatcher().getI(3);
}

So, basically with the above, using:
debug writeln(args);
Causes "Error: @nogc function D main cannot call non-@nogc 
function"


Using:
debug assumeNoGC({ writeln(args); })();
Causes:
Error: @safe function D main cannot call @system function
Error: @nogc function D main cannot call non-@nogc function

Changing attrs in assumeNoGC
enum attrs = functionAttributes!T | FunctionAttribute.nogc | 
FunctionAttribute.safe

Causes same as previous errors

Adding @trusted to declaration of opDispatch gets rid of @safe 
error but I still get "Error: @nogc function D main cannot call 
non-@nogc function". And going through the codebase and figuring 
out where to add @trusted is *very* cumbersome.


I can't figure out how to make this work. The ideal way would be 
just a debug_print() function that works in nogc and safe code. 
I.e. does not affect the attribute inference of templates.


Cheers,
- Ali

[0] https://forum.dlang.org/post/pmf4dm$jmo$1...@digitalmars.com


Re: what are the rules for @nogc and @safe attributes inference?

2018-11-16 Thread Alex via Digitalmars-d-learn

On Friday, 16 November 2018 at 10:25:26 UTC, ikod wrote:
On Thursday, 15 November 2018 at 21:55:18 UTC, Steven 
Schveighoffer wrote:

On 11/15/18 4:09 PM, Adam D. Ruppe wrote:

On Thursday, 15 November 2018 at 21:00:48 UTC, ikod wrote:

what are the rules for @nogc inference?


It attempts it if and only if it is a template.


Well, the general "rule" is, if it's code that must be 
available to the compiler when it's called, then it will be 
inferred.


Examples of code that must be processed every time it's used:

1. Template functions
2. auto-returning functions
3. functions inside templates (like member functions of a 
templated struct)

4. Inner functions

There may be others I didn't think of.

Everything else must be manually attributed. The reasoning is 
that the function may be stubbed in a .di file, and in that 
case, attribute inference wouldn't be possible.


-Steve


Thanks for clarifications, Adam and Steven!

My problem is next code:
=
import std.traits;

T library_func(T)(/*lazy*/ T i)
{
// this fuction can be @nogc or not depending on T 
properties

static if (isArray!T) {
return i ~ i;
}
else
{
return i;
}
}
void user_function_nogc() @nogc
{
int x = 1;
library_func(x+1);
}
void user_function_gc()
{
library_func([1]);
}
void main()
{
}
=
This code compiles as long as `lazy` is commented out. But I'd 
like to have
both lazy parameter and @nogc inferrence for `library_func` so 
that user is not locked to code @nogc or not.


Aha, aha... Interesting!
I had a similar problem with passing a delegate. And it was 
solved:

https://forum.dlang.org/thread/erznqknpyxzxqivaw...@forum.dlang.org

For your problem, there is a bug report:
https://forum.dlang.org/post/wedwfooqdxbwxttpm...@forum.dlang.org
https://issues.dlang.org/show_bug.cgi?id=12664
https://issues.dlang.org/show_bug.cgi?id=12647


Re: Sorting a subrange

2018-11-16 Thread Stanislav Blinov via Digitalmars-d-learn

On Friday, 16 November 2018 at 11:24:20 UTC, Per Nordlöw wrote:


/** Sort sub-range [sub_begin, sub_end] of [begin, end].
 *
 * Describe at 
https://www.youtube.com/watch?v=0WlJEz2wb8Y=2686s

 */
template// I models RandomAccessIterator
void sort_subrange(I begin, I end,
   I sub_begin, I sub_end)
{
if (sub_begin == sub_end) { return; }
if (sub_begin != begin)
{
std::nth_element(begin, sub_begin, end);
++sub_begin;
}
std::partial_sort(sub_begin, sub_begin, end);
}


Back-of-the-envelope translation (probably some error checking 
would be in order):


import std.range.primitives : isRandomAccessRange;

auto sortSubRange(R)(R range, size_t i, size_t j) if 
(isRandomAccessRange!R) {

import std.algorithm.sorting : topN, partialSort;
size_t start = i;
if (i != 0) {
topN(range, i);
start++;
}
partialSort(range[start .. $], j-start);
return range[i .. j];
}

void main() {
auto x = [1,2,7,4,2,6,8,3,9,3];
auto y = sortSubRange(x, 3, 6);
import std.stdio;
writeln(y); // 3, 3, 4
writeln(x); // ex. 2, 2, 1, 3, 3, 4, 6, 7, 9, 8
}



Sorting a subrange

2018-11-16 Thread Per Nordlöw via Digitalmars-d-learn
How do I sort a subrange of a range `x` where the subrange is 
defined by a lower and upper (in this case exlusive) element 
contained within `x`?


auto x = [1,2,7,4,2,6,8,3,9,3];
auto y = sortSubRange(x, 3,5];

should yield `y` being

[3,3,4]

and `x` being

[a ,3,3,4, b]

where

- a contains the elements 1,2,2 in some undefined order and
- b contains the elements 6,7,8,9 in some undefined order

.


Algorithm was highlighted in C++ at 
https://www.youtube.com/watch?v=0WlJEz2wb8Y=1719s


as

/** Sort sub-range [sub_begin, sub_end] of [begin, end].
 *
 * Describe at https://www.youtube.com/watch?v=0WlJEz2wb8Y=2686s
 */
template// I models RandomAccessIterator
void sort_subrange(I begin, I end,
   I sub_begin, I sub_end)
{
if (sub_begin == sub_end) { return; }
if (sub_begin != begin)
{
std::nth_element(begin, sub_begin, end);
++sub_begin;
}
std::partial_sort(sub_begin, sub_begin, end);
}



Re: what are the rules for @nogc and @safe attributes inference?

2018-11-16 Thread ikod via Digitalmars-d-learn
On Thursday, 15 November 2018 at 21:55:18 UTC, Steven 
Schveighoffer wrote:

On 11/15/18 4:09 PM, Adam D. Ruppe wrote:

On Thursday, 15 November 2018 at 21:00:48 UTC, ikod wrote:

what are the rules for @nogc inference?


It attempts it if and only if it is a template.


Well, the general "rule" is, if it's code that must be 
available to the compiler when it's called, then it will be 
inferred.


Examples of code that must be processed every time it's used:

1. Template functions
2. auto-returning functions
3. functions inside templates (like member functions of a 
templated struct)

4. Inner functions

There may be others I didn't think of.

Everything else must be manually attributed. The reasoning is 
that the function may be stubbed in a .di file, and in that 
case, attribute inference wouldn't be possible.


-Steve


Thanks for clarifications, Adam and Steven!

My problem is next code:
=
import std.traits;

T library_func(T)(/*lazy*/ T i)
{
// this fuction can be @nogc or not depending on T properties
static if (isArray!T) {
return i ~ i;
}
else
{
return i;
}
}
void user_function_nogc() @nogc
{
int x = 1;
library_func(x+1);
}
void user_function_gc()
{
library_func([1]);
}
void main()
{
}
=
This code compiles as long as `lazy` is commented out. But I'd 
like to have
both lazy parameter and @nogc inferrence for `library_func` so 
that user is not locked to code @nogc or not.




Re: Writing Postgresql extension in D

2018-11-16 Thread Bienlein via Digitalmars-d-learn

On Friday, 16 November 2018 at 02:18:11 UTC, Ranjan wrote:
On Thursday, 15 November 2018 at 17:03:55 UTC, Andrea Fontana 
wrote:

On Thursday, 15 November 2018 at 13:05:59 UTC, Ranjan wrote:
This is my first time on the Dlang forum. I like the language 
but my usecase is a bit different.


I want to write Postgresql extension in D. Currently 
extension can be written in C or C linked languages. Has 
anyone done this or can point me to some code.


Thanks


Did you read this: https://dlang.org/spec/interfaceToC.html ?

Andrea


Yes, but it's not useful, in Postgesql extension C code needs 
to call D, without GarbageCollection. I am able to do this in 
RustLang but I am not sure how to in D, as it has a GC. Looking 
for examples from the community.


Thanks


I'm not an exert with C nor D. So I might misuderstand the 
issue... You can write a skeleton plugin for postgres in C that 
at init time starts the D runtime. From then on your C skelton 
plugin can call some function in D.