Re: UFCS with implicit "this" ?

2016-08-08 Thread Jonathan M Davis via Digitalmars-d-learn
On Tuesday, August 09, 2016 05:13:44 cy via Digitalmars-d-learn wrote:
> I really like UFCS, which is to say, defining functions outside
> the class/struct to operate on it, but you can still say
> object.function(...) and it'll get rewritten into
> function(object,...).
>
> Only sticky point is the convenience of "this". Like I can go
>
> struct A {
>   bool a;
>   bool b;
>   bool c;
>   bool d;
>   bool foo() {
>   return a && b || c && !d;
>   }
> }
>
> But if I try do do the same thing with "bool bar(A object)" I end
> up with this:
>
> bool bar(A object) {
>   return object.a && object.b || object.c && !object.d;
> }
>
> My example is a bit contrived, but it occurred to me how neat it
> would be if we could just specify "implicit" objects in our
> current scope.

Personally, I think that you should just make it a member function if it's
not a generic function, but to each their own, I suppose. Regardless,
there's already a feature to do what you're looking for - with statements.
e.g.

bool bar(A object)
{
with(object)
return a && b || c && !d;
}

https://dlang.org/spec/statement.html#WithStatement

- Jonathan M Davis



UFCS with implicit "this" ?

2016-08-08 Thread cy via Digitalmars-d-learn
I really like UFCS, which is to say, defining functions outside 
the class/struct to operate on it, but you can still say 
object.function(...) and it'll get rewritten into 
function(object,...).


Only sticky point is the convenience of "this". Like I can go

struct A {
bool a;
bool b;
bool c;
bool d;
bool foo() {
return a && b || c && !d;
}
}

But if I try do do the same thing with "bool bar(A object)" I end 
up with this:


bool bar(A object) {
return object.a && object.b || object.c && !object.d;
}

My example is a bit contrived, but it occurred to me how neat it 
would be if we could just specify "implicit" objects in our 
current scope. Like I was messing with an RGB and an HSL object, 
and I ended up having things like:


hsl.saturation = (max(rgb.r,rgb.g,rgb.b) - 
min(rgb.r,rgb.g,rgb.b)) / (2 - max(rgb.r,rgb.g,rgb.b) - 
min(rgb.r,rgb.g.rgb.b))


when I wanted something more like this:

saturation = (max(r,g,b) - min(r,g,b)) / (2 - max(r,g,b) - 
min(r,g,b)


Is there any way to do that in D? They don't let you use "alias 
this rgb" for a function scope, only a type's scope, so I guess 
it isn't possible?


I mean, aside from making an inner structure to the function, and 
copying the object by value... that's even more confusing than 
worth the convenience.


Re: Pass RegexMatch to a function?

2016-08-08 Thread Jonathan M Davis via Digitalmars-d-learn
On Tuesday, August 09, 2016 01:07:53 Gerald via Digitalmars-d-learn wrote:
> I have a RegexMatch that I want to pass to a function that takes
> the match and replaces various tokens in a string with the match
> and/or individual groups of the match. I'm struggling to figure
> out how to pass a RegexMatch to a function, right now I have code
> like the follows:
>
> RegexMatch regexMatch = matchAll(urlMatch.match,
> regex(tr.pattern, tr.caseless?"i":""));
> string command = replaceMatchTokens(urlMatch.match, regexMatch);
>
> ...
>
> string replaceMatchTokens(string tokenizedText, ref RegexMatch
> match) {
>  string result = tokenizedText.replace("$0", match.match);
>
>  int i = 0;
>  foreach(group; match.captures) {
>  result = result.replace("$" ~ to!string(i), group);
>  i++;
>  }
>  return result;
> }
>
> When I try to compile this, it fails with the follow on the line
> where replaceMatchTokens is declared:
>
> Error: struct std.regex.RegexMatch(R, alias Engine =
> ThompsonMatcher) if (isSomeString!R) is used as a type
>
> I've also tried declaring it as follows:
>
> string replaceMatchTokens(string tokenizedText, ref
> RegexMatch!(string, ThompsonMatcher) match) {
>
> With the following errors:
>
> source/gx/terminix/terminal/terminal.d(1273,28): Error: struct
> std.regex.RegexMatch(R, alias Engine = ThompsonMatcher) if
> (isSomeString!R) is used as a type
> source/gx/terminix/terminal/terminal.d(2701,54): Error: template
> std.regex.match cannot deduce function from argument types
> !()(RegexMatch!(string, ThompsonMatcher)), candidates are:
> /usr/include/dlang/dmd/std/regex/package.d(777,13):
> std.regex.match(R, RegEx)(R input, RegEx re) if (isSomeString!R
> && is(RegEx == Regex!(BasicElementOf!R)))
> /usr/include/dlang/dmd/std/regex/package.d(785,13):
> std.regex.match(R, String)(R input, String re) if (isSomeString!R
> && isSomeString!String)
> /usr/include/dlang/dmd/std/regex/package.d(792,13):
> std.regex.match(R, RegEx)(R input, RegEx re) if (isSomeString!R
> && is(RegEx == StaticRegex!(BasicElementOf!R)))

RegexMatch is a templated type, so if you type RegexMatch, you're not
providing an actual type - just the name of the template used to generate a
type. For instance, if you have

struct S(T)
{
T member;
}

S would be meaningless in most cases. It would be instantiations of S such
as S!int or S!string which would actually be types. Almost always, the
solution when dealing with templated types is to templatize your function
(you can specify the exact instantiation you're using, but that can get
pretty ugly. In this case, what you probably want is something like

string replaceMatchTokens(RM)(string tokenizedText, RM match)
if(std.traits.isInstanceOf(RegexMatch, RM))
{
...
}

- Jonathan M Davis



Pass RegexMatch to a function?

2016-08-08 Thread Gerald via Digitalmars-d-learn
I have a RegexMatch that I want to pass to a function that takes 
the match and replaces various tokens in a string with the match 
and/or individual groups of the match. I'm struggling to figure 
out how to pass a RegexMatch to a function, right now I have code 
like the follows:


RegexMatch regexMatch = matchAll(urlMatch.match, 
regex(tr.pattern, tr.caseless?"i":""));

string command = replaceMatchTokens(urlMatch.match, regexMatch);

...

string replaceMatchTokens(string tokenizedText, ref RegexMatch 
match) {

string result = tokenizedText.replace("$0", match.match);

int i = 0;
foreach(group; match.captures) {
result = result.replace("$" ~ to!string(i), group);
i++;
}
return result;
}

When I try to compile this, it fails with the follow on the line 
where replaceMatchTokens is declared:


Error: struct std.regex.RegexMatch(R, alias Engine = 
ThompsonMatcher) if (isSomeString!R) is used as a type


I've also tried declaring it as follows:

string replaceMatchTokens(string tokenizedText, ref 
RegexMatch!(string, ThompsonMatcher) match) {


With the following errors:

source/gx/terminix/terminal/terminal.d(1273,28): Error: struct 
std.regex.RegexMatch(R, alias Engine = ThompsonMatcher) if 
(isSomeString!R) is used as a type
source/gx/terminix/terminal/terminal.d(2701,54): Error: template 
std.regex.match cannot deduce function from argument types 
!()(RegexMatch!(string, ThompsonMatcher)), candidates are:
/usr/include/dlang/dmd/std/regex/package.d(777,13):
std.regex.match(R, RegEx)(R input, RegEx re) if (isSomeString!R 
&& is(RegEx == Regex!(BasicElementOf!R)))
/usr/include/dlang/dmd/std/regex/package.d(785,13):
std.regex.match(R, String)(R input, String re) if (isSomeString!R 
&& isSomeString!String)
/usr/include/dlang/dmd/std/regex/package.d(792,13):
std.regex.match(R, RegEx)(R input, RegEx re) if (isSomeString!R 
&& is(RegEx == StaticRegex!(BasicElementOf!R)))


Re: encoding ISO-8859-1 to UTF-8 in std.net.curl

2016-08-08 Thread ag0aep6g via Digitalmars-d-learn

On 08/09/2016 12:05 AM, Alexsej wrote:

//header from server
server: nginx
date: Mon, 08 Aug 2016 22:02:15 GMT
content-type: text/xml; Charset=utf-8
content-length: 204
connection: keep-alive
vary: Accept-Encoding
cache-control: private
expires: Mon, 08 Aug 2016 22:02:15 GMT
set-cookie: ASPSESSIONIDSSCCDASA=KIAPMCMDMPEDHPBJNMGFHMEB; path=/
x-powered-by: ASP.NET


Looks like std.net.curl doesn't handle "Charset" correctly. It only 
works with lowercase "charset".


https://github.com/dlang/phobos/pull/4723


Re: encoding ISO-8859-1 to UTF-8 in std.net.curl

2016-08-08 Thread Alexsej via Digitalmars-d-learn

On Monday, 8 August 2016 at 21:11:26 UTC, ag0aep6g wrote:

On 08/08/2016 09:57 PM, Alexsej wrote:

// content in ISO-8859-1 to UTF-8 encoding but I lose
//the Cyrillic "отсутствует или неверно задан параметр"
// I get it "отсутствует или неверно
задан параметр"
// How do I change the encoding to UTF-8 in response


string s = cast(immutable char[])content;
auto f = File("output.txt","w");  // output.txt file in 
UTF-8;

f.write(s);


The server doesn't include the encoding in the Content-Type 
header, right? So curl assumes the default, which is ISO 
8859-1. It interprets the data as that and transcodes to UTF-8. 
The result is garbage, of course.


I don't see a way to change the default encoding. Maybe that 
should be added.


Until then you can reverse the wrong transcoding:


import std.encoding: Latin1String, transcode;
Latin1String pseudo_latin1;
transcode(content.idup, pseudo_latin1);
string s = cast(string) pseudo_latin1;


Tiny rant:

Why on earth does transcode only accept immutable characters 
for input? Every other post here uncovers some bug/shortcoming 
:(


thanks it works.


Re: encoding ISO-8859-1 to UTF-8 in std.net.curl

2016-08-08 Thread ag0aep6g via Digitalmars-d-learn

On 08/08/2016 11:11 PM, ag0aep6g wrote:

Why on earth does transcode only accept immutable characters for input?


https://github.com/dlang/phobos/pull/4722


Re: encoding ISO-8859-1 to UTF-8 in std.net.curl

2016-08-08 Thread Alexsej via Digitalmars-d-learn

On Monday, 8 August 2016 at 21:11:26 UTC, ag0aep6g wrote:

On 08/08/2016 09:57 PM, Alexsej wrote:

// content in ISO-8859-1 to UTF-8 encoding but I lose
//the Cyrillic "отсутствует или неверно задан параметр"
// I get it "отсутствует или неверно
задан параметр"
// How do I change the encoding to UTF-8 in response


string s = cast(immutable char[])content;
auto f = File("output.txt","w");  // output.txt file in 
UTF-8;

f.write(s);


The server doesn't include the encoding in the Content-Type 
header, right? So curl assumes the default, which is ISO 
8859-1. It interprets the data as that and transcodes to UTF-8. 
The result is garbage, of course.


I don't see a way to change the default encoding. Maybe that 
should be added.


Until then you can reverse the wrong transcoding:


import std.encoding: Latin1String, transcode;
Latin1String pseudo_latin1;
transcode(content.idup, pseudo_latin1);
string s = cast(string) pseudo_latin1;


Tiny rant:

Why on earth does transcode only accept immutable characters 
for input? Every other post here uncovers some bug/shortcoming 
:(

//header from server
server: nginx
date: Mon, 08 Aug 2016 22:02:15 GMT
content-type: text/xml; Charset=utf-8
content-length: 204
connection: keep-alive
vary: Accept-Encoding
cache-control: private
expires: Mon, 08 Aug 2016 22:02:15 GMT
set-cookie: ASPSESSIONIDSSCCDASA=KIAPMCMDMPEDHPBJNMGFHMEB; path=/
x-powered-by: ASP.NET



arrays, mmu, addressing choices

2016-08-08 Thread Charles Hixson via Digitalmars-d-learn
I have a rather large array that I intend to build. but much of it will 
only occasionally be used.  Will the unused sections automatically be 
paged out?  If it matters my system is Debian Linux.


This array will be indexed by a ulong.  Is there any reasonable maximum 
size?  I've considered segmented addressing anyway, in case that's 
needed to allow paging, and it will definitely be needed when I get 
around to concurrent processing, with different sections resident in 
different threads.  But if appropriate I could do that from the start.


The questions above are really for a normal array, but I'd also be 
interested in how using an associative array would affect them.


I expect to eventually be using more memory than I have RAM in my 
system, so designing for paging is going to be important.  (Before then 
I'll be adding more RAM and a larger disk drive, but if I complete the 
full design even a large disk is going to be small.)




Re: encoding ISO-8859-1 to UTF-8 in std.net.curl

2016-08-08 Thread ag0aep6g via Digitalmars-d-learn

On 08/08/2016 09:57 PM, Alexsej wrote:

// content in ISO-8859-1 to UTF-8 encoding but I lose
//the Cyrillic "отсутствует или неверно задан параметр"
// I get it "отсутствует или неверно
задан параметр"
// How do I change the encoding to UTF-8 in response


string s = cast(immutable char[])content;
auto f = File("output.txt","w");  // output.txt file in UTF-8;
f.write(s);


The server doesn't include the encoding in the Content-Type header, 
right? So curl assumes the default, which is ISO 8859-1. It interprets 
the data as that and transcodes to UTF-8. The result is garbage, of course.


I don't see a way to change the default encoding. Maybe that should be 
added.


Until then you can reverse the wrong transcoding:


import std.encoding: Latin1String, transcode;
Latin1String pseudo_latin1;
transcode(content.idup, pseudo_latin1);
string s = cast(string) pseudo_latin1;


Tiny rant:

Why on earth does transcode only accept immutable characters for input? 
Every other post here uncovers some bug/shortcoming :(


Re: How do i convert this Makefile to dub

2016-08-08 Thread drug007 via Digitalmars-d-learn

On 08.08.2016 21:48, Adil wrote:

On Monday, 8 August 2016 at 18:45:35 UTC, drug007 wrote:

On 08.08.2016 21:35, Adil wrote:

On Monday, 8 August 2016 at 18:29:54 UTC, Adil wrote:

[...]


One minor addition. I use the Makefile in our CI tool, that inserts
auto-increment numbers in place of git hashes. Numbers are a
familiar. Ex:

make VERSION_STRING=v%build.number%;
make screener-d-debug VERSION_STRING=v%build.number%;

Can i insert a version number when i run dub?

You can do it by using `preBuildCommands` in dub.sdl, see
http://code.dlang.org/package-format?lang=sdl


How can i pass a VERSION_STRING from the cmd line?
I don't know about passing from cli, but you can redirect output to some 
.d file and import it, for example.


encoding ISO-8859-1 to UTF-8 in std.net.curl

2016-08-08 Thread Alexsej via Digitalmars-d-learn

import std.stdio;
import std.net.curl;

void main()
{

string url = "www.site.ru/xml/api.asp";

string data =
"


59538

...
";

auto http = HTTP();
http.clearRequestHeaders();
http.addRequestHeader("Content-Type", "application/xml");
//Accept-Charset: utf-8
http.addRequestHeader("Accept-Charset", "utf-8");

//ISO-8859-1
//http://www.artlebedev.ru/tools/decoder/
//ISO-8859-1 → UTF-8
auto content = post(url, "data", http);
// content in ISO-8859-1 to UTF-8 encoding but I lose
//the Cyrillic "encoding='UTF-8'?>отсутствует или неверно задан параметр"
	// I get it "encoding='UTF-8'?>отсутствует или неверно 
задан параметр"

// How do I change the encoding to UTF-8 in response


string s = cast(immutable char[])content;
auto f = File("output.txt","w");  // output.txt file in UTF-8;
f.write(s);
f.close;
}


Re: How do i convert this Makefile to dub

2016-08-08 Thread Adil via Digitalmars-d-learn

On Monday, 8 August 2016 at 18:45:35 UTC, drug007 wrote:

On 08.08.2016 21:35, Adil wrote:

On Monday, 8 August 2016 at 18:29:54 UTC, Adil wrote:

[...]


One minor addition. I use the Makefile in our CI tool, that 
inserts
auto-increment numbers in place of git hashes. Numbers are a 
familiar. Ex:


make VERSION_STRING=v%build.number%;
make screener-d-debug VERSION_STRING=v%build.number%;

Can i insert a version number when i run dub?
You can do it by using `preBuildCommands` in dub.sdl, see 
http://code.dlang.org/package-format?lang=sdl


How can i pass a VERSION_STRING from the cmd line?


Re: How do i convert this Makefile to dub

2016-08-08 Thread drug007 via Digitalmars-d-learn

On 08.08.2016 21:35, Adil wrote:

On Monday, 8 August 2016 at 18:29:54 UTC, Adil wrote:

I have a Makefile setup that I use to return the latest git tag/commit
from within my program. The setup is as below:



VERSIONED_LIB = myversion.d && rm -f myversion.d
VERSION_STRING ?= $(shell git rev-parse --short HEAD)

makeVersion:
echo "module compileConfig; public string versionString =
\"$(VERSION_STRING)\";" > myversion.d;

mysoftware: makeVersion
dmd -de -O /* compiler flags */ source/myprogrma.d myversion.d
rm -f myversion.d


When i run `make mysoftware` my binary now contains the latest git
commit HASH, which i use for debugging.

How can i mimic the same setup i dub? Is there an alternative to
achieve the same goal?


One minor addition. I use the Makefile in our CI tool, that inserts
auto-increment numbers in place of git hashes. Numbers are a familiar. Ex:

make VERSION_STRING=v%build.number%;
make screener-d-debug VERSION_STRING=v%build.number%;

Can i insert a version number when i run dub?
You can do it by using `preBuildCommands` in dub.sdl, see 
http://code.dlang.org/package-format?lang=sdl


Re: How do i convert this Makefile to dub

2016-08-08 Thread Adil via Digitalmars-d-learn

On Monday, 8 August 2016 at 18:29:54 UTC, Adil wrote:
I have a Makefile setup that I use to return the latest git 
tag/commit from within my program. The setup is as below:




VERSIONED_LIB = myversion.d && rm -f myversion.d
VERSION_STRING ?= $(shell git rev-parse --short HEAD)

makeVersion:
	echo "module compileConfig; public string versionString = 
\"$(VERSION_STRING)\";" > myversion.d;


mysoftware: makeVersion
dmd -de -O /* compiler flags */ source/myprogrma.d myversion.d
rm -f myversion.d


When i run `make mysoftware` my binary now contains the latest 
git commit HASH, which i use for debugging.


How can i mimic the same setup i dub? Is there an alternative 
to achieve the same goal?


One minor addition. I use the Makefile in our CI tool, that 
inserts  auto-increment numbers in place of git hashes. Numbers 
are a familiar. Ex:


make VERSION_STRING=v%build.number%;
make screener-d-debug VERSION_STRING=v%build.number%;

Can i insert a version number when i run dub?


How do i convert this Makefile to dub

2016-08-08 Thread Adil via Digitalmars-d-learn
I have a Makefile setup that I use to return the latest git 
tag/commit from within my program. The setup is as below:




VERSIONED_LIB = myversion.d && rm -f myversion.d
VERSION_STRING ?= $(shell git rev-parse --short HEAD)

makeVersion:
	echo "module compileConfig; public string versionString = 
\"$(VERSION_STRING)\";" > myversion.d;


mysoftware: makeVersion
dmd -de -O /* compiler flags */ source/myprogrma.d myversion.d
rm -f myversion.d


When i run `make mysoftware` my binary now contains the latest 
git commit HASH, which i use for debugging.


How can i mimic the same setup i dub? Is there an alternative to 
achieve the same goal?


Re: string mixup problem with stdin.byLine

2016-08-08 Thread Meta via Digitalmars-d-learn

On Monday, 8 August 2016 at 07:09:55 UTC, torea wrote:

On Monday, 8 August 2016 at 05:17:24 UTC, Dave Akers wrote:

I do believe your problem is with the line...
On Monday, 8 August 2016 at 02:44:20 UTC, torea wrote:

string cleanLine = strip( cast(string)line );
It's casting a char[] to and immutable(char)[], causing the 
mutable buffer from byLine to be used as a string. what you 
want is...

string cleanLine = strip( to!string(line) );
which should make a copy of the mutable buffer.

I still a beginner at D but I think that will fix your problem.

-Dave


Problem fixed!!
Thank you very much for the solution and the explanation!


Alternatively you can use std.stdio.byLineCopy and don't need to 
add the `to!string`. If you are calling to!string on ever line 
there will probably be no performance difference, but if you are 
not, such as only calling to!string on every *second* line or 
something like that, you should stick with byLine and calling 
to!string when needed.


Re: string mixup problem with stdin.byLine

2016-08-08 Thread Seb via Digitalmars-d-learn

On Monday, 8 August 2016 at 07:09:55 UTC, torea wrote:

On Monday, 8 August 2016 at 05:17:24 UTC, Dave Akers wrote:

I do believe your problem is with the line...
On Monday, 8 August 2016 at 02:44:20 UTC, torea wrote:

string cleanLine = strip( cast(string)line );
It's casting a char[] to and immutable(char)[], causing the 
mutable buffer from byLine to be used as a string. what you 
want is...

string cleanLine = strip( to!string(line) );
which should make a copy of the mutable buffer.

I still a beginner at D but I think that will fix your problem.

-Dave


Problem fixed!!
Thank you very much for the solution and the explanation!



You should always carefully read the description and Notes ;-)


Note:
Each front will not persist after popFront is called, so the 
caller must copy its contents (e.g. by calling to!string) when 
retention is needed. If the caller needs to retain a copy of 
every line, use the byLineCopy function instead.


http://dlang.org/phobos/std_stdio.html#.File.byLine

Unfortunately you are not the first one who bumped into this 
problem and this non intuitive behavior of byLine is heavily 
disputed.


Re: method static-ness has no effect on the type?

2016-08-08 Thread Cauterite via Digitalmars-d-learn

On Monday, 8 August 2016 at 10:21:47 UTC, ag0aep6g wrote:




Also thanks for submitting the bug for me.


Re: method static-ness has no effect on the type?

2016-08-08 Thread ag0aep6g via Digitalmars-d-learn

On 08/08/2016 12:14 PM, Cauterite wrote:

On Monday, 8 August 2016 at 10:05:58 UTC, ag0aep6g wrote:

The first assert compares the return types of f1 and f2. They both
return `void`, so everything's fine there.


I think you're mistaken about this. typeof(S.f1) definitely gives the
type of the function, not of the return. Try it out:


Yup. My mistake. It's the same as with & then.



Re: Question regarding Base64 decoding

2016-08-08 Thread Johannes Loher via Digitalmars-d-learn
Am 02.08.2016 um 00:47 schrieb Seb:
> On Monday, 1 August 2016 at 08:53:30 UTC, Kagamin wrote:
>> A bug.
> 
> ... which should be filled at Bugzilla and/or fixed. Thanks! :)

I created a pullrequest: https://github.com/dlang/phobos/pull/4720


Re: Cannot distinguish between template function wtih 0 args and 1 arg

2016-08-08 Thread ag0aep6g via Digitalmars-d-learn

On 08/08/2016 04:36 AM, Engine Machine wrote:

This really makes no sense

Error: template Mem cannot deduce function from argument types
!(cast(eException)1280L, "main.d", 38u, "main.WinMain")(int), candidates
are:
Mem(T, B = eX, string file = __FILE__, uint line = __LINE__, string func
= __FUNCTION__)(size_t bytes)
Mem(T, B = eX, string file = __FILE__, uint line = __LINE__, string func
= __FUNCTION__)()


Going backwards:

func is "main.Winmain" - ok.
line is 38u - ok.
file is "main.d" - ok.
B is cast(eException)1280L - B seems to be a type parameter, can't be a 
value.

T is missing.

The compiler goes forwards, not backwards, of course, so everything is 
mismatched.


[...]

This only occurs when I call it with the non-default template values:

I call it simply like Mem!(T, B, file, line, func)(34).


That doesn't look like the instantiation that causes the error. You've 
got five template arguments here, but in the error there are only four.


Can you post more complete code? Something doesn't add up here.


Re: method static-ness has no effect on the type?

2016-08-08 Thread Cauterite via Digitalmars-d-learn

On Monday, 8 August 2016 at 10:05:58 UTC, ag0aep6g wrote:
The first assert compares the return types of f1 and f2. They 
both return `void`, so everything's fine there.


I think you're mistaken about this. typeof(S.f1) definitely gives 
the type of the function, not of the return. Try it out:


struct S {
void f1(int, string, float) {};
};
static assert(typeof(S.f1).stringof == "void(int, string, 
float)");


( https://dpaste.dzfl.pl/cda66002120a )


Re: method static-ness has no effect on the type?

2016-08-08 Thread ag0aep6g via Digitalmars-d-learn

On 08/08/2016 10:30 AM, Cauterite wrote:

See: https://dpaste.dzfl.pl/2ec6780d4b25


That code is short enough to post it here directly. For easier 
reference, this is it:



struct S {

void f1() {
auto x = 
};

static void f2() {
static assert(!__traits(compiles, {auto x = }));
};
};

static assert(is(typeof(S.f1) == typeof(S.f2))); // ?
static assert(is(typeof() == typeof()));  // ?

static assert(!__traits(isStaticFunction, S.f1));
static assert(__traits(isStaticFunction, S.f2));

void main() {

// call f2;
S.init.f2();

// mov [ebp-4], S.init;
// lea eax, [ebp-4];
// call f1;
S.init.f1();
};


(Aside: no semicolons after function/struct declarations in D.)


We have two methods defined, f1 and f2, where f2 is static but they have
otherwise identical signatures.
We can see from the disassembly that f1 receives a `this` pointer while
f2 does not.
Yet, typeof() == typeof(). This makes no sense, how can the
compiler even know whether to pass a `this` pointer when both methods
have same type?


The first assert compares the return types of f1 and f2. They both 
return `void`, so everything's fine there.


The second assert is a bit more surprising. `` is considered a 
function, but `` is a delegate. Obviously, you can't get a 
proper delegate from just the type. You need an instance of the struct 
for that. So having `` be a delegate would be weird, too.


I don't know why `` is allowed at all. Maybe there is a good 
reason, but it also allows bad stuff like this:



struct S
{
void f1(int x) { import std.stdio; writeln(x); }
}

void main()
{
void function(int x) f = 
f(42); /* prints garbage */
}


This even works in @safe code. It also works when using .funcptr to get 
the function pointer from a delegate. I'v filed an issue:

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


Re: Tracking memory usage

2016-08-08 Thread Cauterite via Digitalmars-d-learn

On Sunday, 7 August 2016 at 00:28:40 UTC, Alfred Pincher wrote:

this is a very nice feature. I hope D has something similar?


If you want to implement that kind of allocation tracking you'll 
probably want to use gc_getProxy()+gc_setProxy(). They're global 
C functions you can access by declaring:

extern(C) gc.gcinterface.GC gc_getProxy() nothrow;
extern(C) void gc_setProxy(gc.gcinterface.GC);

First call gc_getProxy() to get the real GC instance and save it 
somewhere.
Then call gc_setProxy() with your object implementing the GC 
interface functions, and in each function forward to the 
corresponding function of the real GC instance, after any 
statistic-gathering code you want run.


Something like this:

__gshared GC RealGcInstance = gc_getProxy();
__gshared GC MyProxy = new class GC {
// ...
extern(C) void gc_free(void* Ptr) nothrow {
printf("freeing pointer %x\n", Ptr); // or whatever
return RealGcInstance.free(Ptr);
};
// ... etc.
};
gc_setProxy(MyProxy);

I haven't tested this method myself, but it will probably work. 
Refer to 
https://github.com/dlang/druntime/blob/master/src/gc/proxy.d and 
https://github.com/dlang/druntime/blob/master/src/gc/gcinterface.d


Also remember that you can't invoke the GC from inside the proxy 
functions. Using helper functions marked @nogc might make it 
easier to avoid.


Re: callback craziness

2016-08-08 Thread ag0aep6g via Digitalmars-d-learn

On 08/08/2016 02:42 AM, Engine Machine wrote:

So, what about passing in the lambda verses the temp variable?


Nothing. I didn't see a case where it worked one way but not the other. 
If you have code where adding a variable makes things work, please post 
a complete test case.


[...]

My code is as follows and I cannot get 0 parameters working nor passing
the function in directly. These were my original questions to begin with
and haven't been answered. Here is the code I am using.

alias callback(Args...) = @nogc void function(string, int, Args);
@nogc public void foo(Args...)(callback!Args c, Args args, int x) { }

foo((string s, int i) { }, 1);

does not work

nor does

foo!()((string s, int i) { }, 1);


The second one does work. https://dpaste.dzfl.pl/212b467c62a4


Ultimately it would also be nice if the template parameters were deduced
automatically instead of having to specify them. The compiler should be
able to figure out the types supplied parameters.

e.g.,

foo((string s, int i, T x) { }, someT, 1);

instead of

foo!(T)((string s, int i, T x) { }, someT, 1);

should it not?


I think the `callback` template is the problem here.

Template instantiation is a one way street. You generally can't answer 
the question "With what arguments would template Foo need to be 
instantiated to get result Bar?". For starters, multiple different 
arguments may map to the same result, making the reverse ambiguous.


It works when you skip the `callback` template and put the 
function/delegate type directly into the signature:



@nogc public void foo(Args...)(void function(string, int, Args) @nogc c,
Args args, int x)
{}

void main() @nogc
{
foo((string s, int i) { }, 1);

alias T = float;
T someT;
foo((string s, int i, T x) { }, someT, 1);
}



method static-ness has no effect on the type?

2016-08-08 Thread Cauterite via Digitalmars-d-learn

See: https://dpaste.dzfl.pl/2ec6780d4b25

We have two methods defined, f1 and f2, where f2 is static but 
they have otherwise identical signatures.
We can see from the disassembly that f1 receives a `this` pointer 
while f2 does not.
Yet, typeof() == typeof(). This makes no sense, how can the 
compiler even know whether to pass a `this` pointer when both 
methods have same type?


Re: Cannot distinguish between template function wtih 0 args and 1 arg

2016-08-08 Thread Cauterite via Digitalmars-d-learn

On Monday, 8 August 2016 at 02:36:24 UTC, Engine Machine wrote:
Error: template Mem cannot deduce function from argument types 
!(cast(eException)1280L, "main.d", 38u, "main.WinMain")(int), 
candidates are:
Mem(T, B = eX, string file = __FILE__, uint line = __LINE__, 
string func = __FUNCTION__)(size_t bytes)
Mem(T, B = eX, string file = __FILE__, uint line = __LINE__, 
string func = __FUNCTION__)()


From this error message it looks like the `B = eX` parameter is 
not getting matched up against the value `cast(eException)1280L` 
as you are hoping for. Probably because `1280L` is a value and 
it's expecting a type.
Try replacing it with something like `alias B = eX` or `enum B = 
eX`.


Re: string mixup problem with stdin.byLine

2016-08-08 Thread torea via Digitalmars-d-learn

On Monday, 8 August 2016 at 05:17:24 UTC, Dave Akers wrote:

I do believe your problem is with the line...
On Monday, 8 August 2016 at 02:44:20 UTC, torea wrote:

string cleanLine = strip( cast(string)line );
It's casting a char[] to and immutable(char)[], causing the 
mutable buffer from byLine to be used as a string. what you 
want is...

string cleanLine = strip( to!string(line) );
which should make a copy of the mutable buffer.

I still a beginner at D but I think that will fix your problem.

-Dave


Problem fixed!!
Thank you very much for the solution and the explanation!