Re: Is it possible to use templates to implement something like the `@show` macro from the Julia programming langauge in D?

2024-09-09 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 8 September 2024 at 22:01:10 UTC, WraithGlade wrote:
Basically, I want there to be a way to print both an expression 
and its value but to only have to write the expression once 
(which also aids refactoring). Such a feature is extremely 
useful for faster print-based debugging.

[...]
I want to just be able to write this:

```
show!(1 + 2)
```


Try this:

```
import core.interpolation;
void show(Args...)(InterpolationHeader hdr, Args args, 
InterpolationFooter ftr) {

import std.stdio;
foreach(arg; args) {
static if(is(typeof(arg) == 
InterpolatedExpression!code, string code))

write(code);
else static if(is(typeof(arg) == 
InterpolatedLiteral!str, string str))

write(str);
else
write(" = ", arg);
}
writeln();
}
```


Used like:

```
void main() {
int a = 5, b = 22;
show(i`$(a), $(b), $(a + b)`);
}
```

Output:

a = 5, b = 22, a + b = 27


You can show as many expressions as you want in there, each 
$() thing is expanded to `code inside = result`.


So

show(i"$(1 + 2)"); // prints 1 + 2 = 3


The interpolated sequence syntax makes it a bit heavier: that 
`i"$(  )"` around it is required here, but it works anyway.


Re: Mixin Templates and Operators

2022-04-06 Thread Adam D Ruppe via Digitalmars-d-learn
On Wednesday, 6 April 2022 at 10:36:04 UTC, francesco.andreetto 
wrote:
Am I doing something wrong or it is impossible to use mixin 
templates like that?


mixin templates can't bring in operator overloads. The spec 
doesn't really say this I think, but that's the way it has been 
for a long time.


It only checks for operator overloads on the direct thing itself, 
no UFCS, no mixin template.


Re: Mixin Templates and Operators

2022-04-06 Thread Adam D Ruppe via Digitalmars-d-learn
On Wednesday, 6 April 2022 at 17:33:28 UTC, Steven Schveighoffer 
wrote:
As I mentioned elsewhere, it does work. But the situation I 
think must be that it's only one mixin template. Probably also 
you can't have any overloads in the type itself.


ooh yeah there's multiple here so the names don't 
overload and one on the time itself would override the ones from 
mixin template.


You'd have to alias them together on the type.


Re: Looking for a workaround

2022-04-06 Thread Adam D Ruppe via Digitalmars-d-learn
On Wednesday, 6 April 2022 at 18:10:32 UTC, Guillaume Piolat 
wrote:

Any idea how to workaround that?


Works fine if you just use the language instead of the buggy 
phobos wrappers:


---
struct MyUDA
{
}

class A
{
@MyUDA int a;
}

class B : A
{
@MyUDA int b;
}

void main()
{
foreach(memberName; __traits(allMembers, B))
foreach(attr; __traits(getAttributes, __traits(getMember, 
B, memberName)))

static if(is(attr == MyUDA))
pragma(msg, memberName); // a, b
}
---

So make a function that does that and applies whatever it is you 
need to apply and you're in business.


Note that it is `is(typeof(attr) == MyUDA)` if defined 
`@MyUDA(args)`.


Re: arsd-minigui - couple of questions

2022-04-11 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 11 April 2022 at 12:40:29 UTC, sai wrote:
One more request, is it possible for you to do to ImageBox what 
you did to Button to show the transparent images (png)? Because 
Imagebox is showing black color for transparent pixels.


oh yeah this one is different because the imagebox custom draws 
it, so it is really as simple as passing `true` to the opacity 
there too when it converts.


Try this diff:

https://github.com/adamdruppe/arsd/commit/912047ccdda7e7775f64431a631519e6024d2494

i think it fixes it, let me know.


Re: CTFE and BetterC compatibility

2022-04-27 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 27 April 2022 at 14:21:15 UTC, Claude wrote:
The operation requiring the D-runtime is appending the array, 
but it should **only** be done at compile-time.


In that case, you want to prove to the compiler it is only called 
at compile time by encapsulating the function inside a template 
or defining it immediately where it is called.


Delete the stand-alone function `parse` and instead call it like 
this:


```
// define it
enum Data parsedData = function Data (string str) pure
{
Data data;

while (str.length != 0)
{
// Skip spaces
while (str[0] == ' ')
str = str[1 .. $];

// Parse single digit integer
data.digits ~= parseDigit(str[0]);

// Consume digit
str = str[1 .. $];
}

return data;
} ("5 4 2 6 9"); // and call it in the same place
```



Or if you want it to be independently defined still, you can 
define it inside a helper template but you'd have to return a 
basic type instead of Data, so I think calling it immediately is 
what you want to do here.



There was going to be a ctfe-only thing you could put in the 
function so the compiler doesn't try to generate the runtime 
version, but this got killed due to internal D politics. A pity.


Re: Library for image editing and text insertion

2022-04-27 Thread Adam D Ruppe via Digitalmars-d-learn
On Wednesday, 27 April 2022 at 14:40:59 UTC, Alexander Zhirov 
wrote:

Gorgeous! LDC has compressed my code at times!


How small did it get?

And with my libs if you import the other ones like `arsd.png` or 
`arsd.jpeg` directly instead of `arsd.image` that MIGHT help trim 
it down by removing support for other formats.  I'm not sure 
though, none of them are especially big but it might add up.


Re: Library for image editing and text insertion

2022-04-27 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 27 April 2022 at 17:07:54 UTC, matheus wrote:
I know about Adam Ruppe's work, I already used his terminal.d, 
but I think that unfortunately most people don't and I think it 
should be announced more in these parts.


tbh sometimes i just don't feel like answering messages. even 
this one, i was like "i can do that easily, but do i want to 
support another user?"


but meh i had a few mins to kill anyway


For me arsd is for D what stb is for C.


Note that a few of those modules are stb ports over to D.

I wrote the png and bmp modules myself, for example, but the jpeg 
is a port from C (that port done by ketmar on irc) and the ttf 
one is stb_ttf ported to D then with a little wrapper struct 
pasted on top.


One thing I'm kinda proud of though is my OperatingSystemFont 
class in simpledisplay which can load a font and then pass it 
into the ttf thing and/or the nanovega module for all kinds of 
custom effects. You don't necessarily have to package your own 
ttf files!


Re: How do I get the screen resolution?

2022-04-28 Thread Adam D Ruppe via Digitalmars-d-learn
On Thursday, 28 April 2022 at 11:22:15 UTC, Alexander Zhirov 
wrote:

Are there any methods to get the screen resolution?


Call DisplayWidth/DisplayHeight on the X connection... my 
simpledisplay.d provides bindings (though not a high level helper 
function since both X and Windows calls are trivial)


On C/C++ from under X11, it is not possible to do this on the 
command line via SSH, since the display is not defined.


Just defined the display, that's easy.


import std.process;
enviornment["DISPLAY"] = ":0";

that can work with any lib, then connect.


OR, with my lib, it is all included:

---
import arsd.simpledisplay;

XDisplayConnection.setDisplayName(":0"); // set the local name 
regardless of what is set on ssh

auto connection = XDisplayConnection.get(); // connection

import std.stdio;
writeln(DisplayWidth(connection, 0), " x ", 
DisplayHeight(connection, 0)); // the 0 is the screen number

---


Though note with a multiple monitor system, this will give the 
*full* size of the virtual screen, not individual screens.


simpledisplay has methods for this. but I marked it `private` 
and it only loads the data when a window is created... you COULD 
hack past this anyway but prolly not worth the hassle. Maybe I 
will make it public officially in the next release.


But if you are desperate for the info now, here's how you can 
bypass private and get at it anyway:


---
// use reflection to bypass `private`
alias MonitorInfo = __traits(getMember, 
arsd.simpledisplay.SimpleWindow, "MonitorInfo");


// make a temporary window just to get the info
auto window = new SimpleWindow(1, 1, null, OpenGlOptions.no, 
Resizability.fixedSize, WindowTypes.eventOnly);


// this is the function that actually loads the monitor info
window.actualDpi();

// make sure none waiting in a buffer
flushGui();

// and now get the data out
foreach(monitor; MonitorInfo.info) {
writeln(monitor.position.size);
}

window.close();
---


But since you're bypassing private and poking internals, if/when 
I do decide to make this public instead of private, I'll probably 
break this approach (when it is public though you can just simply 
loop over the info).


Re: CTFE and BetterC compatibility

2022-04-28 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 28 April 2022 at 12:36:56 UTC, Dennis wrote:
In this case, it was actually a trailing whitespace in the 
changelog entry making the test suite fail, but the PR author


Stefan's own `assert(__ctfe);` approach was better anyway...


Re: What's a good way to disassemble Phobos?

2022-04-30 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 30 April 2022 at 18:18:02 UTC, Dukc wrote:
I'm looking for something where I could search for the call to 
the DRuntime functions in question, from an already combined .o 
or .a. What do you suggest? I'm on Linux.


objdump -d works on .o files


Re: How to get compatible symbol names and runtime typeid names for templated classes?

2022-05-03 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 3 May 2022 at 09:42:45 UTC, cc wrote:

something I can pass to `Object.factory`.


Object.factory is useless and will hopefully be removed someday.

Instead, make your own factory registration function.

Put a static constructor in the class which appends a factory 
delegate to an array or something you can use later. Then you can 
use your own thing to construct registered objects.


Re: How to get compatible symbol names and runtime typeid names for templated classes?

2022-05-03 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 3 May 2022 at 13:25:14 UTC, Arafel wrote:
I'd like to do a runtime registration system myself, using a 
"template this" static constructor. A simple version supporting 
only default constructors would be:


Yeah, you can't template this a static constructor, but you can 
just use a static constructor. It will have to be mixed into each 
child class though, and the compiler won't help to remind you.


But do something along the lines of:


```d
module factory.register;

private Object function()[string] factories;

Object construct(string name) {
if(auto f = name in factories)
return (*f)();
return null;
}

mixin template Register() {
static this() {
import factory.register;

alias This = typeof(this);

// bypassing private
__traits(getMember, factory.register, "factories")
[This.mangleof] = function Object() {
// you could even delegate to a static
// function if one is present, or pass 
arguments
// etc. this impossible with 
Object.factory

return new This();
};
}
}
```

That code is your library. Then, to use it:


```d
import factory.register;

class MyThing {
// you have to remember to do this in each child
mixin Register;
}

void main() {
auto t = new MyThing();

// I used the mangle instead of the FQN since it
// is easier.
Object o = construct(typeof(t).mangleof);
MyThing t2 = cast(MyThing) o;
assert(t2 !is null); // assert it actually worked
}
```




Now, you can extend this a little if you're willing to add an 
interface too. And if you forget to register the base class, the 
interface method being not implemented will remind user they did 
something wrong, and you can runtime assert to check child 
classes.


Check this out:


```d
module factory.register;

private Object function()[string] factories;

Object construct(string name) {
if(auto f = name in factories)
return (*f)();
return null;
}

// adding this for the assert
bool typeIsRegistered(string name) {
return (name in factories) !is null;
}

// this interface gives runtime access to the info we need
interface Serializable {
string typeCode() const;
}

mixin template Register() {
// interface implementation
override string typeCode() const {
// casting away const for more consistent names
alias no_const = typeof(cast() this);

auto name = no_const.mangleof;

// a runtime check to help remind you if 
something not registered

import factory.register;
assert(typeIsRegistered(name), "Type 
"~typeof(this).stringof~" not registered!");


// also making sure the child class was registered
// by ensuring the runtime type is the same as 
the static type
assert(typeid(this) == typeid(no_const), "Child 
class "~typeid(this).toString()~" was not registered!");


return name;
}

static this() {
import factory.register;

alias This = typeof(this);

// bypassing private
__traits(getMember, factory.register, "factories")
[This.mangleof] = function Object() {
// you could even delegate to a static
// function if one is present, or pass 
arguments
// etc. this impossible with 
Object.factory

return new This();
};
}
}


```


And the usage:


```d

import factory.register;

class MyThing : Serializable {
mixin Register;
}

class Child : MyThing {
// forgot to register uh oh
// mixin Register;
}

void main() {
auto t = new MyThing();

Object o = construct(typeof(t).mangleof);
MyThing t2 = cast(MyThing) o;
assert(t2 !is null);

auto child = new Child();
// if we called this in the serialize function or even 
one of those constructors' contracts
// it can verify things work by triggering the asserts 
back in the library implementation

child.typeCode();
}
```



So doing things yourself gives you some control.


Re: How to get compatible symbol names and runtime typeid names for templated classes?

2022-05-03 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 3 May 2022 at 14:38:53 UTC, Arafel wrote:
Actually, it would be cool to do it through an interface, 
although I don't think an interface's static constructors are 
invoked by the implementing classes... it would be cool, though.


yeah interfaces can't have constructors.

I'd try it myself, but I wouldn't know where to start. Compiler 
internals are way beyond my comfort zone...


Believe it or not, you don't need to touch the compiler. Open 
your druntime's object.d and search for `RTInfo`


http://druntime.dpldocs.info/object.RTInfo.html

That is instantiated for every user defined type in the program 
and you have the compile time info. all druntime uses it for 
is a tiny bit of GC info and even then only sometimes.


But it could do so so so much more. Including doing custom 
factories and runtime reflection buildups!


Re: How to get compatible symbol names and runtime typeid names for templated classes?

2022-05-03 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 3 May 2022 at 16:38:23 UTC, cc wrote:

This is really interesting syntax, I'm surprised that works!


Can read a little more on my blog about it:

http://dpldocs.info/this-week-in-d/Blog.Posted_2019_06_10.html#tip-of-the-week

pretty cool little pattern.


Re: Google Code Jam 2022

2022-05-06 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 6 May 2022 at 04:26:13 UTC, Siarhei Siamashka wrote:

So it may seem that D should be a very good choice for
programming competitions, but there's still no success.


Programming competitions are a 100% waste of time. I'm too busy 
doing real work.


Re: What are (were) the most difficult parts of D?

2022-05-11 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 12 May 2022 at 01:06:02 UTC, Christopher Katko wrote:
completely different semantics for a class vs a struct. Is it a 
reference? Is it a value? Look up the entire declaration and 
have the entire Dlang manual open to find out.


As far as I remember, no automatic RAII support, even though 
it's insanely useful.


class = virtual functions

struct = RAII




Re: What are (were) the most difficult parts of D?

2022-05-12 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 12 May 2022 at 14:42:43 UTC, Anonymouse wrote:
That said, one thing I cannot seem to firmly wrap my head 
around is `is` expressions. `is` does so many things.


It is simpler than it looks, I wrote about it in my book and in a 
post here:


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


```
alias AA = long*[string];
static if (is(AA whatEvenGoesHere : VP[K], VP, K))


You don't have to put anything there. The is expression kinda 
parallels declarations, so that thing would be the name for the 
newly declared symbol. But you don't need to declare a new symbol 
there so you can leave it blank; most the pieces are optional.


The one thing that has caused me most anguish and woe is 
hands-down https://issues.dlang.org/show_bug.cgi?id=18026 
though.


yeah bugs happen.


Re: What are (were) the most difficult parts of D?

2022-05-12 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 12 May 2022 at 15:18:34 UTC, jmh530 wrote:

What's the difference between a Type and Type Identifier?


The is expression roughly follows variable declaration style.

You write

int a;

to declare a new symbol named `a` of type `int`.

Similarly,

static if(is(T a))

declares a new symbol of type `a` if `T` is a valid type. (Of 
course, in this case, a and T are aliases of each other, so it 
isn't super useful, but in the more complex matches using the == 
and : operators, it might be different.)


The Identifier is optional.


Re: What are (were) the most difficult parts of D?

2022-05-13 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 13 May 2022 at 18:23:58 UTC, H. S. Teoh wrote:

On Thu, May 12, 2022 at 11:45:47PM +, Guillaume Piolat via
It's a problem because it goes from solving "no accidental 
race condition" and you get "people forget to add shared or 
__gshared and their shared library silently fail" situation. 
You could have none of that with explicit TLS.


Valid point.


Yeah, I used to be pro-TLS by default, then got bit by it several 
times and moved to the fence, and now I'm anti.


Data races aren't actually prevented by it (maybe forcing you to 
specify shared or tls would at least get you think about it 
though) and lots of things mysteriously fail if you forget about 
it.


You can lock the variable and everything and it still null cuz it 
was tls the whole time. Oops.


This a case where I think forcing explitness would be better than 
either default, but failing that, tls by default is the more-bad 
choice.


Re: D WebAssembly working differently than C++, Zig

2022-05-16 Thread Adam D Ruppe via Digitalmars-d-learn
I would suspect it is something to do with your memset... even if 
it needs to take the int (wtf but ldc is weird) you might want to 
reinterpret cast it to float to avoid any extra conversions.


Re: D WebAssembly working differently than C++, Zig

2022-05-17 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 16 May 2022 at 18:17:03 UTC, Allen Garvey wrote:
Thanks so much, that fixed the problem! You have no idea have 
long I have spent trying to debug this!


Oh I should have checked my impl, where I did all this already!

https://github.com/adamdruppe/webassembly/blob/master/arsd-webassembly/object.d#L263


And also might be able to just have the function forward to the 
ldc intrinsic:


https://github.com/ldc-developers/druntime/blob/ldc/src/ldc/intrinsics.di#L160

might help speed up a lil too, i don't know though (I didn't do 
it here for me)


Re: D WebAssembly working differently than C++, Zig

2022-05-17 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 17 May 2022 at 11:43:45 UTC, Siarhei Siamashka wrote:
Looks like you forgot to increment the pointer and need "*d++ = 
cast(ubyte) c;" there.



hahaha yup.


And filling the buffer one byte at a time is likely slow.


prolly but meh, that's where the intrinsics are nice.


Re: Why are structs and classes so different?

2022-05-17 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 17 May 2022 at 14:40:48 UTC, Kevin Bailey wrote:

Foo foo;

is undefined behavior waiting to happen, that I can't detect at 
a glance.


It is actually perfectly well defined - for the class, it will be 
null, and this will kill the program if you use it.


You might not like that definition, but that's how it is defined.

- A *secondary* goal would be for class objects to be able to 
have deterministic destructors like structs.


they can with the `scope` keyword.


The first looks trivial: Just have it allocate a Foo by default.


Worth noting that D *never* calls a user defined function on 
variable declaration; there are no default constructors.


Even if it is a struct, it never actually calls a constructor, it 
just copies over the default init value.


This is different than classes, which have some kind of 
constructor call any time you make one.



I think it is probably this default constructor stance that the 
rest flows from: a class is assumed to encapsulate some 
non-trivial state so it has a constructor, interfaces, object 
identities, etc. A struct is more of a plain collection of data.


Of course, in practice the lines are more blurred than that, but 
I think that's where it comes from. Especially if you look at the 
older D versions when structs didn't support constructors at all.


Re: Error: undefined symbol: _WinMain@16 When try compile no console

2022-05-19 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 19 May 2022 at 19:29:25 UTC, Marcone wrote:

Using -L/SUBSYSTEM:windows user32.lib


you using a main() function right?

Please note when compiling on Win64, you need to explicitly list 
-Lgdi32.lib -Luser32.lib on the build command. If you want the 
Windows subsystem too, use -L/subsystem:windows 
-L/entry:mainCRTStartup.


If using ldc instead of dmd, use -L/entry:wmainCRTStartup instead 
of mainCRTStartup; note the "w".



see some deets i wrote here

http://arsd-official.dpldocs.info/arsd.simpledisplay.html#installation-instructions


Re: Error: undefined symbol: _WinMain@16 When try compile no console

2022-05-19 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 19 May 2022 at 20:20:49 UTC, Marcone wrote:

I am using a main() function.
I am compiling on Windows x86 32 bits.
I am using DMD 2.100.0
This error is only in version 2.100.0 of DMD.


Are you using the `-L/entry:mainCRTStartup` or the 
`L/entry:wmainCRTStartup` ?


Re: UI Library

2022-05-20 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 20 May 2022 at 03:47:14 UTC, harakim wrote:

Thank you. I will definitely give that a try.


My minigui uses the normal Windows controls so it works well 
there. On linux it uses a custom thing of my own design so your 
mileage may vary.


The docs don't have a lot of examples but hopefully one you do 
the first one the rest won't be too hard, the classes are 
relatively simple and the events are based on javascript so if 
you've used that before you can probably get to know it.


But just ask me if something comes up since I can push fixes to 
master p quickly.


The only files it needs from the repo are `minigui.d`, 
`simpledisplay.d` and `color.d`. There's other optional things in 
there that might be useful though. My recommended way to use it 
is to `git clone` the repo in your source dir then `dmd -i 
yourfile.d` so it is easy to update with a `git pull` and the 
compiler pulls what it needs (and nothing more) automatically 
when compiling.


But you can also do it yourself or use the dub packages etc.


Re: template? mixin? template mixins? for modifying a struct setup

2022-05-20 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 20 May 2022 at 14:54:31 UTC, Christopher Katko wrote:
If the declarations are at module scope, `static` has no 
effect, and CTFE will be used for initialization.


It won't use CTFE? Why is there a local module requirement?



"module scope" just means at the top level in a module. so not 
inside a function.


Re: Sleep in a cycle

2022-05-20 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 20 May 2022 at 14:59:07 UTC, Alexander Zhirov wrote:
I have a loop spinning, I want to pause in it in order to 
repeat the next iteration. An error is displayed during 
compilation.


The error has nothing to do with the sleep


source/app.d(32,5): Warning: statement is not reachable
Error: warnings are treated as errors
   Use -wi if you wish to treat warnings only as 
informational.



this is saying the stuff after your `while(true)` is never 
reached because it is an infinite loop.


Re: Install DCD language server on Raspberrry PI4 (aarch64) requires rdmd , command not found.

2022-05-21 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 21 May 2022 at 22:44:55 UTC, Alain De Vos wrote:

Can I compile rdmd from source ?


Yes, rdmd is a trivial program.

https://github.com/dlang/tools/blob/master/rdmd.d


Re: Allocate a string via the GC

2022-05-23 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 23 May 2022 at 09:38:07 UTC, JG wrote:

Hi,

Is there any more standard way to achieve something to the 
effect of:


```d
  import std.experimental.allocator;
  string* name = theAllocator.make!string;
 ```


Why do you want that?

Easiest way I know of is to just wrap it in a struct, then `new 
that_struct`, which is also a better way for all the use cases I 
know but those use cases are pretty rare so there's probably 
a better way to do what you're trying to do.


Re: Allocate a string via the GC

2022-05-23 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 23 May 2022 at 12:20:11 UTC, JG wrote:

I am writing an interpreter and I needed access to a string via
a pointer of type void*

I ended up wrapping it in a struct since I needed another value
anyway. Seems odd that one can't do it in a less unusual way.


OK yeah, that's the main use case I'd think of, and that's also 
exactly why I think doing the struct is the best thing anyway 
since you can bundle whatever you need in there instead of just a 
single value.


Re: How are delegate attributes in fn signature inferred?

2022-05-23 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 23 May 2022 at 13:44:53 UTC, wjoe wrote:

  i.construct((ulong i) {return cast(int)(i+i);}).print;


You can actually make this work with `construct!(int[])` rather 
than plain `construct`. This is a (really annoying) deficiency in 
dmd's implementation. (that sdc solved btw proving it can be done 
just dmd never bothered)



Where's **pure nothrow @nogc @safe** coming from?


That's because it is a delegate literal, so it automatically 
figured out the tightest thing that works (this is also why it 
came as `function` instead of `delegate`, since it doesn't use 
any local variables from the enclosing function, it doesn't need 
the delegate pointer either).


But all those implicitly convert away so it doesn't really 
matter. The type system allows this, just the crappy 
implementation can't handle inferring that R when it is mentioned 
both as R r *and* ElementType!R - the stupid compiler sees 
ElementType!R and bails out.


Thus why you have to help it by telling the type when 
instantiating it


  i.construct!(int[])((ulong i) {return cast(int)(i+i);}).print;




Re: Cannot check function address

2022-05-24 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 24 May 2022 at 22:10:21 UTC, frame wrote:
To also anwser to Adam: no, this symbol is unique. The first 
line of the error says:


```
Error: function `a.fun(string param)` is not callable using 
argument types `()`.

```


There's a big difference between a function and a function 
pointer.


This error message says "function". But the code you showed as a 
function pointer.


If it were a function pointer, the error would be:

```
Error: function pointer `a()` is not callable using argument types
(int)`
```


So there is clearly some kind of mix up here.


The point is, it shouldn't be called in this line anyway?


If it is a function, you get its address with the & operator. But 
if it is supposed to be a function pointer, something is wrong 
with the declaration...


Re: gdc 12.1: undefined references when linking separately compiled files

2022-05-28 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 28 May 2022 at 13:12:46 UTC, kdevel wrote:
gdc -o ppinsta ppinsta.o esah.o evaluate.o jsr.o jsw.o parser.o 
ptvr.o stack.o testdatagenerator.o


You might need to add -lgphobos or -lgphobos2 or whatever it is 
called too explicitly.


Re: gdc 12.1: undefined references when linking separately compiled files

2022-05-28 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 28 May 2022 at 14:16:51 UTC, kdevel wrote:

$ gdc -o ppinsta ppinsta.d parser.d


Compiling together is faster anyway this is prolly what you want 
most the time.


But I know what's going on now, it is the template emission 
thing, the compiler thinks, since it is from std, it was already 
compiled somewhere else and skips it but it isn't actually there 
so the linker errors.


Using

gdc -fall-instantiations -c parser.d

Might generate it in that parser.o getting it to link. Might need 
to be used in all builds but I *think* just here, hard to say 
without a test.


Re: Basic SQLite Application

2022-06-01 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 1 June 2022 at 03:46:38 UTC, harakim wrote:
I started trying to get it to compile in another directory 
structure but since I've switched to dub


It should work the way you have it, just with dub you can also 
the dub version instead of copying the files: 
https://code.dlang.org/packages/arsd-official%3Asqlite


both are supposed to work.

anyway

it compiles and runs and returns some large negative number as 
an error without printing what's in the writeln.


What is the number? My guess is you might have gotten the wrong 
sqlite3.dll (it should come from the same source as the .lib file 
you used) or it is in the wrong place.


I won't rule out that my lib file is the wrong file as I don't 
know how to tell or find the right one.


That's possible too but it would normally fail to link entirely 
if this was it. My money is on the dll, especially since the 
main() doesn't even try to open the database, it must be a 
loading issue. Where did you get the .lib file anyway?


BTW:

"copyFiles":["lib/sqlite3.lib"]


You don't need that, the .lib is only used while building. You 
might need to copyFiles the .dll though.


Re: Basic SQLite Application

2022-06-01 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 1 June 2022 at 15:40:43 UTC, harakim wrote:
It's been a long time since I did any C development, and I have 
never done any on windows, but I thought I could statically 
link to the .lib at compile time and then I wouldn't need a dll.


You sometimes can, it depends on how the library is built. If it 
was built as a dll, you need to use it that way unless you 
recompile the library itself.


Re: Dynamic Arrays Capacity

2022-06-03 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 3 June 2022 at 12:49:07 UTC, bauss wrote:
I believe it's only true in unicode for utf-32 since all 
characters do fit in the 4 byte space they have


Depends how you define "character".


Re: Comparing Exceptions and Errors

2022-06-05 Thread Adam D Ruppe via Digitalmars-d-learn

On Sunday, 5 June 2022 at 10:38:44 UTC, Ola Fosheim Grøstad wrote:

That is a workaround that makes other languages more attractive.


It is what a lot of real world things do since it provides 
additional layers of protection while still being pretty easy to 
use.


*Correctness **is** probabilistic.* Even in the case of 100% 
verified code, as there is a possibility that the spec is wrong.


I'm of the opinion that the nothrow implementation right now is 
misguided. It is a relatively recent change to dmd (merged 
December 2017).


My code did and still does simply catch Error and proceed. Most 
Errors are completely harmless; RangeError, for example, is 
thrown *before* the out-of-bounds write, meaning it prevented the 
damage, not just notified you of it. It was fully recoverable in 
practice before that silly Dec '17 dmd change, and tbh still is 
after it in a lot of code.


If it was up to me, that patch would be reverted and the spec 
modified to codify the old status quo. Or perhaps redefine 
RangeError into RangeException, OutOfMemoryError as 
OutOfMemoryException, and such for the other preventative cases 
and carry on with joy, productivity, and correctness.


Re: How to map machine instctions in memory and execute them? (Aka, how to create a loader)

2022-06-06 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 6 June 2022 at 15:13:45 UTC, rempas wrote:
  void* code = mmap(null, cast(ulong)500, PROT_READ | 
PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0);


On a lot of systems, it can't be executable and writable at the 
same time, it is a security measure.


see https://en.wikipedia.org/wiki/W%5EX


so you might have to mprotect it to remove the write permission 
before trying to execute it.


idk though


Re: 'each' can take static arrays

2022-06-10 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 10 June 2022 at 16:59:04 UTC, Ali Çehreli wrote:

Why the inconsistency?


Phobos has dozens of random special cases throughout. I'd prefer 
if these were all removed, but right now there's just some 
functions that special case to allow it and others that don't.


Apparently each is one that does.


Re: UI Library

2022-06-11 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 11 June 2022 at 01:20:17 UTC, harakim wrote:
The issue I'm having is that I don't understand how to assign 
bounds in the nested widget. I'm sure there's a very clean 
solution. I basically want a paintContent method but with the 
bounds dynamically assigned by the parent.


Well the bounds given to paintContent just define your content 
area boundaries, relative to the nested widget. The content area 
is inside its own border. The actual position is assigned by the 
parent (the virtual function there is recomputeChildLayout, you 
can override that to arrange instead of letting it automatically 
fill the space).




I don't really know what exactly you have in mind for the bounds, 
but anything outside your widget area is going to be clipped 
anyway, so I think you really want to change that child layout 
computation.





Re: UI Library

2022-06-11 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 11 June 2022 at 21:44:17 UTC, harakim wrote:
I tried the solution I suggested and it did not work because 
the child would occlude the parent (which is in the comments 
now that I see it.)


yeah minigui's model is to tile the widgets; they aren't supposed 
to overlap (except their parent, but then they cover the parent)


I decided to stick to simpledisplay strictly and forgo using 
the minigui library for the time being, and that is working 
well.


Yeah, nested widgets are something i sometimes use btu more often 
then not, i'll make the whole display for a thing - say a graph - 
just be a single widget and paint it in there.


A simpledisplay window's paint code can generally be pasted into 
a single minigui widget's paint code without much modification 
(the minigui WidgetPainter actually is a subclass of 
simpledisplay's ScreenPainter)


Re: Creating DLL

2022-06-16 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 16 June 2022 at 13:57:48 UTC, Sergeant wrote:

export int my(int a, int b)


the name here is going to be mangled, so like "_D5mydll2myiiZi" 
or something like that.


You might want to add `extern(C)` to it so it keeps the simple 
name "my", that might help.


Re: Creating DLL

2022-06-16 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 16 June 2022 at 16:07:41 UTC, Sergeant wrote:
May I ask one more question: why a code like this would work in 
D-application but not in D-DLL? (also I notice some other D 
functions don't work in DLL):


Probably because the runtime not initialized properly. Export an 
Initialize() and Terminate() functions and call them from your 
application loading the dll.


Inside those functions:


export extern(C) void Initialize() {
   import core.runtime;
   Runtime.initialize();
}


export extern(C) void Terminate() {
   import core.runtime;
   Runtime.terminate();
}



If you call those the other functions should start working.

(this is a fairly common thing libraries need to do, but it might 
be tricky if you are loading the dll into an uncooperative 
application, there's other hacks for that, but having your 
functions like this and the app calling them are the right way to 
do it)


Re: Creating DLL

2022-06-16 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 16 June 2022 at 16:19:22 UTC, Ali Çehreli wrote:

pragma (crt_constructor)


You have to be pretty careful about this since it might not run 
in the order you expect. If there's two things in the program 
with a equal-priority crt constructor, they are run in arbitrary 
order. In a shared lib, there's also the possibility that loader 
locks are in place, and if it runs rt_init specifically, that can 
run D module constructors... which might load other libraries.


Similar concerns apply to doing rt_init in DllMain.

This is why an explicit initialization call is the preferred 
method - there, the time it is called is well-defined by the user 
after initial loading is complete.


Re: Creating DLL

2022-06-16 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 16 June 2022 at 16:37:34 UTC, Ali Çehreli wrote:
Agreed but that excludes using the D runtime in 'static this' 
(and shared) blocks, right?


It is runtime.initialize that calls those `static this` blocks.


If my explicit call to Initialize is in a 'shared static this'


This is backward - the explicit call to Initalize is in the exe. 
It'd look like:


// this code is in the exe! pretend it is C++ or whatever

HANDLE lib = LoadLibrary("my_d_lib.dll");
if(lib !is null) {
 auto fn = cast(typeof(init_func)) 
GetProcAddress("Initialize");

 if(fn !is null) {
   fn(); // this now calls runtime.initialize which calls 
the static this blocks etc

  // you're now good to call any D functions
 }
}



Re: multidim array with enum

2022-06-18 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 18 June 2022 at 17:19:24 UTC, Chris Katko wrote:
I'm having difficulty figuring out exactly what signature D is 
expecting.


BITMAP*[2][DIR] bmps;


I'm actually not sure if that [DIR] is an associative array or 
DIR's base type or a static array of DIR's size.


I *think* it is an assoc array... let's test it using the `in` 
operator:


auto a = DIR.UP in bmps;

That compiled. So this must be an associative array!


Try this instead:

BITMAP*[2][DIR.max] bmps;


That's a static array of directions and I think that's what you 
intended and the other things should work as you want too with 
this.


Re: can you initialize a array of POD structs?

2022-06-18 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 18 June 2022 at 17:37:44 UTC, Chris Katko wrote:

D
struct pair { float x, y;}

pair p[] = [[0, 0], [255, 255], [25,-25]]; //nope



An array of pair is `pair[]`, keep the brackets with the type.

Then a struct literal is either:

pair(0, 0) // using constructor syntax

or in some select contexts (including this one):

{0, 0} // using named literal syntax


Therefore:

pair[] p = [{0, 0}, {255, 255}, {25,-25}];

compiles here.


Re: destroy and @safe

2022-06-21 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 21 June 2022 at 15:13:36 UTC, Paul Backus wrote:
`destroy` should be `@safe` as long as the destructor it's 
calling is `@safe`.


For classes, the current dmd+druntime implementation makes it 
impossible to determine statically if the destructor is safe or 
not.


Structs I'm not sure about, the implementation might block it 
there too but idk.


Re: dlang bug - accessing module variable from method segfaults only when using module reference directly

2022-07-01 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 1 July 2022 at 12:57:01 UTC, Chris Katko wrote:

Cannot access memory at address 0x10


Looks like an ordinary null pointer. How did you create the 
variable?


Re: How to check if something can be null

2022-07-01 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 1 July 2022 at 13:48:25 UTC, Antonio wrote:
I has been using this pattern each time something needs special 
treatment when it can be null:


i'd prolly check `static if(is(typeof(null) : T))` which means if 
the null literal implicitly converts to type T.


there's also the bludgeon __traits(compiles, v is null) too lol




Re: How to call a function from a dll created with d ?

2022-07-01 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 1 July 2022 at 22:32:24 UTC, Vinod K Chandran wrote:

So using a `def` file is a must I think.


no it is not. you just need to mark things export and make sure 
names match (including module name)


Re: How to obtain Variant underlying type?

2022-07-09 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 9 July 2022 at 14:36:44 UTC, anonymouse wrote:
 auto vb = v.base; // what should I put here to achieve the 
following:

 typeof(vb); // int[][]


Impossible; Variant's type is only known at runtime, and this 
would require compile time knowledge.


Re: How can I convert a file encode by CP936 to a file with UTF-8 encoding

2022-07-13 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 13 July 2022 at 11:47:56 UTC, rocex wrote:
How can I convert a file encode by CP936 to a file with UTF-8 
encoding


My lib doesn't have it included but the basic idea is to take 
this table:


https://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP936.TXT

and do the conversions. So loop through it, if it is < 128, it 
stays the same, if it == 128 it is 0x20AC, and greater than that 
you need to read the second byte too and look it up in that table.


It looks like for many of the bytes, they increase in sequence, 
so you might only need part of the actual lookup table, and the 
rest you can do with some addition. Looks like from lead byte 83 
it is a almost sequential offset. Probably safest to just 
copy the whole table.


Re: File.write introduces \r regardless of presence

2022-07-16 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 16 July 2022 at 19:54:08 UTC, HuskyNator wrote:

File("test.txt", "w").write(a);


The default here is write in text mode, change the "w" to "wb" 
and it won't molest your line endings any more.


Re: mixin template bug with opBinary?

2022-07-22 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 22 July 2022 at 12:33:37 UTC, Anthony Quizon wrote:

Is this a bug or am I doing something wrong?


I think this is a bug. The compiler must not take well to this 
pattern, maybe the assoc array template argument, but idk. It 
looks like the first type used gets cached and reused even if it 
is supposed to change.


I vaguely recall seeing this before but yeah smells buggy 
anyway.



An alternative you might consider is dropping some of the type 
and using typeof(this):


```
module foo;

mixin template opBi(
alias f0
) {
static foreach (k, f; f0) { typeof(this) opBinary(string op:
k)(typeof(this) r) { return f(this, r); } }
}

struct A {
mixin opBi!(
[ "+": (A a, A b) => a],
);
}

struct B {
mixin opBi!(
[ "+": (B a, B b) => a],
);
}
```

That sidesteps the bug though it just trusts you pass the right 
type to `f0`.


Re: Using "%s" with inputting numberic values

2022-07-24 Thread Adam D Ruppe via Digitalmars-d-learn

On Sunday, 24 July 2022 at 23:12:46 UTC, pascal111 wrote:
In the next code, we used "%s" format with receiving an integer 
value, while from C experience, we know that we use "%d" or 
"%i" formats, so what "%s" stands for here, I guess it's for 
receiving string data type?


The D things in std.stdio, writef and readf, use %s to just mean 
default for the given type. Since you passed it an int, the 
function knows it got an int (this is different than C, where the 
function only knows the format string so it requires you to get 
it right) and just automatically picks a default representation 
to scan.


You can writef("%s %s", "foo", 5); and it will see "foo" is a 
string and thus do it as a regular %s then see 5 is an int and 
since it knows, and you asked for just the default as-string 
representation, it will convert just like %d would.




Re: "string" data type with readln

2022-07-25 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 25 July 2022 at 19:55:40 UTC, pascal111 wrote:
I tried to type small program, and tried to use "string" data 
type with "readln", but the compiler refused it, and I had to 
use "char[]".


the overload you used modifies the array you give it

try

string s = readln();



Re: BASIC "sgn" function equivalent

2022-07-28 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 28 July 2022 at 12:02:54 UTC, pascal111 wrote:
I'm making an equivalent of "sgn" function of BASIC language, 
and I used "(T)" in its definition, but the function can 
receive wrong data by passing string data to it, how we can 
solve it?


There's no need to do the complication of a template, just do a 
normal function taking a `double`. You can add overloads if you 
want like one taking a `long` and/or `int` but those would cover 
all types that have signs.


Re: Write binary data as a file

2022-08-02 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 2 August 2022 at 11:10:27 UTC, Alexander Zhirov wrote:

As a result, I get only a set of text data.


my database layer is doing to!string(that_ubyte) which is wrong. 
gonna see about pushing a fix


Re: How to find all modules in a package?

2022-08-03 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 3 August 2022 at 03:36:55 UTC, Domain wrote:
I want to find out all public functions in all modules in a 
package. Can I do that at compile time?


No, D packages are not closed; anyone can add new modules to them 
at any time.


Re: curses/ncurses liberary in D

2022-08-04 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 4 August 2022 at 21:15:39 UTC, pascal111 wrote:

https://github.com/adamdruppe/arsd/blob/master/terminal.d


How can I use this terminal module? Is there a document for it?


http://arsd-official.dpldocs.info/arsd.terminal.html


Re: curses/ncurses liberary in D

2022-08-05 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 5 August 2022 at 04:14:22 UTC, H. S. Teoh wrote:

including cursorX, cursorY


Worth noting these are not initialized in linear mode, only in 
fullscreen/cellular. I might change that soon, it is on my todo 
list.


(Granted, though, the main page could be expanded to include 
examples of how to use these functions.. take that up with 
Adam. :-P)


Email me a patch.


Re: curses/ncurses liberary in D

2022-08-05 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 5 August 2022 at 18:20:36 UTC, pascal111 wrote:
But I'll need help to understand some functions like how we can 
use "readf" equivalent, I don't see it.


http://arsd-official.dpldocs.info/arsd.terminal.html#get-line

get a line then strip it and convert to whatever numbers you want 
etc


Re: My programs issues

2022-08-10 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 10 August 2022 at 12:36:42 UTC, pascal111 wrote:
1) I used "exit()" from "core.stdc.stdlib;" module, but someone 
can say this isn't the D way to exit the program.


It is better to simply return a value from main instead.

2) I used "goto", I heard from someone before that using "goto" 
isn't good programming feature.


Don't listen to people who are wrong.


Re: How to use exceptions

2022-08-11 Thread Adam D Ruppe via Digitalmars-d-learn

You might find my recent blog post interesting too:

http://dpldocs.info/this-week-in-d/Blog.Posted_2022_08_01.html#exception-template-concept

and a draft of some more concepts:
http://arsd-official.dpldocs.info/source/arsd.exception.d.html


I also find the lack of information disturbing, but I also hate 
formatting it all into strings, so I wanted to experiment with 
other options there that avoid the strings.


Re: How to use exceptions

2022-08-11 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 11 August 2022 at 23:50:58 UTC, H. S. Teoh wrote:
I think the OP's idea is somewhat different: adding contextual 
information to a propagating exception that the throwing code 
may not have access to.


Yeah, but you can use the mechanism again: you'd catch the one 
then throw a new one with the old one tacked on the back.


The OP's idea of wrapping throwing code with a function that 
tacks on extra information is a good idea.


Yeah, that is good. I also kinda wish that scope(failure) could 
do it so you could tack on info with a more convenient syntax... 
i have some more wild ideas brewing now lol


Re: How to use exceptions

2022-08-11 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 12 August 2022 at 00:40:48 UTC, H. S. Teoh wrote:

Hmm! That gets me thinking.  Maybe something like this?


aye. and scopes share dtors which means we can do it in the lib 
today:


---
struct AdditionalInfo {
static string[] info;

this(string info) {
AdditionalInfo.info ~= info;
}

~this() {
AdditionalInfo.info = AdditionalInfo.info[0 .. $ 
- 1];


}

@disable this(this);
}

class AdditionalInfoException : Exception {
this(string t) {
import std.string;
super(t ~ "\n" ~ AdditionalInfo.info.join(" "));
}
}

void bar() {
with(AdditionalInfo("zone 1")) {
with(AdditionalInfo("zone 2")) {
}

throw new AdditionalInfoException("info");
}
}

void main() {
bar();
}
---

the throw site needs to cooperate with this but you could still 
try/catch an operation as a whole too and attach the original 
exception in a new one.


needs a bit more thought but this might work. biggest problem is 
still being stringly typed, ugh.


with compiler help tho we could possibly attach info on function 
levels right in the EH metadata, so it looks it up as it does the 
stack trace generation. but that would be limited to per-function 
i believe... but eh there's nested functions.


tbh i think op's delegate is a better plan at this point but 
still my brain is running some concepts.


Re: Recommendation for parallelism with nested for loops?

2022-08-18 Thread Adam D Ruppe via Digitalmars-d-learn
On Friday, 19 August 2022 at 01:49:43 UTC, Shriramana Sharma 
wrote:
Also, what is the best way to do parallelism in such a 
situation?


If the inner loops are about the same size for each pass of the 
outer loop, you can just simply parallel on the outer loop and 
get the same benefit.


Even if they aren't equal, you'll get decent benefit from 
parallel on the outer one alone, but not as good since the work 
won't be balanced.


Still, that's what I'd try.


Re: Best practice for dub registry package and module names

2022-09-04 Thread Adam D Ruppe via Digitalmars-d-learn

On Sunday, 4 September 2022 at 01:52:11 UTC, Ali Çehreli wrote:
Should the package be the author's name: acehreli.a, 
acehreli.b, and acehreli.c?


This is what I'd suggest. You want something that nobody else is 
likely to step on throughout the entirety of the D ecosystem. It 
doesn't have to literally be your name, but it should be 
something unique and probably arbitrary at the top level. This 
way you can use it as much as you want without worrying about 
conflicting with someone else.


Then you have the more descriptive name as the module.

Your dub package name is then a combination of these to make that 
unique too. So you might have dub package `acehreli-a` which has 
the D module `acehreli.a`.


What about module names? If the type is 'struct MyCache', 
should the module name be mycache, or my_cache, or my-cache?


Module names must be valid D identifiers, so no dash there. 
Whether you use _ or squeeze the words together is up to you, I'd 
say pick whichever one is easier to read.


I usually squeeze words together.



Re: Best practice for dub registry package and module names

2022-09-04 Thread Adam D Ruppe via Digitalmars-d-learn

On Sunday, 4 September 2022 at 03:50:56 UTC, Ali Çehreli wrote:
For example, there is fixedsizearray, which does not belong to 
any package:


Yeah, this is bad design since two separate people might reuse 
the name and then end users - even if it comes through a couple 
layers of dependencies they didn't even know about - can see 
conflicts when they try to link the program.


You really need globally unique D names.

On the other hand, arsd-official:minigui does have a package. 
(And that answers a question: Dash character is acceptable in 
package and module names.)


dub allows dash. D does not. The dub name and the D name do not 
have to match (I personally consider this yet another design flaw 
in dub, but it is what it is).


The reason mine is called "arsd-official" on dub is because 
someone else registered "arsd" before me, but they didn't keep up 
with changes, so I had to do it myself but the name was already 
taken.


But remember, the dub package name and the D package/module names 
are completely separate. D knows absolutely nothing about dub and 
dub knows very little about D. You should have them match when 
you can for user convenience, but it doesn't actually check it.


How does that work? When the following dependency added to a 
user's project,


  "arsd-official:minigui": "~>10.9.1"

does dub pull the entirety of arsd-official and then use 
minigui module from it?


Yes, dub always pulls its top level thing in full. Then I had to 
specify a long list of subpackages in dub.json to let it 
understand the independent modules.


Dub is unbelievably and embarrassingly bad. It really is a 
disappointment, but you can make it somewhat work if you repeat 
yourself enough times. Downloading a few extra kilobytes of D 
code is the least of its problems.


Re: Is there a way to

2022-09-10 Thread Adam D Ruppe via Digitalmars-d-learn
On Saturday, 10 September 2022 at 23:37:30 UTC, Kyle Ingraham 
wrote:
How can I write a type that is strict for the first two 
parameters but tolerant of any other parameter following those?


That's not a type per se, but you can assign wrapper at the 
assignment thing.


Like

your_delegate = (a,b) => func_with_three_args(a, b, "some 
default");


that kind of thing. if you have a delegate in an object, you can 
use a property setter to accept more things and wrap it like that.


Re: Is there a way to

2022-09-10 Thread Adam D Ruppe via Digitalmars-d-learn

On Sunday, 11 September 2022 at 00:32:18 UTC, Kyle Ingraham wrote:
I can't use default parameters because I want to be able to 
call the delegate with arguments extracted from a URL path at 
runtime


Some kind of wrapper might not only be your best option, it might 
be your only option.


Your delegate would be like string callWith(string[][string] 
webArgs) and you can generate a wrapper to convert arguments and 
call the original function.


I'm mucking about with a custom router for vibe-d and trying to 
setup the ability for handlers to have different parameter 
signatures.


I'd be surprised if vibe doesn't already have this built in, my 
web frameworks have since before vibe was born. (my 
implementation btw does the wrapper thing like described above)


Re: Is it valid in D to write an opSlice overload that takes no arguments?

2022-09-11 Thread Adam D Ruppe via Digitalmars-d-learn
On Sunday, 11 September 2022 at 09:47:34 UTC, solidstate1991 
wrote:

Here's this code:


This should be allowed, but also the way you're supposed to write 
it now is a no-argument opIndex.


Re: Is this a new bug ?

2022-09-24 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 24 September 2022 at 06:13:55 UTC, test123 wrote:

If so please report it for me to bugs platform.


This isn't a bug, the effect of keyword: things stop at the 
matching }.


(static if and version don't introduce a namespace scope, but 
they still follow this rule for the { colon: ... } blocks)


You need to duplicate your uint test2 variable inside those 
branches.


Re: Detect uninitialized class var access

2022-09-24 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 24 September 2022 at 13:17:19 UTC, rassoc wrote:
just crashes with `Error: program killed by signal 11` on linux 
and nothing else.


gdb --args ./your_program

and then it will tell you all the details you want to know about 
when this happens.


strangly sometimes adding the -O option will cause dmd to catch 
simple cases at compile time but gdb is the general solution to 
track these down.


Re: Template function alias that leaves out the last type parameter

2022-09-27 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 27 September 2022 at 22:39:52 UTC, torhu wrote:
How would I achieve something like this, do I have to turn the 
aliases into functions?


You can write it out long-form with two steps like this:

---
template _messageBox(string title, int style)
{
void _messageBox(T...)(T args)
{
import std.format;
string s = format("%s", args);
/* etc... */
}
}

alias _messageBox!("lol", 4) info;
alias _messageBox!("Warning", 4) warning;
alias _messageBox!("Error", 4) error;

void main() {
info(4, "ok");
}
---


Re: Way to pass params to a function passed to a fiber?

2022-10-03 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 3 October 2022 at 08:10:43 UTC, Bienlein wrote:

Hello,

I'm looking for a way to pass parameters to a function called 
by a fiber. Starting a fiber works like this:



You can also make a subclass of fiber that stores them with the 
object.




Re: DateTime resetting

2022-10-11 Thread Adam D Ruppe via Digitalmars-d-learn

On Tuesday, 11 October 2022 at 22:09:34 UTC, Joel wrote:
I've been working on a diary program (ChronoLog). but lately my 
date and time variable keeps resetting. I've spent hours trying 
to fix it. I'm wondering if there's a known issue.


An ordinary DateTime variable? Those are pretty simple and won't 
reset unless something else is wrong around it.


Do you have the code online? Or can at least show some of the 
context around its use?


Re: DateTime resetting

2022-10-11 Thread Adam D Ruppe via Digitalmars-d-learn
I'm just eyeballing the code, is it the g_dateTimeCursor you're 
concerned about? That's the only one I really see there.


A few things that might explain it:

1) as a global variable, it is thread local. I don't see any use 
of threads in here, but if you do, each one has a separate copy 
and other threads won't see the same value. I do see a `new Task` 
in places though so maybe it is this... I don't know where that's 
coming from or what it actually does but possible the different 
tasks are running in different threads, and thus seeing a 
different variable. If it is this, you can make the variable 
`shared` (then handle the cross thread safety so they don't 
overwrite each other) and maybe fix it.


2) there's a bunch of places it might be modified from so 
possible you just overwrite it somewhere



I also see a _dateTime in there. This is a member of the Control 
struct and since it is a struct, remember it is an 
independent value whenever you use it, just like an int.


int a = 5;
int getA() { return a; }

int b = getA();
b += 5;

// but a is still 5 here! Because ints are values, when it is 
returned by the function, it gets an independent copy.


Structs work the same way. So that `getControl` in base.d returns 
an independent copy of the control, and this has an independent 
copy of the _dateTime variable too. Changes to one will not 
affect the original.


So this might cause your problem too, with the info being lost. 
It is possible that changing getControl to return `ref` will help 
here, but hard to be sure when just eyeballing the code like I am.



Let me know if this helps.



Re: Can someone tell me what the compiler thought I was trying to do?

2022-10-18 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 19 October 2022 at 00:57:31 UTC, H. S. Teoh wrote:
Has it really been implemented?  I tested the latest git 
master, the following code doesn't compile:


it only applies to types, not to functions.


Re: Can someone tell me what the compiler thought I was trying to do?

2022-10-18 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 19 October 2022 at 01:34:54 UTC, mw wrote:

Is there any (design) doc about this?


scroll up, click the link from this very thread.

https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1038.md#design-goals-and-possible-alternatives



Re: Is "auto t=T();" not the same as "T t;"?

2022-10-25 Thread Adam D Ruppe via Digitalmars-d-learn
On Tuesday, 25 October 2022 at 13:51:30 UTC, Andrey Zherikov 
wrote:

A[] a = [A.init];


This is a problem - this is referring to a static array instance, 
shared across all copies of B. You almost certainly don't want 
this.


That B.a[0] is the *same object* across different 
default-constructed Bs... unless the optimizer hits it or 
something.


But just don't do this. Only basic values and immutable strings 
are good to initialize this way. With the array or class objects, 
you're liable to get some shared thing.


If you change this to be initialized in a constructor (which will 
require an argument in D) or factory function, you'll get far 
more consistent behavior as each instance will have its own array.


As for why B() and B.init are different here... i don't know, 
probably some subtly of the compiler's implementation.


Re: Importing modules under DUB on Windows

2022-10-28 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 26 October 2022 at 16:20:01 UTC, DLearner wrote:
Wanted to use a function stored in a module outside the main 
source.


easiest thing to do with dub is to add it as a sourcePath or a 
sourceFile. Well, actually, easiest is to just copy the module 
right into your default src folder, but second easiest is to add 
the other thing as the sourcePath/sourceFile.


Messing with lib compiles and import paths rarely worth the 
hassle.


(and without dub btw you can make a generic lib directory, add it 
to your -I path, then just `dmd -I/path/to/libs -i 
yourmainfile.d` and it automatically picks up things from import 
paths. that's how i do it myself)



Also later i see you are using the arsd terminal.d, which you can 
also use through dub's dependency system by adding 
`arsd-official:terminal` to its list.


Re: Importing modules under DUB on Windows

2022-10-28 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 28 October 2022 at 15:15:04 UTC, DLearner wrote:

Took suggestion, dub run then produced:
`Linking...
lld-link: error: subsystem must be defined
Error: linker exited with status 1`


That means the linker didn't see a `main` function. Make sure you 
have a `void main() {}` somewhere (and of course if you want the 
application to do something, make main do something)





Re: overloading main

2022-10-30 Thread Adam D Ruppe via Digitalmars-d-learn

On Sunday, 30 October 2022 at 16:09:54 UTC, NonNull wrote:
I am linking to a C project with some C already automatically 
translated into D including the C main function `int main(int 
argc, char** argv){/* ... */}` which I wanted to call from a D 
main function in a new module.


did you put extern(C) on that thing? im p sure it'd allow it then 
but then it'd be the entry point instead of the D main so i 
don't think it'd let you get ahead.


So it seems that main cannot be overloaded with a prototype 
that is not a valid entry point in D. Is this restriction 
essential? And if not, why make it?


it prolly just to keep newbs from making confusing mistakes and 
getting weird behavior at startup. If there's two mains, which 
one is the expected entry? Perhaps it could just be the one that 
matches the permitted signature, and if there isn't one it 
complains. But how does it know if there is one? Suppose there's 
module A:


module a;
int main(int argc, char** argv) {}


And module B:
module b;
void main() {}


They are compiled separately:

dmd -c a.d
dmd -c b.d
dmd a.o b.o

Which one is the main you want to use? What if you just did `dmd 
a.d`, should it error that the prototype is wrong, or just give 
the user the linker error "could not find D main" when they think 
they have it right there? (remember the linker doesn't know what 
D signatures are so it can't print a helpful message to correct 
the mistake).


Re: Make IN Dlang

2022-11-01 Thread Adam D Ruppe via Digitalmars-d-learn
I don't have specific answers to your questions but your goal 
sounds similar to Atila's reggae project so it might be good for 
you to take a look at:


https://code.dlang.org/packages/reggae


Re: What's the correct way of creating an instance of class in D?

2022-11-03 Thread Adam D Ruppe via Digitalmars-d-learn

On Thursday, 3 November 2022 at 15:40:02 UTC, H. S. Teoh wrote:
D does not have the equivalent of C++'s allocating a class 
instance on the stack.  In D, all class instances are allocated 
on the heap and class variables are references to them.


well there is

scope Object o = new Object;

which is stack allocated but still a reference of course



Re: Hipreme's #4 Tip of the day - Don't use package.d

2022-11-04 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 4 November 2022 at 14:11:55 UTC, bauss wrote:
Having used D for like a decade at this point, I've never 
experienced any issues with it.


Lucky you, lots of other people have. Broken phobos updates, 
impossible to transition to it without code breakages (which is 
the only reason it exists), random inconsistencies with the rest 
of the language leading to link errors.



package.d is absolutely essential in some cases.


Which cases?


Re: Hipreme's #4 Tip of the day - Don't use package.d

2022-11-04 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 4 November 2022 at 19:10:33 UTC, jmh530 wrote:
If you don't plan to use private(package_name), then I don't 
know what the point of it is.


This works fine without the package.d anyway.


Re: Hipreme's #4 Tip of the day - Don't use package.d

2022-11-04 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 4 November 2022 at 19:34:58 UTC, jmh530 wrote:

Oh really, then what's the point of package.d?


It was originally added because Phobos had `std.algorithm` and 
`std.datetime` and some people wanted to break them up into 
pieces, but not break user code that still said `import 
std.algorithm` instead of `import std.algorithm.sorting` (or 
whatever).


One alternative was to call the new things like 
`std.algorithm_parts.sorted` but this name a little ugly and 
people would be less likely to transition to it.


The failure of this scheme though is that the package.d design is 
braindead and broke things anyway as people updated and it 
brought about other various bugs down the line. It was possible 
to do it well but it wasn't.


Re: Hipreme's #4 Tip of the day - Don't use package.d

2022-11-04 Thread Adam D Ruppe via Digitalmars-d-learn

On Friday, 4 November 2022 at 19:40:09 UTC, H. S. Teoh wrote:
So that you can import abc.def separately from abc.def.ghi and 
abc.def.jkl.


This isn't that hard; in the old days you'd have `pkg.foo` then 
`import pkg.all` instead of `import pkg;`. The specific thing 
that led to the package.d thing is the desire to transition 
Phobos in addition to some flawed ideology. (One of the other 
constraints was that you should be able to zip up the directory 
of the package and have it all together, hence using 
dir/package.d instead of just dir.d. But this would have worked 
anyway if not for the inconsistent design flaw of requiring the 
file to be called package.d in the first place! And with this if 
you compile it separately vs compiling it together you get 
totally different results. It really is just a *terrible* design.)


Re: My new programming book ...

2022-11-06 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 7 November 2022 at 00:55:33 UTC, zjh wrote:

Is there a second edition? After all, it has been many years.


No, but not that much has changed and you can always post here 
with questions.


Re: Passing a string by reference

2022-11-08 Thread Adam D Ruppe via Digitalmars-d-learn
On Tuesday, 8 November 2022 at 12:30:50 UTC, Alexander Zhirov 
wrote:
Do I understand correctly that in order for me to pass a string 
when creating an object, I must pass it by value?


You should almost never use `ref string`. Just use plain `string`.

In fact, ref in general in D is a lot more rare than in languages 
like C++. The main reason to use it for arrays is when you need 
changes to the length to be visible to the caller... which is 
fairly rare.


In the case of the variable `c`, a drop occurs. Why? An object 
is not being created on the stack?


nope, an object isn't created there at all. you should use `new 
C`.


Re: My new programming book ...

2022-11-08 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 7 November 2022 at 04:54:05 UTC, ikelaiah wrote:
I'm aware of the publication date. However, I find the content 
still highly relevant to many day-to-day tasks (my use case).


Yeah, I tried to focus more on the ideas behind it than the 
specifics of a library. My thought is if you understand what it 
is trying to do, the adjustments to bring it up to date shouldn't 
be too hard.


It took some effort to avoid talking more about my libraries 
though lol. I did do a few small examples near the end of the 
book, and some of those have had minor changes, like I've since 
renamed "import simpledisplay" to "import arsd.simpledisplay". 
But the rest of it should still work, i try to keep things pretty 
stable in my libs.


BTW one of the things in chapter 2 i found surprisingly popular 
was the talk about std.socket. I did write a follow-up to that in 
my blog here:

http://dpldocs.info/this-week-in-d/Blog.Posted_2019_11_11.html#sockets-tutorial

Since the socket api is the same as C, I assumed people would 
know it from other sources, but the C api isn't as common 
knowledge as it used to be. So this tries to explain (tho even 
there I didn't go into ipv6 fallbacks and whatnot but it still 
lays the foundation).


And of course always feel free to ask here or whatever about 
anything, if I'm online I try to answer things pretty quickly.


Re: My new programming book ...

2022-11-08 Thread Adam D Ruppe via Digitalmars-d-learn

On Monday, 7 November 2022 at 06:10:46 UTC, zjh wrote:
How is your `minigui`? Please write an `introduction` when you 
have time.


It is on my list but minigui is a pretty simple class collection 
of basic widgets. It works pretty well now. I don't have too many 
intro examples yet though. My blog has one thing but it uses an 
experimental piece 
(http://dpldocs.info/this-week-in-d/Blog.Posted_2020_11_02.html) 
that isn't  really representative of the average program.


But if I make it to the dconf online I'll probably show off a 
minigui application there this year.


Re: Using glibc headers with ImportC

2022-11-12 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 12 November 2022 at 13:46:27 UTC, qua wrote:

This is supposed to work, right?


No, it isn't. And it probably never will.

importC looks for a .c file in the current directory. It is that 
.c file's responsibility to #include whatever .h files you want.




Re: Using glibc headers with ImportC

2022-11-12 Thread Adam D Ruppe via Digitalmars-d-learn

On Saturday, 12 November 2022 at 14:39:14 UTC, qua wrote:
Do I have to do anything else? I've read that importc doesn't 
have a preprocessor and I assume it is related to that, however 
"ImportC can automatically run the C preprocessor associated 
with the Associated C Compiler".


I still don't think that's been released yet, so if you aren't on 
the git master or at least the latest beta build it isn't going 
to work. Which dmd version are you running?


  1   2   3   4   5   6   7   8   9   10   >