Re: Making an .exe that executes source file inside itself.

2018-04-26 Thread IntegratedDimensions via Digitalmars-d-learn

On Thursday, 26 April 2018 at 06:18:25 UTC, BoQsc wrote:

On Wednesday, 25 April 2018 at 20:44:10 UTC, u0_a183 wrote:

On Wednesday, 25 April 2018 at 19:54:26 UTC, BoQsc wrote:
On Wednesday, 25 April 2018 at 19:43:31 UTC, Jonathan M Davis 
wrote:
On Wednesday, April 25, 2018 19:19:58 BoQsc via 
Digitalmars-d-learn wrote:
So there has been idea I've got for around few months now: 
making

a software which executable would contain a source file.
A software that anyone could modify by opening an 
executable and
quickly change a few lines of it, rerun an executable, see 
the

changes.

Could this be easily possible with D language, considering 
that sources files can be ran without long slow compilation 
process?


The normal way to do that is to just write a script. In the 
case of D, you can just use rdmd to do it. e.g. if you're on 
a POSIX system, just put


#!/usr/bin/env rdmd

at the top of your .d file and chmod it so that it's 
executable, and it'll run like any other script.


- Jonathan M Davis


Thank you Jonathan for a response.
I was aware of this, and it certainly perfectly works where 
command line/terminal interface is the main tool to control 
the system, a good example would be linux/gnu distributions 
and macOS.
However in Windows while installing D language, I noticed 
that .d source file extension is not associated with neither 
D compiler (dmd.exe) nor D script interpretator (rdmd.exe)
So they can't be ran directly by clicking on those, nor they 
have any icons that show that these source codes are actually 
executable. This is a huge problem, because people that are 
not aware of D language migh be harder to understand that 
source script could be executable, at least - without help 
from some more experienced user.


If the purpose is to make scripts run by clicking them you can 
assign a file type to .d files.


On Windows 10. 
https://www.digitaltrends.com/computing/how-to-set-default-programs-and-file-types-in-windows-10/


Doing so would make the script engine the default program 
instead of a text editor so you might not want to. Or maybe 
assign .dxe and changing the filename before running.


Executable has executable file type for a reason - it 
self-implies that the main function of the file - is to be 
executed.
The problem with making source code files executable is that, 
source code files, might not always be monolithic executable 
code, but a part of a bigger interconnected program.
That would lead to partily working program execution, and most 
of the times guess work of whether source code file was 
supposed to be executed.




This is wrong. All code must be included. All library source code 
is included. If this is infeasible then simply the binaries are 
included. It would be no different than dynamic linking that 
already exists. It doesn't create any new problems.


Sure certain things would need to be worked out properly to 
optimize the experience, but that is obvious. One can't make 
everything perfect though and one shouldn't expect it...


The clear alternative would be: .exe file on which, if 
rightclicked - would open context menu showing posibility of 
"edit/improve this executable". Which would not create 
additional problem mentioned above.





Re: readonly member (but assignable at constructor time)

2018-04-26 Thread Jonathan M Davis via Digitalmars-d-learn
On Friday, April 27, 2018 02:59:16 Dr.No via Digitalmars-d-learn wrote:
> In C# you can have a readonly member assignable either at
> declaration or constructor time, like this:
>
> class C
> {
>readonly myClass mc;
>
>this()
>{
>  mc = new myClass();
>}
>
>
>void doSomething()
>{
>  mc = new myClass(); // wrong! result in compiler error, mc is
> readonly
>}
> }
>
> Does D have something like this natively or there's a way to do
> so with traits/CTFE at runtime?

D has const, though that has some pretty far-reaching repercussions, since
it means that the object can't be mutated at all, and the only member
functions that can be called on it are const or inout.

If you want to specifically make it so that the object is mutable but the
reference can't be assigned to, then it would have to be protected by a
wrapper struct that @disabled opAssign and then either used alias this or
opDispatch to forward calls to the class reference inside the struct. D's
const is transitive and does not have any form of head-const, so const can't
be used in a case like that.

- Jonathan M Davis



readonly member (but assignable at constructor time)

2018-04-26 Thread Dr.No via Digitalmars-d-learn
In C# you can have a readonly member assignable either at 
declaration or constructor time, like this:


class C
{
  readonly myClass mc;

  this()
  {
mc = new myClass();
  }


  void doSomething()
  {
mc = new myClass(); // wrong! result in compiler error, mc is 
readonly

  }
}

Does D have something like this natively or there's a way to do 
so with traits/CTFE at runtime?


bitfields comparison in opEquals

2018-04-26 Thread Per Nordlöw via Digitalmars-d-learn
I have a struct with a mixin(bitfields) containing many small 
bitfields. I also have a class member in the struct.


And because I want the class member to compare by using `is` I 
need to define


bool opEquals(const scope typeof(this) that) const @safe pure 
nothrow @nogc

{
return (this.data == that.data &&
this.context is that.context &&

// these are all bitfields members
// TODO can we do this comparison in one go?
this.lang == that.lang &&
this.pot == that.pot &&
this.manner == that.manner &&
this.senseNr == that.senseNr &&
this.hasUniquePot == that.hasUniquePot &&
this.isHashed == that.isHashed);
}

Is there a way to make the bitfields-comparsion in opEquals run 
faster by somehow checking for its size in words (n) and casting 
it to size_t[n] which can be compared very fast.


Re: Arguments of function as an array.

2018-04-26 Thread Jonathan M Davis via Digitalmars-d-learn
On Thursday, April 26, 2018 21:28:27 Jonathan via Digitalmars-d-learn wrote:
> Is there a way in D to take past arguments as an array?  A like a
> normal Variadic function.  All the arguments should be of the
> same type just as an array.
>
> Basically I want to allow a function like this to be called
> without square brackets.
>
> void fun(int[] intArray) {
>  //...
> }
> void main() {
>  fun([5,6,4]);
> }
>
> Like  this:
>
> void fun(int... intArray) {
>  //typeof(intArray) is `int[]`
> }
> void main() {
>  fun(5,6,4);
> }
>
> Is this doable in D?

For better or worse, D has multiple types of variadic functions. Variadic
templated functions are almost certainly the most commonly used, but what
the spec calls "typesafe variadic functions" result in a dynamic array like
what you're talking about:

https://dlang.org/spec/function.html#typesafe_variadic_functions

- Jonathan M Davis



Re: Arguments of function as an array.

2018-04-26 Thread ag0aep6g via Digitalmars-d-learn

On 04/26/2018 11:28 PM, Jonathan wrote:
Is there a way in D to take past arguments as an array?  A like a normal 
Variadic function.  All the arguments should be of the same type just as 
an array.


Basically I want to allow a function like this to be called without 
square brackets.


void fun(int[] intArray) {
     //...
}
void main() {
     fun([5,6,4]);
}

Like  this:

void fun(int... intArray) {
     //typeof(intArray) is `int[]`
}
void main() {
     fun(5,6,4);
}

Is this doable in D?


void fun(int[] intArray ...) {}

https://dlang.org/spec/function.html#typesafe_variadic_functions

Note that such an array is not garbage collected. It's a slice of the 
stack. Don't return it from the function.


Arguments of function as an array.

2018-04-26 Thread Jonathan via Digitalmars-d-learn
Is there a way in D to take past arguments as an array?  A like a 
normal Variadic function.  All the arguments should be of the 
same type just as an array.


Basically I want to allow a function like this to be called 
without square brackets.


void fun(int[] intArray) {
//...
}
void main() {
fun([5,6,4]);
}

Like  this:

void fun(int... intArray) {
//typeof(intArray) is `int[]`
}
void main() {
fun(5,6,4);
}

Is this doable in D?


Idiomatic way to add examples to dub package

2018-04-26 Thread FreeSlave via Digitalmars-d-learn
Most dub packages are libraries and should provide runnable 
examples.
What's the current idiomatic way to add examples? I used 
sub-packages with dependency on the library and "*" as version 
and running them as dub run :examplename
Now I've noticed vibed uses a different scheme - examples are 
like separate packages that are supposed to ran with --root 
option (if running from the library root directory) and specify 
the dependency with "path" property like here 
https://github.com/vibe-d/vibe.d/blob/master/examples/http_server/dub.json
That involves more typing when running an example but keeps the 
main dub.json independent from examples (no need to specify 
sub-packages)


Also I still don't understand if I need to include 
dub.selections.json in VCS repo. I read somewhere that it should 
be included but vibed examples don't have dub.selections.json. 
E.g. here 
https://github.com/dlang/dub/issues/829#issuecomment-215741874 
jacob-carlborg  said
For applications the dub.selection.json files should be in 
version control, for libraries it should not be


Examples are applications so I thought dub.selections.json should 
be included. But it may be an outdated information.


If there're tutorials on both topics (how to include examples and 
when one should include dub.selections.json in VCS), I would like 
to read them. I could not find any useful info on code.dlang.org 
regarding these issues, while those look like basic issues that 
must be covered in manuals.


Re: What's wrong with this alias?

2018-04-26 Thread Ali Çehreli via Digitalmars-d-learn

On 04/26/2018 10:56 AM, Dr.No wrote:

> class C
> {
>
>  void error(A...)(string fmt, A args)
>  {
>  import report : error;
>  reportedAnyError = true;
>  error(fmt, args);
>  }
>  alias warning = report.warning;
> }
>
>
> I got this:
>
> Error: undefined identifier report.warning

If that really is the code, you're forgetting to import report in that 
scope. Otherwise, that kind of alias works at least in this simple case:


void foo(A...)(A a) {
import std.stdio;
writeln(a);
}

alias bar = foo;

void main() {
bar(42, "hello");
}

Ali



What's wrong with this alias?

2018-04-26 Thread Dr.No via Digitalmars-d-learn

consider this:

module report;

// output an error message on stderr
void error(A...)(string fmt, A args)
{
import colorize : fg, color, cwriteln, cwritefln, cwrite;
stderr.cwrite("error: ".color(fg.yellow));
cwritefln(fmt.color(fg.yellow), args);
}

void warning(A...)(string fmt, A args)
{
import colorize : fg, color, cwriteln, cwritefln, cwrite;
cwrite("warning: ".color(fg.blue));
cwritefln(fmt.color(fg.blue), args);
}

then

class C
{

void error(A...)(string fmt, A args)
{
import report : error;
reportedAnyError = true;
error(fmt, args);
}
alias warning = report.warning;
}


I got this:

Error: undefined identifier report.warning

but this works:

void warning(A...)(string fmt, A args)
{
import report : warning;
warning(fmt, args);
}

why alias cannot find my symbol there?



Re: Get files from directory sorted by name

2018-04-26 Thread Dr.No via Digitalmars-d-learn

On Wednesday, 25 April 2018 at 19:25:11 UTC, Jesse Phillips wrote:

On Wednesday, 25 April 2018 at 17:34:41 UTC, Dr.No wrote:
Is there something implemented already to get the files from 
directory by name using D or I'm on my own and I have to write 
it myself? I didn't find how do that with dirEntries()


I want to add that sorting can be done, if you just call 
std.algorithm.sort you'll find that file names with numbers in 
them will be sorted as a well strings.


Newfile1.txt
Newfile10.txt
Newfile2.txt


I've had realized that then implemented natural sort


Re: Get files from directory sorted by name

2018-04-26 Thread Dr.No via Digitalmars-d-learn
On Wednesday, 25 April 2018 at 18:06:07 UTC, Jonathan M Davis 
wrote:
On Wednesday, April 25, 2018 17:34:41 Dr.No via 
Digitalmars-d-learn wrote:
Is there something implemented already to get the files from 
directory by name using D or I'm on my own and I have to write 
it myself? I didn't find how do that with dirEntries()


There is nothing in the standard library for doing it, though 
maybe someone has something on code.dlang.org. However, the 
underlying OS API doesn't exactly conform well to that 
particular use case. AFAIK, given how the C APIs work, the only 
option is to get the list of files and then sort it, which 
could be done easily enough with dirEntries. Something as 
simple as


auto files = dirEntries(dir, SpanMode.shallow).array();
sort!((a, b) => a.name < b.name)(files);

would give you a sorted DirEntry[] of all of the directories 
and files directly in the directory. SpanMode.depth or 
SpanMode.breadth could be used instead if you want 
sub-directories, and std.algorithm.iteration.filter could be 
used if you want to do something like filter out directories. 
std.algorithm.iteration.map could be used if you just want the 
file names. So, if you wanted just the names, you could do


auto files = dirEntries(dir, SpanMode.shallow).map!(a => 
a.name)().array();

sort(files);

though you'd need to use std.path.baseName if you didn't want 
the full path
- e.g. map!(a => a.name.baseName)(). If you wanted just files, 
you could do

something like

auto files = dirEntries(dir, SpanMode.shallow).
 filter!(a => a.isFile()).array();
sort!((a, b) => a.name < b.name)(files);

or

auto files = dirEntries(dir, SpanMode.shallow).
 filter!(a => a.isFile()).map!(a => a.name).array();
sort(files);

Exactly which combination of functions you use depends on what 
you want for the end result. But the key thing is that you use 
std.array.array to convert the forward range into a dynamic 
array so that std.algorithm.sorting.sort can sort it (since it 
requires a random-access range). I really don't think that 
you're going to find any other way to do this other than 
someone who has written a function that just ends up doing the 
same thing by wrapping a call to dirEntries or the underlying C 
API.


- Jonathan M Davis


I have had just called sort, to later realize the sort wasn't in 
the way humans expect (which is the way Windows Explorer does) so 
I eventually reached 
https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ but I failed to call StrCmpLogicalW() from core.sys.windows.shlwapi or link on my own:


pragma(lib, "Shlwapi.lib")
extern(Windows) int StrCmpLogicalW(
  PCWSTR psz1,
  PCWSTR psz2
);

but I got links error so I went to implement StrCmpLogicalW() on 
my own and sorted like this:


auto files = dirEntries(inputDir, SpanMode.shallow).array();
// natural sort
sort!((a, b) => StrCmpLogical(a, b) < 0)(files);

which resulted in the files in same way as Windows 
Explorer/Natural sort.






Re: Template to retrieve compile-time enum member from run-time enum member?

2018-04-26 Thread Simen Kjærås via Digitalmars-d-learn

On Thursday, 26 April 2018 at 16:10:16 UTC, Timoses wrote:
Is it possible to use a template to place the "static foreach" 
looping to find the correct enum value into? Like I am trying 
in the initial "draft" GetMenum?


As the compiler says, the value of `e` is not known at 
compile-time. In order to correctly instantiate the template with 
that value, all possible instantiations must be instantiated, and 
the correct one chosen by a static foreach, just like you do.


The only step you're missing is the template needs to be 
instantiated inside the static foreach, like this:


auto instantiateWith(alias Fn, T)(T x)
if (is(T == enum))
{
import std.traits : EnumMembers;
switch (x)
{
static foreach (e; EnumMembers!T)
case e:
return Fn!e;
default:
assert(false);
}
}

enum menum { A, B, C }

template Temp(menum m)
{
enum Temp = m.stringof;
}

unittest {
menum m = menum.A;
import std.stdio;
assert(instantiateWith!Temp(m) == Temp!(menum.A));
m = menum.B;
assert(instantiateWith!Temp(m) == Temp!(menum.B));
m = menum.C;
assert(instantiateWith!Temp(m) == Temp!(menum.C));
}

--
  Simen


Template to retrieve compile-time enum member from run-time enum member?

2018-04-26 Thread Timoses via Digitalmars-d-learn

The following should depict what I'm trying to achieve:


```
import std.stdio;

enum menum { A, B, C }

void main()
{
   foo(menum.B);
}

void foo(menum e)
{
// Not possible
// run time variable 'e' in conjunction with template 'Temp'
writeln(Temp!(GetMenum(e)));
}

static int i = 0;

template Temp(menum e)
{
// ... do stuff
shared static this()
{
static if (e == menum.A)
i = 1;
}

import std.meta : Alias;
alias Temp = Alias!i;
}

// Trying to return a compile-time variable with a function... 
Not like this...
// I don't see a way to pass in the run-time variable without a 
function..

template GetMenum()
{
menum GetMenum(menum e)
{
import std.traits : EnumMembers;
static foreach(mem; EnumMembers!menum)
if (mem == e)
return mem;

return menum.A;
}
}
```

yields: Error: variable e cannot be read at compilte time

However, if I replace foo with
```
void foo(menum e)
{
import std.traits : EnumMembers;
static foreach(mem; EnumMembers!menum)
if (mem == e)
writeln(Temp!(GetMenum(mem)));
}
```
it works..

Is it possible to use a template to place the "static foreach" 
looping to find the correct enum value into? Like I am trying in 
the initial "draft" GetMenum?


Re: Troubles with template constraints on string and static if

2018-04-26 Thread Alex via Digitalmars-d-learn

On Thursday, 26 April 2018 at 15:06:49 UTC, sungal wrote:
I have this piece of code and I can't understand why the 
`static if` conditionals are always false.


```
import std.digest.sha;
import std.file;
import std.stdio;

void main()
{
auto hash1 = produceHash!string("prova.d");
auto hash2 = produceHash!File(File("./prova.d"));
}

string produceHash(Type)(Type data)
if(is(Type == string) || is(Type == File))
{
string h;
static if(is(Type == File)) {
enforce(data.exists, "File does not exist.");
// Hashing both name and file, to avoid having the same 
Hash on empty files
return 
toHexString(digest!SHA256(data.byChunk(4096*1024))).dup;

} else static if(is(Type == string)){
return toHexString(digest!SHA256(data)).dup;
}
static assert(false, "Data must be string or file. ");
}
```

```
prova.d(22): Error: static assert  "Data must be string or 
file. "

prova.d(7):instantiated from here: produceHash!string
```


The static assert is unconditionally evaluated after the static 
if/else clause. This leads to a compile time assertion failure.

Add an "else", maybe.


Troubles with template constraints on string and static if

2018-04-26 Thread sungal via Digitalmars-d-learn
I have this piece of code and I can't understand why the `static 
if` conditionals are always false.


```
import std.digest.sha;
import std.file;
import std.stdio;

void main()
{
auto hash1 = produceHash!string("prova.d");
auto hash2 = produceHash!File(File("./prova.d"));
}

string produceHash(Type)(Type data)
if(is(Type == string) || is(Type == File))
{
string h;
static if(is(Type == File)) {
enforce(data.exists, "File does not exist.");
// Hashing both name and file, to avoid having the same 
Hash on empty files
return 
toHexString(digest!SHA256(data.byChunk(4096*1024))).dup;

} else static if(is(Type == string)){
return toHexString(digest!SHA256(data)).dup;
}
static assert(false, "Data must be string or file. ");
}
```

```
prova.d(22): Error: static assert  "Data must be string or file. "
prova.d(7):instantiated from here: produceHash!string
```


Re: Making an .exe that executes source file inside itself.

2018-04-26 Thread JN via Digitalmars-d-learn

On Wednesday, 25 April 2018 at 19:19:58 UTC, BoQsc wrote:
So there has been idea I've got for around few months now: 
making a software which executable would contain a source file.
A software that anyone could modify by opening an executable 
and quickly change a few lines of it, rerun an executable, see 
the changes.


Could this be easily possible with D language, considering that 
sources files can be ran without long slow compilation process?


If it makes sense for your project, you could embed a scripting 
language with LuaD or PyD and rerun the script whenever it 
changes.


Alternatively, I don't know about specifics how to implement it 
in D, but the key phrase you are looking for is "code hotswap" or 
"hot loading". It's being popularized right now in gamedev 
circles, to avoid slow complications of the code. The way to do 
it is push code into DLLs, then reload the DLL if the change is 
detected. Of course it's not that simple, because there are some 
tricky parts around DLL boundaries and you have to reload the 
entire state, but it is possible. In such case, rather than 
recompile the entire code, you can just recompile a small subset 
of functionality to a DLL.


Re: Using an external Assembler with D

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

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

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

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


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


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