What prevents ImportC from using .h directly?

2024-05-12 Thread Chris Piker via Digitalmars-d-learn

Hi D

Import D is working quite well so far.  One limitation is that 
module definitions require a tiny *.c file which is often just:

```C
#include 
```

Creating this file is trivial and has almost no knock-on effects, 
except when dealing with single file programs. I have quite a few 
small utilities with dub headers. It would be handy if I could 
set an import path and use ImportC on the header file directly, 
skipping the small C file all together.  A specific example in my 
case follows.


Given a C-lib interface defined in the header file:
```
/usr/include/cspice/SpiceUsr.h
```

it would be neat if a dub header similar to the following worked:
```d
#!/usr/bin/env dub
/+ dub.sdl:
   name "some_app"
   cImportPaths "/usr/local/include/cspice"
+/

import SpiceUsr;

// ... source continues
```

So, why does ImportC need *.c files exclusively?  I'm sure it 
solves a problem, but I don't know what that problem is.








Re: Recommendations on porting Python to D

2024-05-03 Thread Chris Piker via Digitalmars-d-learn

On Thursday, 25 April 2024 at 16:57:53 UTC, mw wrote:

On Wednesday, 24 April 2024 at 22:07:41 UTC, Chris Piker wrote:


Python-AST to D source converter may already exist?


https://github.com/joortcom/eiffel_rename/tree/main/yi

A rudimentary converter from (extended) Python to D. Maybe you 
can use it as a starting point.


Thanks for the suggestions.  I put the question aside for a bit, 
but yesterday ran across a python transpiler here:


  https://github.com/py2many/py2many

It already has support for C++, Go and others.  Since I have 
mountains of python code created over many years, maybe it would 
be worth contributing to this project out of self interest.


Can you take a look at py2many and see what you think about it?  
Getting D on the support list might be good.




Re: Recommendations on porting Python to D

2024-04-25 Thread Chris Piker via Digitalmars-d-learn

On Thursday, 25 April 2024 at 07:04:13 UTC, Sergey wrote:

On Wednesday, 24 April 2024 at 22:07:41 UTC, Chris Piker wrote:


Python-AST to D source converter may already exist?


Another possible way maybe is using C :)
Python -> C -> D
https://wiki.python.org/moin/PythonImplementations#Compilers


Thanks for the info, though I think going to a low-level language 
in the middle will make code that has almost no high level 
structure.  Converting that back in to class-style D would likely 
take a while, in which case a manual port is a better option.  
Both python and D offer garbage collection so going through a 
non-GC language first would probably obfuscate the intended 
structure.


Maybe converting this AST to another AST format and then using a 
D code generator would be a better route.


So backing up, are there any AST -> D source generators in 
existence?


Re: Recommendations on porting Python to D

2024-04-24 Thread Chris Piker via Digitalmars-d-learn
On Wednesday, 24 April 2024 at 20:13:26 UTC, Lance Bachmeier 
wrote:
I haven't used Python much in recent years, but my recollection 
is that Python 2 had an ast module that would spit out the ast 
for you.


Thanks for the pointer! So I ran one of my modules through and 
generated an AST, and get results similar to:

```
Module(
   body=[
  Import(
 names=[
alias(name='sys')]),
  FunctionDef(
 name='pout',
 args=arguments(
posonlyargs=[],
args=[
   arg(arg='item')],
kwonlyargs=[],
kw_defaults=[],
defaults=[]),
 body=[
```
etc.

I presume I'll now need to write something that parses this into 
D source (maybe with the assistance of a module provided above).  
Before I do that, is this syntax general enough that a Python-AST 
to D source converter may already exist?  Obvious searches in 
google and the D package index didn't turn up anything.


I have no background at all in working with ASTs, in fact my 
formal education is not even in CS, so I'm way outside my 
wheelhouse at this point.






Recommendations on porting Python to D

2024-04-24 Thread Chris Piker via Digitalmars-d-learn

Hi D

I have a somewhat extensive CGI based web service written in 
Python and I'd like to port it to D.  I can do this manually of 
course, and maybe that's the best way, but for a rough start, is 
anyone aware of any tools that generate an abstract syntax tree 
which could then be converted to somewhat equivalent D code?  
This might give me a jump-start on the manual conversion process. 
 Then later I can work on removing the CGI dependency.


I'm aware that this wouldn't work in general due to all the third 
party modules typically used in python, but most of this code is 
self contained Python2 and doesn't depend on many imports.


I can just call my old C code from D, but the old Python is 
another story.


Thanks for any advice you may have,




Re: Best way to use large C library in D as of 2024

2024-04-12 Thread Chris Piker via Digitalmars-d-learn

On Monday, 1 April 2024 at 02:08:20 UTC, Lance Bachmeier wrote:

On Saturday, 30 March 2024 at 05:01:32 UTC, harakim wrote:
It works well if you only need to work with a header. There are 
still a few rough edges that get in the way if you're compiling 
the full C sources (I filed bugs for all of them):


- Can't handle va_arg
- Can't cast to a pointer of a struct that's typedef'd
- Can't use complex numbers with the ternary operator


...
Once these final odds and ends are working, we have a killer 
language feature.


Even though DMD can't compile some C code, that's pretty much a 
non-issue for me anyway.  In my environment the servers are all 
Linux so "apt-get" (or equivalent) typically provides a 
pre-compiled dependency.  Being able to list a package as a 
system dependency and then just call it from D with no interface 
code is a Big Freaking Deal!


Compared to Python interfaces this is a huge improvement.  It 
makes D an even better replacement for the mixed mode python + C 
development I was doing before switching to D for new projects.





Re: Best way to use large C library in D as of 2024

2024-04-12 Thread Chris Piker via Digitalmars-d-learn

On Saturday, 30 March 2024 at 07:11:49 UTC, Mike Parker wrote:
Though I appreciate the sentiment, it's much more effective and 
efficient for people actually using the feature, and who 
appreciate it, to write up a blog post about it somewhere and 
share that on Twitter/Reddit/HN, etc.


I would, but I'm just not a social media person.  I pretty much 
only post online content here and at github.com.  You may have 
the problem that D doesn't attract "very-online" personality 
types.  I do mention D in work presentations, but those are not 
visible to the public.




Re: Best way to use large C library in D as of 2024

2024-03-26 Thread Chris Piker via Digitalmars-d-learn

On Tuesday, 26 March 2024 at 20:19:27 UTC, bachmeier wrote:


Should be able to just use it, as described here: 
https://forum.dlang.org/post/qxctappnigkwvaqak...@forum.dlang.org Create a .c file that includes the header files and then call the functions you need.


Wow. **That just worked the first time!**  Holy &^@$ that's easy!

So why does the 2nd page returned from the google search
```
interfacing with C site:dlang.org
```
(which happens to be: https://dlang.org/spec/interfaceToC.html) 
still have this text:


Since D can call C code directly, it can also call any C 
library functions,
giving D access to the smorgasbord of existing C libraries. To 
do so, however,
one needs to write a D interface (.di) file, which is a 
translation of the C .h

header file for the C library into D.

For popular C libraries, the first place to look for the 
corresponding D interface
file is the Deimos Project. If it isn't there already, please 
write and contribute

one to the Deimos Project.

?

This lead me to believe that interfacing was a chore and I was 
considering going back to C for a small program I need.


Best way to use large C library in D as of 2024

2024-03-26 Thread Chris Piker via Digitalmars-d-learn

Hi D

I have a C library I use for work, it's maintained by an external 
organization that puts it through a very through test framework.  
Though source code is supplied, the intended use is to include 
the header files and link against pre-compiled code.


What is the best way, as of 2024 to use this library with D, in 
particular dmd?  ImportC doesn't seem like the go-to option since 
the C source does not need to be complied.  I've seen some forum 
post indicating that manually generated D wrappers are no longer 
needed, but I'm fuzzy on the particulars.  If there's any blog 
posts or other instructions you'd like to reference I'd be happy 
to check them out.


For reference here's the C library in question: 
https://naif.jpl.nasa.gov/naif/toolkit_C_PC_Linux_GCC_64bit.html


Thanks for any guidance you can provide,




Re: template/mixin magic for to! auto inferring type from variable

2024-02-02 Thread Chris Katko via Digitalmars-d-learn

On Friday, 2 February 2024 at 21:01:53 UTC, Paul Backus wrote:


No, D only does bottom-up type inference, not top down.

If you want to avoid repeating the type, use `auto` on the left 
side:


```d
auto time = to!uint(data[1]);
auto priority = to!int(data[2]);
```


Okay thanks. It finally clicked what bottom-up/top-down type 
interference is.


The auto solution won't work for a struct however which I'm using:

```D
struct procTable{ //contains all the fields inside a file I'm 
parsing

   uint time;
   int priority;
   string name;
   // etc
   }
```



template/mixin magic for to! auto inferring type from variable

2024-02-01 Thread Chris Katko via Digitalmars-d-learn

Is there some way to do:
```D
string[3] data; //strings from some file input, some are ints, 
uints, etc.


auto into!(T)(T value){return to!???(value); } // ???

uint time = into!(data[1]); // We already know this is uint
int priority = into!(data[2]);
```

instead of:
```D
uint time = to!uint(data[1]); // specifying type twice
int priority = to!int(data[2])
```


How to write an interface but with different signatures

2023-11-19 Thread Chris Katko via Digitalmars-d-learn
I know that sounds stupid on the face of it. An interface 
shouldn't change. But consider this:


A frame timer and a clock timer(seconds) that re-use 
functionality from a parent class/interface.


```
class timerType
{
void start() = 0;
void stop() = 0;
void restart() = 0;
void set(?) = 0; // 
}

class frameTimer : timerType
{
void set(int numFrames){}
}

class clockTimer : timerType
{
void set(float numSeconds){}
}

```

If we put both signatures in the top we're kind of polluting the 
interface. If we don't put them in the interface, then you can 
create a timer with no set() function.


None of this is super important on a practical level. There's 
going to probably be a total of two or three timer types. But as 
a learning exercise, I'm curious if there is a right/proper/best 
way to solve this conceptual problem.


And to be clear, frames and seconds are NOT directly 
interchangeable or convertible. If the game runs at 2 FPS for a 
moment, a 5 second timer is still 5 seconds (e.g. a countdown), 
but a frame timer of 2 (for an animation) is still going to be 2 
frames.


SumType structure wrapping seems to fail (dmd v2.105.2)

2023-09-30 Thread Chris Piker via Digitalmars-d-learn

Hi D

As suggested in other threads I've tried wrapping a SumType in a 
structure to add functionality and used `alias ... this` to make 
assignment, etc. easier.  However the following code fails in dmd 
2.105.2.


```d
import std.sumtype;

struct Item{
  SumType!(void*, byte[3],  ubyte[3], string[3]) value;
  alias value this;
  this(T)(T thing){ value = thing;}
}

void main(){
  Item item;
  byte[3] byte_vec = [0x01, 0x02, 0x03];
  item.value = byte_vec;   // <-- works
  item = byte_vec; // <-- fails to compile
}
```
Is there some important detail I'm missing?  The compiler error 
message is:

```
Error: generated function `test_sumtype3.Item.opAssign(Item p)` 
is not

   callable using argument types `(byte[3])`
   cannot pass argument `stuff` of type `byte[3]` to parameter
   `Item p`
```

Thanks for any suggestions,



Re: How to print current type of a SumType?

2023-09-30 Thread Chris Piker via Digitalmars-d-learn

We posted at the same time!  Thanks for help nonetheless.

I do hope over time, SumTypes get the Ali Çehreli treatment.  I 
keep his book open on my desk all the time.





Re: How to print current type of a SumType?

2023-09-30 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 1 October 2023 at 01:17:50 UTC, Chris Piker wrote:

```d
alias Vec3 = SumType!(void* /* invalid vector */, byte[3], 
short[3], char[][3]);


```



I know it's bad form to reply to my own question, but I think I 
found a reasonably simple way:


```d
string prnType(Vec3 vec){
   return vec.match!( t => typeof(t).stringof);
}
```

which is hardly worth making into a function of it's own.  Other 
suggestions are welcome of course.


SumTypes are really tripping me up.  Unlearning years of writing 
C takes more time then I'd prefer.




How to print current type of a SumType?

2023-09-30 Thread Chris Piker via Digitalmars-d-learn

Hi D

I've a simple question but it's bedeviling me anyway.  How do I 
get a string representation of the current type of a SumType?  
I'm trying to avoid something like this:


```d
alias Vec3 = SumType!(void* /* invalid vector */, byte[3], 
short[3], char[][3]);


string prnType(Vec3 vec){

  return vec.match!(
 (void* _) => "void*",
 (byte[3] _) => "byte[3]",
 (short[3] _) => "short[3]",
 (char[][3] _) => "char[][3]"
  );
}
```

I'm sure there's a much easier way, especially once there's a 
largish number of vector types.


Thanks,



Re: Recommendation on plotting library

2023-07-22 Thread Chris Piker via Digitalmars-d-learn
Thanks for the both of the long replies.  I've ready them twice 
and will do so again.  To focus in on one aspect of D package 
support:


On Saturday, 22 July 2023 at 02:24:08 UTC, Greggor wrote:
In general whenever possible I think its better for everyone 
that stuff is built from source. It ensures that builds can be 
re-produced by anyone and that issues with building are caught 
fast by anyone consuming the library.


I agree 100%.  I've run into similar python package hell dealing 
with Tensor flow on Rocky Linux 8, since it wasn't Ubuntu.  The 
problem is we're small, and many dependencies are already written 
in C, and dub is not setup to handle C dependencies.  If I could 
turn my legacy C projects (pre-processor macros and all) into dub 
projects I'd do so as fast as possible.


If dub supported two things:

1. Building C projects

2. Installing the resulting binaries in "site-packages" or 
similar.


many, many project kickstart issues would be solved.

Like C++, D is designed as a successor to C.  It would be nice to 
bring C into the party with full dub support.




Re: Recommendation on plotting library

2023-07-21 Thread Chris Piker via Digitalmars-d-learn

On Friday, 21 July 2023 at 17:40:25 UTC, Greggor wrote:

Up to date versions of Windows 10 should have curl included and 
dub can run commands before building, so you could try 
downloading a prebuilt lib for windows via curl. 
https://everything.curl.dev/get/windows


Hey, nice!  This might be a winner.  Unless I'm missing something 
libcairo-2.dll, libpng13.dll and zlib1.dll could be downloaded, 
and then ggplotd plot can build against those (probably?).


The key thing that dub is missing compared to pip is some concept 
of an "install" directory.  Compared to everything else dub 
handles, not adding this capability mostly comes down to self 
imposed limitations.  I wonder how many in the community would 
like to see those limitations removed?


I presume it's just as easy to add commands that run after the 
build as before.  I could have an alternate dub configuration 
that's short for "setup_build_test_install" that runs everything.


If multiple projects start defining an install target the same 
way, then you have a convention, which can eventually lead to a 
standard.





Re: Recommendation on plotting library

2023-07-21 Thread Chris Piker via Digitalmars-d-learn

On Friday, 21 July 2023 at 06:15:10 UTC, Jonathan M Davis wrote:
On Thursday, July 20, 2023 10:57:22 PM MDT Chris Piker via 
Digitalmars-d-learn wrote:


Regardless though, dub really isn't designed with packaging 
anything in mind. Rather, it's designed to build your code as 
well as pull in D libraries that it usees and build those too. 
Anyone looking to actually package stuff would create a package 
from what was built with dub (e.g. with deb, rpm, flatpacks, 
etc.).


So as far as I can tell, python pip originally only dealt with 
python code, but eventually wheels were added for binary support. 
 Just as a wild guess, do you see dub ever evolving in that 
direction?  All the reasons for not supporting pre-compiled 
binaries in pip apply to dub, but yet support was added anyway, 
and it's been wildly successful.


I know it's hard to make predictions (especially about the 
future), but I'd be interesting in your opinion on the matter.




Re: Recommendation on plotting library

2023-07-20 Thread Chris Piker via Digitalmars-d-learn

On Friday, 21 July 2023 at 02:40:10 UTC, harakim wrote:

On Thursday, 20 July 2023 at 02:37:54 UTC, Chris Piker wrote:


If you happen upon a basic charting library for D during this 
hunt, please let me know! Last year, I rolled my own and it got 
the job done, but I wasn't concerned about how they looked. :D


Well, just for fun, if you have a plotting library on github or 
some other public place I wouldn't mind taking a look.  Given the 
state of things, it doesn't have to be awesome to be a good seed 
point.


As for plotting, I imagine it's c bindings only because there's 
no need to re-invent the wheel.


(Warning, possible ill-informed opinions ahead...)

In a way there is a need to reinvent the wheel.  With python I 
can run `pip install matplotlib` and get whatever binaries I need 
to get the job done.  D runs on dub, which I only see handling 
source code, and as far as I can tell, only D source code at 
that.  So unless it's D code, it can't be packaged and delivered 
easily within the D ecosystem.


If dub supports either pre-built binaries, or C code (such as 
libcairo2), I'd be interested in seeing how that's done.  With 
the wizardry I've see around here, it's probably easy, I just 
don't know about it.


Going wy out on a limb for a minute, I think D shines as a 
scripting language replacement.  Most of my programs are single 
file projects these days with dub set as the interpreter.  Also 
Rust seems to be crowding the system level space and so focusing 
on it's "compiled scripts" capability avoids that competition.


(If any of the statements above are faulty, I invite correction.)


Re: Pre-import version statements

2023-07-20 Thread Chris Piker via Digitalmars-d-learn

On Thursday, 20 July 2023 at 06:44:30 UTC, Jonathan M Davis wrote:

D has nothing equivalent to that. You compile your code with 
whichever version of dmd (or ldc, gdc, etc.) that you want, and 
it either compiles or it doesn't.


Thanks :)

As I developer that doesn't bother me too much, though I can 
imagine that management would be concerned.  For larger projects 
it's appreciated when I can point to a particular fixed standard 
that I'm following.  In addition to the `#define` statement 
above, my libraries were also compiled with `gcc -std=c99`.


I'll move over to a compiler specific area and broach the topic.



Pre-import version statements

2023-07-19 Thread Chris Piker via Digitalmars-d-learn

Hi D

In my C code I used to typically put the line:
```
#define _POSIX_C_SOURCE 200112L
```
in the source before importing any standard library headers.  Is 
there something equivalent for phobos?  Say 
`version(phobos2.100)` or similar?


I don't particularly need this functionality, just checking to 
see if there as a formal way to denote what library standard the 
application code is expect to work against.


Thanks,


Re: Recommendation on plotting library

2023-07-19 Thread Chris Piker via Digitalmars-d-learn

On Thursday, 20 July 2023 at 03:58:05 UTC, Andrew wrote:
If you're already using python, it's probably best to keep 
using that.


Oh of course.  Examples *have* to be provided in python, since 
that's the default language of science these days.  But extra 
examples don't hurt, and it would be nice to see D along side 
other options.  I find these days that my D "scripts" are about 
the same size as my python scripts, which is really surprising 
for a compiled language.


I just tried ggplotd and it was easy to make it work on Linux, 
only one external apt command needed, but on Windows, even that 
is a deal breaker.  Package management on Windows seems to be 
wild-west/nonexistent.


Side musing... Since I've seen many people use anaconda on 
Windows, I wonder how hard it would be to make a conda package 
that provided dmd+dub?






Recommendation on plotting library

2023-07-19 Thread Chris Piker via Digitalmars-d-learn

Hi D

One of my jobs is to release and maintain public data archives 
from long-running scientific instruments.  In order to help 
people understand how to process the data, sample code is often 
included with the archive. Recently this has been in the form of 
short programs that generate a plot of a representative time 
period.  Python works well for this task as matplotlib support is 
pretty much universal.  Matlab is also a reasonable choice for 
many.


Were I to also provide sample code in D, what library would you 
recommend for scientific plotting, especially for dynamic power 
spectral densities generated from time-series data (basically 
heatmaps)?


Since dub can pull down dependencies easily enough and since it 
supports single file projects it seems that D would be well 
suited to this task, but I've never plotted any data directly 
from a D program.  Many GUI libraries I see for D are wrappers 
around external C or C++ based libraries that would need to be 
installed separately.  I'd like to avoid such complications if 
that's possible.


Thanks for any advice,


Re: Print debug data

2023-07-16 Thread Chris Katko via Digitalmars-d-learn

On Monday, 17 July 2023 at 03:43:04 UTC, Alain De Vos wrote:

Is it possible to print runtime memory usage of:
-The stack
-The heap
-The garbage collector ?


there's gc.stats for part of it:

https://dlang.org/library/core/memory/gc.stats.html



Re: Advice on debugging possible exception or crash

2023-07-06 Thread Chris Katko via Digitalmars-d-learn

On Thursday, 6 July 2023 at 06:00:04 UTC, Cecil Ward wrote:
My program is instrumented with a load of writeflns. At one 
point it looks as though it suddenly quits prematurely because 
the expected writeflns are not seen in the output. It could be 
that I am just reading the flow of control wrong as it goes 
ret, ret etc. I’m wondering if it is throwing an exception, or 
has a fault initiating a crash, perhaps even due to the 
fetching of arguments of one of the writeflns. In my limited 
experience, exceptions produce an error message though, and I’m 
not seeing anything. Any advice on how to debug this, silent 
termination ?


I don’t have a debugger on this machine, but on an x86-64 box I 
could use gdb if I first take the time to work out how.


one thing I do is have gdb/lldb break on d assert, before it 
destroys the stack. That helped me catch a class of bugs.


```sh
# in the gdb interface before running
break _d_assertp
break _d_assert
break _d_assert_msg

# or to combine it into the commandline:
gdb -ex "break _d_assert" -ex "break _d_assert_msg" -ex "run $1" 
./main


# can also add it to your .gdbinit startup code.
```


Re: Options for Cross-Platform 3D Game Development

2023-07-06 Thread Chris Katko via Digitalmars-d-learn

On Wednesday, 5 July 2023 at 22:27:46 UTC, Andrew wrote:
So, I've gotten the itch to have a go at game development in D, 
after doing a bit of it in Java last year. I've previously used 
LWJGL, which is a java wrapper for OpenGL, OpenAL, GLFW, and 
some other useful libs.


The problem is, apparently OpenGL is deprecated for apple 
devices, so I don't really want to use that unless there are no 
decent alternatives.


So far, the most promising I've seen is 
[bindbc-bgfx](https://code.dlang.org/packages/bindbc-bgfx), but 
it's been a pain to set up due to having to build the bgfx 
codebase, which requires a specific version of glibc that my 
distro (Linux Mint) doesn't offer yet.


Are there any other recommendations for cross-platform 
rendering libraries? Of course I could use a pre-made game 
engine like Unity or Godot, but for me, most of the fun is in 
making the engine.


Are you trying to make a PC game, or a mobile game? Because in 
99% of cases I would pick a different toolchain for mobile than 
PC. OpenGL being depreciated on a single, walled-garden platform, 
does not rule it out for the entire rest of installed systems.


Only if I absolutely needed, cross-platform out-of-the-box with 
mobiles and PC, would I pick a package like, Xamarin. Which now 
forces me to use C#, and the size bloat of including a mono 
framework with all my apps. I would not pick Xamarin just because 
I wanted to keep my options open, I would d pick it because I 
have a planned application that needed to be 1:1 synced across 
iPhone, Android (and possibly PC).


There's also other options. Such as using a OpenGL -> Metal 
conversion layer, like MetalAngle:


https://github.com/kakashidinho/metalangle

https://chromium.googlesource.com/angle/angle

So be sure exactly what you want as the best tools for the job 
will depend greatly on the requirements of the project.




official activate script is super confusing

2023-07-01 Thread Chris Katko via Digitalmars-d-learn

https://dlang.org/install.html#activate

I ran the two curl liners for grabbing DMD and LDC newest.

So now I have ~/dlang/ldc-1.32.2 and ~/dlang/dmd-2.104.0

How am I supposed to have both "activated"? Why does LDC have to 
override DMD, and DMD have to override LDC in the PATH?


I have both installed on another system without using this script 
and they run fine side-by-side. I can call dmd, or ldc, without 
any special "activate" calls. But this script seems to be the 
easiest/fastest way to download DMD and LDC.


I normally have separate scripts for dmd and ldc. (godmd, and 
goldc) But it seems I'll have to hardcode calls to the right 
activate script before my normal script code.


```sh
#godmd
~/dlang/dmd-2.104.0/activate
dmd -I...
```

But the activate scripts may have different version numbers in 
path!


~/dlang/dmd-2.104.0/activate

will one day become

~/dlang/dmd-2.105.0/activate

and so on.


Re: Debugging by old fashioned trace log printfs / writefln

2023-06-29 Thread Chris Katko via Digitalmars-d-learn

On Thursday, 29 June 2023 at 18:27:22 UTC, Cecil Ward wrote:
I’m trying to debug my D program with old-fashioned printfs 
stuck in various strategic places, actually using writefln(). 
My problem is that the addition of printf fights with the 
existing declarations for pure nothrow @nogc @safe and I have 
to adjust them, then put them back correctly when the 
writefln() trace statements are later removed.


Is there something else I could be using, something that is 
allowed to violate the checking rules for purity, nothrow, 
@nogc? Would pragma( msg, "…" ) do the trick? Is that what I 
should be using?


pragma(msg, "") is only for compile time. It for debugging 
functions/templates if they're actually used (which static path 
is used), instantiated, and you can also get type values from 
template inputs to confirm they're what you expect. "Oh this is a 
char[][] not a char[]!"


pragmas are the D equivalent of C/C++ pragmas. In this case, 
C/C++:

```C
#pragma message( message-string )
```



Re: pragma msg field name?

2023-06-27 Thread Chris Katko via Digitalmars-d-learn

On Tuesday, 27 June 2023 at 22:34:17 UTC, Adam D Ruppe wrote:

On Tuesday, 27 June 2023 at 22:20:22 UTC, Chris Katko wrote:

pragma(msg, t.stringof); // does not see any new fields!


D's declarations are all order-independent, in theory those 
foreaches are done simultaneously, so it is kinda a race 
condition.


Thank you, that's what I thought, but then I started adding them 
and there was no warning and I was like "wait... is this 
top-down???"




In practice, the compiler does them in two passes but both 
based on the same initial state.


Adding stuff and then reflecting over the stuff you add must be 
done as explicit steps on the outside, like you can make a 
`struct step1 {}` then `alias step2 = transform!step1;` then 
`alias step3 = transform_again!step2;` or something.


Okay again makes more sense. The amount of stuff that was "kinda" 
working, plus learning through tiny 3 liner code snippets in 
docs, was making my brain explode a bit.


A constructor/factory pattern for this makes way more sense.

Sometimes it's hard to tell where things are symbolic / 
functional, verses procedural/linear.





Re: pragma msg field name?

2023-06-27 Thread Chris Katko via Digitalmars-d-learn
Does anyone know why the new variables don't show up after the 
static foreach?


I have a struct, it has some marked fields. I want to note those 
fields at compile time and make some similarly named fields like 
myField becomes myField__replicated.


The code doesn't _have_ to be inside the struct/class itself. It 
could be:

```
auto replicatedObject = makeReplicated!(myObject);
```
for example.

I'm not sure the high-level best way right now, as I'm currently 
having issues with the nitty-gritty implementation of templates.





snippetcode (drop right into run.dlang.io):
```D
import std;

struct multiplayerObject2
{
ushort type;
ushort type2;
float x, y;

static foreach(t; typeof(this).tupleof)
{
pragma(msg, t.stringof);
		mixin("bool " ~ t.stringof ~ "25;"); // copy the fieldname with 
a suffix

}

pragma(msg, "-separator-");

static foreach(t; typeof (this).tupleof) // again
{
pragma(msg, t.stringof); // does not see any new fields!
}
}

void main()
{

}
```



```D
// Output
type
type2
x
y
-separator-
type
type2
x
y
```


Re: pragma msg field name?

2023-06-26 Thread Chris Katko via Digitalmars-d-learn

On Tuesday, 27 June 2023 at 04:56:19 UTC, Ali Çehreli wrote:

On 6/26/23 21:25, Chris Katko wrote:

> How do I get just the field name?

I know .tupleof, which you can typeof() as well:

class myObject{
int field1, field2, field3;

static foreach(field; typeof(this).tupleof)
{
pragma(msg, field.stringof);
}

static foreach(MemberType; typeof(typeof(this).tupleof)) {
pragma(msg, MemberType);
}
}

The output:

field1
field2
field3
int
int
int

I had to consult what I wrote years ago:

  http://ddili.org/ders/d.en/tuples.html#ix_tuples..tupleof

Ali


That seems to do the trick, I was really not expecting so much 
text just to get something so simple!


At the moment I'm trying to take variables with an attribute 
(rep) and then make a duplicate of them inside the struct. It 
seems to work. If I had duplicate names, it fails. However, the 
new fields don't appear to be showing up on a second enumeration:



enum rep;
struct multiplayerObject2
{
@rep ushort type;
@("rep2") ushort type2;
float x, y;

static foreach(t; typeof(this).tupleof)
{
// no if rep/rep2 here, i'm just testing:
pragma(msg, t.stringof); // does not see any new fields!
		mixin("bool " ~ t.stringof ~ "25;"); // copy the fieldname 
with a suffix

}

pragma(msg, "-separator-");

static foreach(t; typeof (this).tupleof) // again
{
pragma(msg, t.stringof); // does not see any new fields!
}
}


output
```
type
type2
x
y
-separator-
type
type2
x
y
```

However, if I do try to force the names to duplicate (say 
"type2") I get an error involving some sort of __anonymous 
subobject.

```
source/app.d-mixin-123(123,6): Error: variable 
`app.multiplayerObject2.__anonymous.type2` conflicts with 
variable `app.multiplayerObject2.type2` at source/app.d(116,19)

```

I also never realized you could put a static/static foreach 
inside the body of a struct (and not a function) so I'm still 
having trouble wrapping my head around that. Is it processing 
top-down?


Jonathan M Davis: Yeah, it does what I listed if you add the UDA 
to it.


pragma msg field name?

2023-06-26 Thread Chris Katko via Digitalmars-d-learn

inside a static foreach I can do

```
enum rep;

class myObject{
int field1, field2, field3;

static foreach(field; getSymbolsByUDA!(typeof(this), rep))
{
pragma(msg, field);  // fails
pragma(msg, fullyQualifiedName!field); // works
}
}
```

error for pragma(msg, field)
```
source/app.d(33,16): Error: value of `this` is not known at 
compile time

source/app.d(33,4):while evaluating `pragma(msg, field)`

[repeating for every variable in the class]
```

How do I get just the field name? And why does it think this is a 
run-time value? I need to wrap it in some sort of template?


All I see in std.traits docs are: fullyQualifiedName mangledName 
moduleName packageName


Re: Proper way to handle "alias this" deprecation for classes

2023-05-10 Thread Chris Piker via Digitalmars-d-learn

On Wednesday, 10 May 2023 at 20:25:48 UTC, H. S. Teoh wrote:
On Wed, May 10, 2023 at 07:56:10PM +, Chris Piker via 
Digitalmars-d-learn wrote: [...]
I also suffer from left/right confusion, and always have to 
pause to think about which is the right(!) word before uttering 
it.
Oh, I though was the only one with that difficulty.  Glad to hear 
I'm not alone. :-)


I have a tendency to think of things by their purpose when 
programming but not by their location on the line or page.  So 
terms such as "writable" versus "ephemeral" or "addressable" 
versus "temporary" (or "register"), make so much more sense to me.


Back on the ref issue for a moment... I'd imagine that asking the 
compiler to delay creating a writable variable until it finds out 
that a storage location is actually needed by subsequent 
statements, is a tall order. So D chose to introduce programmers 
to lvalues and rvalues head-on, instead of creating a leaky 
abstraction.


Re: Proper way to handle "alias this" deprecation for classes

2023-05-10 Thread Chris Piker via Digitalmars-d-learn

On Wednesday, 10 May 2023 at 16:01:40 UTC, H. S. Teoh wrote:

x   =   y;
^   ^
|   |
lvalue  rvalue


...

// This is OK:
x = y + 1;

// This is not OK:
(y + 1) = x;


Thanks for the clear explanation.

My problem with the terms lvalue and rvalue is much more basic, 
and is just a personal one that only affects probably 0.1% of 
people.  I just can't keep left vs. right straight in real life.  
"Right" in my head always means "correct".


My daughter hates it when I'm telling her which way to turn the 
car since I've said the wrong direction so many times. :)





Re: Proper way to handle "alias this" deprecation for classes

2023-05-10 Thread Chris Piker via Digitalmars-d-learn

On Wednesday, 10 May 2023 at 14:42:50 UTC, Inkrementator wrote:

On Sunday, 7 May 2023 at 21:12:22 UTC, Chris Piker wrote:

https://gist.github.com/run-dlang/9b7aec72710b1108fc8277789776962a


Thanks for posting that.  Reading over the code I'm reminded that 
I never cared whether something was an rvalue or lvalue before 
writing D code.


It's off topic, but I forget why managing memory for rvalues* was 
pushed onto the programmer and not handled by the compiler.  I'm 
sure there is a good reason but it does seem like a symmetry 
breaking requirement.


--
*or was it lvalues, I can never keep the two separate.  Wish the 
some other terminology was adopted long ago, such as "named" vs. 
"ephemeral".




Re: Proper way to handle "alias this" deprecation for classes

2023-05-07 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 7 May 2023 at 21:04:05 UTC, Inkrementator wrote:

On Sunday, 7 May 2023 at 18:19:04 UTC, Ali Çehreli wrote:
alias this is for implicit type conversions, which can be 
achieved explicitly as well.


Open question to everybody: What you're opinion on using opCast 
for this? Since it's a type conversion, it seems fitting to me.


And another suggestion: Wrap the class in a struct that has 
visibility on the class members via the "package" access 
specifier and continue using "alias this".


Hi Inkrementator

In this case, ResponseContainer is already a wrapper structure, 
so on the surface, putting a wrapper on a wrapper feels like 
over-engineering.


On the other hand, your first suggestion of using opCast() does 
seem like a reasonable choice to me.  Can you provide a short 
code snippet using opCast to achieve the same result?







Re: Proper way to handle "alias this" deprecation for classes

2023-05-07 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 7 May 2023 at 18:19:04 UTC, Ali Çehreli wrote:

auto main() {
auto c = new C();

// The same type conversion is now explicit:
foo(c.asIntPtr);
}


Hi Ali

Ah, very clear explanation, thanks!  So basically to fix the 
problem I just delete the alias this line from dpq2, see what 
unit tests and app code it breaks, then fix each of those.  
Actually seems straightforward, for a limited code base anyway.


On a side note, with all the free help you've provided, it's 
about time I gave back.  Since I've no free time or expertise to 
offer, I picked up a hardcover copy of "Programming in D" for a 
bright young programming student I know in appreciation.


Cheers,




Proper way to handle "alias this" deprecation for classes

2023-05-07 Thread Chris Piker via Digitalmars-d-learn

Hi D

One of the dependencies for my project has a class that makes use 
of the `alias x this` construct.  According to dmd 2.103, alias 
this is deprecated for classes, so I'd like to correct the 
problem.


Is there a specific paragraph or two that I can read to find out 
what is the appropriate replacement construct?  On a related 
note, has anyone created a code maintenance guide to help 
work-a-day programmers navigate recent changes to the D language?


For reference, here's a the code in question (from dpq2, 
result.d):

```d
package immutable final class ResultContainer
{
version(Dpq2_Dynamic)
{
import dpq2.dynloader: ReferenceCounter;

private ReferenceCounter dynLoaderRefCnt;
}

// ResultContainer allows only one copy of PGresult* due to 
avoid
// double free. For the same reason this class is declared as 
final.

private PGresult* result;
alias result this;   //< Deprecation Warning Here
package this(immutable PGresult* r)
{
assert(r);

result = r;
version(Dpq2_Dynamic) dynLoaderRefCnt = 
ReferenceCounter(true);

}

...
```

Thanks for any pointers,



Returning a reference to be manipulated

2023-04-13 Thread Chris Katko via Digitalmars-d-learn
I'm trying to figure out how to return a reference to something 
that may not be a reference type.


```D
struct stats
{
float[string] data=0;

float ref opIndex(string key)
  {
  return data[key]; // want a ref to a specific element
  }
}

void test()
{
stats foo;
auto x = foo.bar(); // returns some sort of reference
   // data["tacos"] = 0
x++;   // data["tacos"] = 1
}
```

Right now, I'm using pointers which resolves to:

```D
// float* opIndex(string key){...} using pointer
(*s["tacos"])++; // works with pointer, but is strange looking

s["tacos"]++; // preferred syntax or something similar
```



Assocative array lookup for object

2023-04-11 Thread Chris Katko via Digitalmars-d-learn

```D
class bitmapHandler
{
bitmap*[string] bmps;

void get(string name){return bmps[name]; /* plus other code */}
}

void usage()
{
bitmapHandler bh;
bitmap foo = bh.get("bar");  // works
bitmap foo2 = bh["bar"]; // desired
}
```

Should I be using opEquals? Or something different? The problem 
with 'alias this' here is I want to wrap access to the insides 
with getter functions that do various things like logging and 
error checking.


I mean, if I ruined some encapsulation, I could make a function 
called "bh" and have the usage:

```D
bh("bar");
```
and have it access a singleton object.



Virtual method call from constructor

2023-04-04 Thread Chris Katko via Digitalmars-d-learn

dscanner reports this as a warning:

```D
struct foo{
this()
  {
  /* some initial setup */
  refresh();
  }
void refresh() { /* setup some more stuff */}
// [warn] a virtual call inside a constructor may lead to 
unexpected results in the derived classes


}
```

Firstly, are all calls virtual in a struct/class in D? Is this 
any different from C++? IIRC, in C++, a struct cannot have 
virtual calls, and virtual methods are explicit keywords in 
classes.


Second, could you give me some case examples where this problem 
occurs? Is the issue if I override refresh in a derived class, 
and the base class will accidentally use child.refresh()?


Third, is there the expectation that you should _never_ call any 
internal, private, methods inside a constructor? Or do I just 
call/structure it a different way?


For a concrete example: I have a particle struct. It makes sense 
to me, to have initial setup code (placed in the refresh() 
function) called by this(), that later I can then call again; to 
reset the struct to an initial state in-memory without 
re-allocations.


I imagine in D that there's probably something like:

```D
particles[235] = foo.init;
```

but that blows up in a scenario where I'm only _partially_ 
resetting the struct data. For example, if I had a bunch of 
pointers to system modules, those values don't need to be nulled 
and re-set every time in this(), whereas the physical data like 
position, velocity, angle, need reset in refresh(). You could 
architect around that, but I'm trying to learn the language 
mechanics.


Re: templates and traits

2023-03-18 Thread Chris Katko via Digitalmars-d-learn

On Saturday, 18 March 2023 at 20:42:50 UTC, Nick Treleaven wrote:

On Saturday, 18 March 2023 at 19:22:07 UTC, Chris Katko wrote:
...


So there's multiple sub-problems to solve. I asked this years 
ago, and got 90% of the way done and then lost the code and 
cannot find the original forum post.


Maybe it was this?:
https://forum.dlang.org/post/dqzxnctucwvyhstfz...@forum.dlang.org


YES! I tried google search, forum search, even going through all 
my accounts posts, even my e-mail.


I think I accidentally made that post without logging in so it's 
not attached to my account posts.


templates and traits

2023-03-18 Thread Chris Katko via Digitalmars-d-learn

Given:
```D
struct pos {float x, y;}

draw(myBitmap, pos(320, 240), centered);
draw(pos(320, 240), myBitmap);
draw("text", myFont, pos(320, 240));
```

I'm writing a general "draw" template function that through 
compile-time, calls an associated DAllegro/Allegro 5 function:


```
draw(myBitmap, pos(320, 240), centered);   // 
al_draw_bitmap(myBitmap, pos.x - myBitmap.w/2, pos.y - 
myBitmap.h, 0);

draw(pos(320, 240), myBitmap); // order doesn't matter
draw("text", myFont, pos(320, 240)); // different function 
al_draw_text(...)

```

So there's multiple sub-problems to solve. I asked this years 
ago, and got 90% of the way done and then lost the code and 
cannot find the original forum post.


The pos(320,240) part works fine already. I need:

 - At compile-time, for a variadic template that can take any 
number of arguments, if specific arguments are available, I 
branch and use them to call a specific applicable C function.


I remember I need to write some sort of enum function that checks 
"IsAny" if an argument is passed at all, as well as one to find 
where that argument is. Passing duplicates probably don't matter 
(at least not right now), first valid argument is fine. I can't 
seem to write code (or find example code online) that does this.


But it's something like

```D
enum isAny() = ...;

void draw(T...)(T)
{
if(isAny(bitmap))
  {
  // it's a sprite, now find out if we need it rotated, 
stretched, etc.

  }
is(isAny(string))
  {
  // its text [...]
  }
}
```

A separate problem I've run into is, the 'centered' construct. If 
I have rotate(25) (rotate 25 degrees), that works. But I cannot 
just pass a type named "centered" with no variable attached to 
it, nor can I--I think--pass an enum.  I could do centered(false) 
or centered(0), but that's clunkier than just saying "if 
'centered' is an argument, we center it. If not, we don't." I 
could have a variable named centered, I guess. or an enum with 
{isCentered=1, notCentered=0} and detect if the enum is passed. 
Lot's of ways to skin this cat.


The idea here, is I've got a lot of optional arguments (centered, 
tinted, rotated, scaled, sheared, etc) that I can pick from and I 
don't want to have to sort through a list of 80 different 
permutations of function signatures, or, one gigantic 
megafunction with a ton of zeros/nulls for all the unused 
arguments.


This is a bit of a confusing problem to explain, so I've probably 
left something necessary out.





Re: Use dub to create source lib and executables

2023-03-04 Thread Chris Piker via Digitalmars-d-learn
On Saturday, 4 March 2023 at 21:31:09 UTC, Richard (Rikki) Andrew 
Cattermole wrote:
Yes dub was setup to cover the most common cases, but ignores 
when you have multiple outputs. Not ideal.


There is a PR to add build steps currently, which will help 
improve things, so there is work to make dub better at these 
less common use cases.


The simplest solution is to do one package per binary, then use 
a shell script to trigger them in succession, not great but a 
workable solution.


It's interesting to hear that multiple outputs are rare for other 
developers.


So I was hoping to do away with shell scripts (or make) since dub 
is common on all systems, but alas it's not worth the effort, so 
I won't continue to try and make `"targetType":"none"` work.


By the way, do you know if there will be a dub "build-all" type 
command in the future?


Re: Use dub to create source lib and executables

2023-03-04 Thread Chris Piker via Digitalmars-d-learn
On Saturday, 4 March 2023 at 20:23:29 UTC, Steven Schveighoffer 
wrote:

On 3/4/23 1:33 PM, Chris Piker wrote:

If you mean that you have multiple subprojects inside your main 
dub project, my advice is to follow what other such projects 
do. I always look at vibe for my example.


I have been trying to do that for hours, and all I get is cryptic 
error messages from dub.  I've tried all in one top level 
dub.json, I've tried three dub.json files, one at the top level 
and one for each of lib and utilities.  The fact that dub 
considers the output of a project to only be a single lib, exc, 
etc. is quite restrictive and it means we have to have a target 
of "none" and then subprojects, which is cumbersome at best.


Maybe it's just the frustration talking, but it seems wrong that 
a build rule that is so trivial to construct using 1980s 
makefiles is so hard today.  If I wasn't trying to blend in I 
would have just given up a long time ago.


But thanks for mentioning vibe.d as an example I'll take a look.





Re: Using Windbg to debug D applications and unittests

2023-03-04 Thread Chris Piker via Digitalmars-d-learn

On Monday, 27 February 2023 at 12:09:50 UTC, Basile B. wrote:
At least this is what is done for the Dexed GDB widget, so that 
gdb breaks automatically when an Error or an Exception is new'd 
(https://gitlab.com/basile.b/dexed/-/blob/master/src/u_gdb.pas#L2072).


Glad you mentioned Dexed.  I Had been meaning to try it out but 
forgot about it.  I just downloaded the deb and will give it a 
go.  Thanks!






Use dub to create source lib and executables

2023-03-04 Thread Chris Piker via Digitalmars-d-learn

Hi D

I normally work in a *nix environment, typically on server-side 
code.  For many projects I have gnu makefiles that build a small 
lib along with command line utilities.


Up to now I've been creating a dub.json file for just the 
sourceLibrary, and then putting embedded dub comments at the top 
of each of the utility programs.  The utilities are built via  
`dub build --single` and a thin makefile triggers all the dub 
commands.


This method is inefficient, and it won't work in a typical 
Windows dev environment, so today I'm trying to remove gnu make 
from the picture.  Going back to basics, does anyone know of a 
clear example of how to convert this simplified makefile into 1-N 
dub files?:


```makefile
# Build library + utility programs.
# Lib sources are in "libsrc", 1-file programs in "utils"

# Implicit rule to make a utility program
outdir/%:utils/%.d outdir/mylib.a
dmd -I libsrc -od=outdir -of=$@ $^

# Top level build rule for everything
build:outdir/mylib.a outdir/prog1 outdir/prog2 | outdir

# Explicit rule to make output directory if not present
outdir:
@if [ ! -e outdir ]; then mkdir outdir; fi

# Explicit build rule for the library
outdir/mylib.a:libsrc/mod1.d libsrc/mod2.d
dmd -lib -od=outdir -of=$@ $^
```
This is a paired down example since `make test` and `make 
install` aren't present, but I hope the main ideas are apparent.


I've been at it now for about four hours, with lots of 
web-searches (btw, thanks to schveiguy for getting me this far) 
but I haven't figured out what hierarchy of dub constructs I need 
to create to order to get the effect of the small make file above.


Thanks for considering the question,




Re: Deciding one member of iteration chain at runtime

2023-02-17 Thread Chris Piker via Digitalmars-d-learn

On Friday, 17 February 2023 at 17:42:19 UTC, Ali Çehreli wrote:

// Two different steps
auto g1 = r.map!((int n) => n * n);
auto g2 = r.map!((int n) => n * 10);

// The rest of the algoritm
auto result = choose(condition, g1, g2)
  .array;


Now that's a handy construct.

There's many little goodies in phobos I've yet to learn, thanks 
for the tip!





Re: Deciding one member of iteration chain at runtime

2023-02-17 Thread Chris Piker via Digitalmars-d-learn

On Friday, 17 February 2023 at 17:44:20 UTC, H. S. Teoh wrote:
Here's an actual function taken from my own code, that returns 
a different range type depending on a runtime condition, maybe 
this will help you?


Thanks, this was helpful.

I keep forgetting to expand my horizons on what can be returned 
from an auto function.  I'm still unlearning C & Java.


Cheers,




Deciding one member of iteration chain at runtime

2023-02-17 Thread Chris Piker via Digitalmars-d-learn

Hi D

I have a main "loop" for a data processing program that looks 
much as follows:

```d
sourceRange
  .operatorA
  .operatorB
  .operatorC
  .operatorD
  .operatorE
  .operatorF
  .operatorG
  .operatorH
  .copy(destination);
```
Where all `operator` items above are InputRange structs that take 
an upstream range, and the pipeline really is 9 operations deep.


In order to handle new functionality it turns out that operatorG 
needs to be of one of two different types at runtime.  How would 
I do something like the following:


```d
auto virtualG;  // <-- probably invalid code, illustrating the 
idea

if(runtime_condition)
   virtualG = operatorG1;
else
   virtualG = operatorG2;

sourceRange
  .operatorA
  .operatorB
  .operatorC
  .operatorD
  .operatorE
  .operatorF
  .virtualG
  .operatorH
  .copy(destination);
```
?

I've tried various usages of `range.InputRangeObject` but haven't 
been able to get the syntax right.  Any suggestions on the best 
way to proceed?  Maybe the whole chain should be wrapped in 
InputRangeObject classes, I don't know.


Thanks,


Re: Is there such a JSON parser?

2023-01-02 Thread Chris Piker via Digitalmars-d-learn

On Monday, 2 January 2023 at 14:56:27 UTC, SealabJaster wrote:


Are you asking for a SAX-styled parser for JSON?


I have an upcoming project (about 3-6 months away) that could 
make use of this as well.  If you need someone to try it out 
please let me know and I'll give it a spin.  Good luck on your 
library.


Cheers,




Convert array of simple structs, to C array of values

2022-10-03 Thread Chris Katko via Digitalmars-d-learn

```D
struct pair
  {
  float x;
  float y;
  }

pair[10] values;
import std.conv;
auto valuesInCStyle = to!(const float*)(values);

```

Now that's not going to work because (I would imagine) to! 
doesn't understand x, and y, can be placed in order to give an 
array of:


valuesInCStyle = [values[0].x, values[0].y, values[1].x 
,values[1].y, ...]


I know there's gotta be some simple one liner function in D, but 
I can't think of it.


Re: importC and cmake

2022-09-29 Thread Chris Piker via Digitalmars-d-learn

On Wednesday, 28 September 2022 at 06:04:36 UTC, zjh wrote:
On Wednesday, 28 September 2022 at 05:29:41 UTC, Chris Piker 
wrote:



`Xmake` is indeed simpler.



`Xmake` is really nice!


zjh

Sorry to go off topic for a moment, but do you happen to know how 
to tell xmake that my project is C only, and thus it shouldn't 
add the /TP flag to cl.exe?  The obvious statement:

```lua
set_languages("c99")
```
doesn't accomplish that task.

Thanks for the help,



Re: importC and cmake

2022-09-27 Thread Chris Piker via Digitalmars-d-learn

On Wednesday, 7 September 2022 at 00:31:53 UTC, zjh wrote:

`xmake` is simpler.


Thanks for the recommendation.  Was struggling with cmake for a 
dependent clib.  Xmake is indeed simpler.






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

2022-07-01 Thread Chris Katko via Digitalmars-d-learn

On Friday, 1 July 2022 at 13:28:26 UTC, Chris Katko wrote:
...wait, does "world" not 'exist' until after the constructor 
finishes? Is that's what's going on? But then why does it 
'exist' when I send it directly? Is it only "registered" with 
the module once this() finishes or something like that?


Yep, that's it.

moving all code in world.this() to world.initialize() and 
immediately calling initialize, works fine.


D
g.world = new g.world_t; // code would crash here
g.world.initialize();  // doesn't crash if moved here

class world
{
this(){}
void initialize(){/*...*/}
}

class elf : unit
{
this(pair _pos, atlasHandler atlas/*not used*/)
{   
super(0, _pos, pair(0, 0), g.dude_bmp);
		anim = new animation(1, elf_coords, g.world.atlas); //not 
crashing now

}
}


It appears module access to a class is broken until the 
constructor finishes.


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

2022-07-01 Thread Chris Katko via Digitalmars-d-learn

On Friday, 1 July 2022 at 13:12:05 UTC, Adam D Ruppe wrote:

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?



D
bool initialize() //called from main
{
g.world = new world_t;
}

class atlasHandler{}
class animation
{
this(int _numFrames, ipair[] coordinates, atlasHandler atlas)
{
}
}

class world_t
{   
atlasHandler atlas;

this()
{
viewTest();
atlas = new atlasHandler();

units ~= new elf(pair(200, 200), atlas); //crashes
}
logic()
{
// doesn't crash
units ~= new elf(pair(200, 200), atlas);
}

}

class elf : unit
{
this(pair _pos, atlasHandler atlas)
{   
super(0, _pos, pair(0, 0), g.dude_bmp);
//  anim = new animation(1, elf_coords, atlas); //doesn't crash
anim = new animation(1, elf_coords, g.world.atlas); //CRASH here
isTreeWalker = true;
}
}




also important. it seems to only occur in the constructor. If I 
create an elf after the world constructor, it's fine.


...wait, does "world" not 'exist' until after the constructor 
finishes? Is that's what's going on? But then why does it 'exist' 
when I send it directly? Is it only "registered" with the module 
once this() finishes or something like that?


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

2022-07-01 Thread Chris Katko via Digitalmars-d-learn
Forgot the last line. That's important because world MUST exist 
by time elf is called... because world... created and called elf.


So it's not a memory issue, but some sort of linkage issue.


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

2022-07-01 Thread Chris Katko via Digitalmars-d-learn
To add, I cannot even access g.world from inside elf's 
constructor.


... which is the function that called it.

D
Thread 1 "main" received signal SIGSEGV, Segmentation fault.
objects.elf.this(g.pair, objects.atlasHandler) (this=, atlas=, 
_pos=...) at ./src/objects.d:320


(gdb) bt
#0  objects.elf.this(g.pair, objects.atlasHandler) (this=, 
atlas=, _pos=...) at ./src/objects.d:320

#1  worldmod.world_t.this() (this=) at ./src/worldmod.d:60
#2  main.initialize() () at ./src/main.d:110
#3  main.main(immutable(char)[][]).__lambda6() (__capture=) at 
./src/main.d:462
#4  allegro5.system.al_run_allegro(scope int() 
delegate).main_runner(int, char**) ()

#5  allegro5.system.al_run_allegro(scope int() delegate) ()
#6  D main (args=...) at ./src/main.d:461

(gdb) x g.world
0x0:Cannot access memory at address 0x0






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

2022-07-01 Thread Chris Katko via Digitalmars-d-learn

dmd (but I think LDC also is affected)

this bug has bit me multiple times now, to the point I can 
recognize it. Accessing module variables, from inside a method, 
causes a segfault. Even if the variable should be available by 
then through the call order. Proving that its a bug, you can 
directly send the exact same variable through an argument, and it 
works fine.



(not sure if this code will do it, last time I tried to replicate 
it with solely this kind of code, the bug disappeared.)


D

/// module g.d
class world
{
atlasHandler atlas;

void do()
{
atlas = new AtlasHanlder();
elf e = new elf(atlas);
}
}

/// module 'objects.d'
class atlasHandler{}

class elf
{
this(atlasHandler atlas)
{
assert(atlas !is null); //works fine
assert(g.world.atlas !is null); //crashes

	writefln("atlas [%p] vs g.world.atlas [%s]", atlas, 
g.world.atlas);

// crashes trying to read g.world.atlas
}
}


gdb output (not the exact same module names but you get the 
point):


Thread 1 "main" received signal SIGSEGV, Segmentation fault.

(gdb) p atlas
$1 = (objects.atlasHandler *)
(gdb) p g.world
$2 = (worldmod.world_t *)
(gdb) p g.world.atlas
Cannot access memory at address 0x10
(gdb) p this
$3 = (objects.elf *)
(gdb) x atlas
0x7fffec1cf380: 0x55826580
(gdb) x g.world.atlas
Cannot access memory at address 0x10


It appears that whatever value its sending, is in a protected 
memory segment and automatically segfaulting even upon reading.


Worst case I can public my repo and you can see it for yourself.


Re: nested function overloading

2022-06-23 Thread Chris Katko via Digitalmars-d-learn
On Wednesday, 22 June 2022 at 12:42:48 UTC, Steven Schveighoffer 
wrote:

On 6/22/22 2:05 AM, monkyyy wrote:
On Monday, 20 June 2022 at 13:20:51 UTC, Steven Schveighoffer 
wrote:
And you can also use an inner struct to define overloaded 
functions.


I believe templates make a better bandaid
```d
void main(){
 template bar(){
     void bar_(int){}
     void bar_(float){}
     alias bar=bar_;
 }
 bar(1);
 bar(3.14);
}
```


Wow, I never thought of that, it's a great idea! You don't even 
need to use the alias.


```d
void main(){
template bar(){
void bar(int){}
void bar(float){}
}
bar(1);
bar(3.14);
}
```

-Steve


Wow! That's great! Another trick to add to my toolbox.


Re: can you initialize a array of POD structs?

2022-06-18 Thread Chris Katko via Digitalmars-d-learn

On Saturday, 18 June 2022 at 17:52:16 UTC, Adam D Ruppe wrote:

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.


Thanks!!

One extra caveat for anyone who googles this. You can't use {0, 
0} notation if the struct has constructors. Which make sense 
since you don't want people accidentally bypassing a constructor 
if it exists.


can you initialize a array of POD structs?

2022-06-18 Thread Chris Katko via Digitalmars-d-learn

D
struct pair { float x, y;}

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



multidim array with enum

2022-06-18 Thread Chris Katko via Digitalmars-d-learn
I'm having difficulty figuring out exactly what signature D is 
expecting.


D
enum DIR
{
UP = 0,
DOWN,
LEFT,
RIGHT,  
UPLEFT,
UPRIGHT,
DOWNRIGHT,
DOWNLEFT,
}

BITMAP*[2][DIR] bmps;

// ...

bmps[DIR.UP][0] = nope.
bmps[DIR.UP][0] = new BITMAP *; // nope
bmps[DIR.UP][0] = new BITMAP; // nope
bmps[DIR.UP] = new BITMAP*[2]; // compiles. runtime range 
violation.




I swear this all worked fine when it was just:
D
bmps[DIR] bmps;




Re: nested function overloading

2022-06-17 Thread Chris Katko via Digitalmars-d-learn

On Friday, 17 June 2022 at 12:19:33 UTC, bauss wrote:

On Friday, 17 June 2022 at 12:09:33 UTC, Chris Katko wrote:

I don't need this functionality, but I wanted to be sure.

Does function overloading not work with nested functions? I 
got a compiler error (something like "function already 
defined") when I tried it.


According to the spec then nested functions cannot be 
overloaded:


"Nested functions cannot be overloaded."

See: 19.17.1.3

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


Thanks!

re: documentation. That is one-line tiny footnote in a page 
that's over 85 pages long on my browser. :) I could easily see 
many people missing it until they encounter it.


nested function overloading

2022-06-17 Thread Chris Katko via Digitalmars-d-learn

I don't need this functionality, but I wanted to be sure.

Does function overloading not work with nested functions? I got a 
compiler error (something like "function already defined") when I 
tried it.


Re: a struct as an multidimensional array index

2022-06-10 Thread Chris Katko via Digitalmars-d-learn

On Friday, 10 June 2022 at 17:26:48 UTC, Ali Çehreli wrote:

On 6/10/22 08:13, z wrote:

> arrays of arrays has different order for declaration and
addressing,
> and declaring array of arrays has different order depending
on how you
> declare it and wether it's static or dynamic array, *oof*)
>
> To give you an idea of the situation :
> ```D
>  int[3][1] a;//one array of 3 int
>  writeln(a[0][2]);//first "column", third "row"
> ```

I've written about this multiple times in the past but D's way 
is consistent for me. That must be because I always found C's 
syntax to be very illogical on this. To me, C's problem starts 
with putting the variable name in the middle:


  // C code:
  int a[1][3]; // Why?

So, first, D moves the variable to its consistent place: after 
the type:


  int i;
  int[N] arr;

Both of those are in the form of "type and then name". Good...

And then, here is the consistency with arrays: "type and then 
square brackets".


  int[] dynamicArray;
  int[N] staticArray;

So, here is where you and I differ:

  int[3][1] arr;  // Ali likes
  int[1][3] arr;  // z wants

I like it because it is consistently "type and then square 
brackets". (It so happens that the type of each element is 
int[N] in this case.) If it were the other way, than array 
syntax would be inconsistent with itself. :) Or, we would have 
to accept that it is inside-out like in C.


But of course I understand how it is seen as consistent from 
C's point of view. :)


And this is consistent with static vs dynamic as well because 
again it's "type and then square brackets":


  int[1][] a;  // A dynamic array of int[1]
  int[][3] b;  // A static array of 3 int[]s

Ali


This is an interesting discussion. I had noticed multi-dim arrays 
seemed backwards but I assumed I was doing something wrong and 
had other thing to worry about. I had no idea it was DIFFERENT 
for static vs dynamic arrays? That's horrifying!


Also you reminded me of a possible D bug that I ran into. I had 
classes that had circular dependencies. One had to know about the 
other, and vice-versa. And I had derived classes. But somehow, 
they would explode. I would send one reference to the others 
constructor to 'link' them together, but the reference would be 
NULL. But if I accessed the exact same variable through a global 
reference, it worked fine.


I tried ripping the affected code into a new file but the bug 
wasn't replicated. Even if I matched the compiler/linker options. 
It was super frustrating.


Re: Run a command-line process with data sent, and retrieve the data.

2022-06-10 Thread Chris Katko via Digitalmars-d-learn

On Friday, 10 June 2022 at 17:37:30 UTC, Chris Katko wrote:
I want to pipe in string data to a shell/commandline program, 
then retrieve the output. But the documentation I read appears 
to only show usage for 'Files' for stdin/stdout/stderr.


ala something like this:
D
string input = "hello\nworld";
string output;
runProcess("grep hello", input, output);
assert(output = "hello");



Okay that's probably incorrect grep, but you get the point.


Run a command-line process with data sent, and retrieve the data.

2022-06-10 Thread Chris Katko via Digitalmars-d-learn
I want to pipe in string data to a shell/commandline program, 
then retrieve the output. But the documentation I read appears to 
only show usage for 'Files' for stdin/stdout/stderr.


ala something like this:
D
string input = "hello\nworld";
string output;
runProcess("grep hello", input, output);
assert(output = "hello");



a struct as an multidimensional array index

2022-06-10 Thread Chris Katko via Digitalmars-d-learn
Is it somehow possible to use a struct as a [multidimensional] 
array index:


D

struct indexedPair
{
size_t x, y;
}

bool isMapPassable[100][100];
auto p = indexedPair(50, 50);

if(isMapPassable[p]) return true;



Probably not, but I'm curious.


Odd construct idea. Splitting arguments inside a parameter list.

2022-05-23 Thread Chris Katko via Digitalmars-d-learn

D
struct pair
{
float x,y;
}

myFunction(float taco, float x, float y, float burrito)
 {
 // stuff
 }

myfunction(_taco, _x, _y, _burrito);  // call function

// But can we do this?
pair p;
myfunction(_taco, p; _burrito);  // p becomes (x,y) and satisfies 
the two floats in the signature


I don't know if I need this but I'm curious if it's a template 
possibility. Though under-the-hood it could violate some 
necessary assumption about function signature matching.


I'm curious if you can pass a struct of values (a 'tuple'?) with 
the right subfields, as if those fields occupied a function 
signature. (As I write this and try to explain it, it probably 
sounds impossible.)


I have an existing API that uses X/Y coordinates, but I like 
using packed/named tuples (right term?) for related arguments. 
pos(x,y) vs velocity(x,y) for example make it super easy to tell 
which x belongs to which construct. Worst case I could just write 
wrapper functions for like 60+ functions. But it's still an 
interesting "can D do this" idea that popped into my head 
tonight. I'm always curious about what's possible.


 - Note that it doesn't necessarily have the struct fields match 
the called function argument names. I'm talking about calling 
with a struct with two floats (of any name), fulfilling two float 
requirement of a function signature. Is there a way for a 
tuple/array/some-sort-of-combined object to fulfill two separate 
function arguments?


Of course we could always just do:
D
pair p;
myFunction(taco, p.x, p.y, burrito);



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

2022-05-22 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 22 May 2022 at 20:11:12 UTC, rikki cattermole wrote:


On 23/05/2022 8:05 AM, Chris Piker wrote:

Vibe.d is well tested against the frontend.

Its part of dmd's test suite.

See: https://buildkite.com/dlang/dmd/builds/26775
Thanks, that's handy.  Do you know where the equivalent test 
suite is for gdc?


No idea.

I've pinged Iain, because you are certainly at that point that 
is well past my knowledge of GDC. Not something I use, as it 
isn't exactly easy to use on Windows, plus LDC has some pretty 
awesome features.


Hey thanks!  I bet LDC is pretty cool, have to look into it 
sometime.  For now at my site just introducing D is a bit 
radical, don't want to capsize the boat by leaving the gcc  
toolchain altogether.  I'm willing to help out with GDC work were 
I can, at least by being a bleeding-edge tester if nothing else.


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

2022-05-22 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 22 May 2022 at 19:33:21 UTC, rikki cattermole wrote:

I should probably jump back to another thread, but maybe one more 
reply isn't too much off topic discussion...


DMD and LDC would have produced the same set of issues, because 
its the same frontend.


Oh, the compile stage works okay (after building a custom gcc), 
its linking that's the problem now.

```
dub build --single my_prog.d  # Works
env LD_RUN_PATH=/usr/local/gcc12/lib64 DFLAGS="-Wno-deprecated" 
dub build --compiler=gdc-12 --single my_prog.d  # Fails with link 
errors.

```
An example link error is:
```
/usr/bin/ld: libvibe_core.a: in function 
`_D3std6format8internal5write__T8getWidthTAwZQnFNaNbNiNfQoZl':
args.d:(.text+0x657e): undefined reference to 
`_D3std9algorithm9searching__T3allSQBg6format8internal5write__T8getWidthTAwZQnFQgZ9__lambda2Z__TQCoTQBbZQCwMFNaNbNiNfQBsZb'

```
I've made sure libgphobos.so is in the LD_RUN_PATH above.

Since there's no substitute for end-to-end testing, a CI that 
weekly grabbed packages off of code.dlang.org and tried them with 
gdc would be handy.  Now that gdc-12 is out, it might be 
something to consider.  I know that it's the package provider's 
job, but a automated friendly nudge wouldn't hurt.



Vibe.d is well tested against the frontend.

Its part of dmd's test suite.

See: https://buildkite.com/dlang/dmd/builds/26775
Thanks, that's handy.  Do you know where the equivalent test 
suite is for gdc?






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

2022-05-22 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 22 May 2022 at 19:01:41 UTC, rikki cattermole wrote:


On 23/05/2022 6:06 AM, Chris Piker wrote:
Iain's workload should be decreasing now that it is using the 
up to date frontend. Rather than the older C++ version with 
backports that he has been maintaining.


Hats off to Iain for sure.  Wish I had the resources to pay for 
his work, would certainly do so.



   2. Testing common packages against gdc


Why?


Mostly because I've put in about 15 hours effort so far trying to 
get a vibe.d based project to build using gdc, with no success.  
I'm about to give up and declare either gdc or vibe.d unsuitable 
for use in a large upcoming project.  That's too bad really 
because D only has any credibility at all in my work group due to 
the existence of gdc, and vibe.d is a nice platform to build on.


   3. Updating dub so that it could assist with creating deb 
and yum packages


Packaging is something dub doesn't do right now, it is 
something that would be very nice to have.


For this item, if there was just a "dub install --prefix=" type 
command it would be good enough.  Let the packaging tools take 
over from there and scoop-up the output.



   4. Having a standard GUI library (maybe).


If you have the many tens of millions to build it, sure.


Ah, if only.  Let me check the couch cushions, should be a trust 
fund hiding in there somewhere ;)




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

2022-05-22 Thread Chris Piker via Digitalmars-d-learn

On Wednesday, 11 May 2022 at 05:41:35 UTC, Ali Çehreli wrote:
What are you stuck at? What was the most difficult features to 
understand? etc.


To make it more meaningful, what is your experience with other 
languages?


Ali


Hi Ali, thanks for asking.

Coming from C background I had problems with voldemort types.  I 
kept wanting to know the storage type for items so that I could 
use it in interfaces, but that's not as big a deal anymore.


Currently my problem is integration into common tool chains in a 
Linux environment.  On Linux the common development tools are 
built around gcc & gdb.  The common package managers are apt and 
dnf.  Right now I can't compile vibe.d using gdc, and I can't 
`apt install vibe-d`  So I'd say lack of Linux integration is my 
most difficult problem using D.


I'd certainly contribute to a fund that focused on D Linux 
usability, namely:


  1. Supporting gdc development and distribution.
  2. Testing common packages against gdc
  3. Updating dub so that it could assist with creating deb and 
yum packages

  4. Having a standard GUI library (maybe).

These days the language itself is not so much of a concern.  The 
development days for D2 are long over.  What exists is excellent. 
 I think the central focus should on libraries and integration 
with larger ecosystems.





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

2022-05-19 Thread Chris Katko via Digitalmars-d-learn

On Thursday, 19 May 2022 at 10:35:30 UTC, ag0aep6g wrote:

On 19.05.22 12:15, Chris Katko wrote:

given
```D
struct COLOR
{
float r, g, b, a; // a is alpha (opposite of transparency)
}

auto red   = COLOR(1,0,0,1);
auto green = COLOR(0,1,0,1);
auto blue  = COLOR(0,0,1,1);
auto white = COLOR(1,1,1,1);
//etc
```

is there a way to do:
```D
auto myColor = GREY!(0.5);
// where GREY!(0.5) becomes COLOR(0.5, 0.5, 0.5, 1.0);
```


What's wrong with a simple plain function?

COLOR grey(float rgb)
{
return COLOR(rgb, rgb, rgb, 1);
}
auto myColor = grey(0.5);


Yeah that occurred to me as I was falling asleep. Though, do I 
have to a specify


```D
static auto myColor = grey(0.5);
```
to ensure it's done at compile time? It's not the end of the 
world, but ideally, these are static / hardcoded values that can 
be used thousands of times a second.


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

2022-05-19 Thread Chris Katko via Digitalmars-d-learn

given
```D
struct COLOR
{
float r, g, b, a; // a is alpha (opposite of transparency)
}

auto red   = COLOR(1,0,0,1);
auto green = COLOR(0,1,0,1);
auto blue  = COLOR(0,0,1,1);
auto white = COLOR(1,1,1,1);
//etc
```

is there a way to do:
```D
auto myColor = GREY!(0.5);
// where GREY!(0.5) becomes COLOR(0.5, 0.5, 0.5, 1.0);
```


Re: Template shenannigans with multiple datatypes

2022-05-13 Thread Chris Katko via Digitalmars-d-learn

On Friday, 13 May 2022 at 07:05:36 UTC, vit wrote:

On Friday, 13 May 2022 at 06:43:39 UTC, Chris Katko wrote:
I have an intrinsicGraph(T) class that is given a pointer to a 
T dataSource and automatically polls that variable every frame 
to add it to the graph, whether it's a float, double, integer, 
and maybe bool.


[...]


I dont understand first qestion but second question has a 
solution:


```d
intrinsic_graph!T make_graph(T, Args...)(auto ref T val, auto 
ref Args args){

return new intrinsic_graph!T(val, args);
}


instrinsicGraph!float testGraph;
instrinsicGraph!ulong testGraph2;
// later
testGraph = make_graph(units[0].x, 100, 300, COLOR(1,0,0,1));
testGraph2 = make_graph(g.stats.fps, 100, 500, COLOR(1,0,0,1));


```


Okay, to clarify just in case I'm very confusing because I'm up 
late.


If I wanted a "multipleGraph". A graph that takes multiple values 
and plots them on the same graph. I need to store a buffer for 
each dataSource. Luckily, because I'm painting them to the 
screen, the buffers only really need to be float even if they 
started as a boolean, int, or double. However, if I'm keeping a 
list of pointers to things I want to snoop when I call onTick(), 
I can't think of a way to support multiple types:


```D
class intrinsicGraph(T)
   {
   T* dataSource;
   float[] buffer;

   void onTick()
 {
 //grab datasource data and do something.
 buffer ~= to!float(*datasource);
 }
   }

auto g = intrinsicGraph!float();
```

But what if there's multiple types?

```D
class multiGraph(???)
   {
   ???[] dataSources;
   float[] buffers;

   void onTick()
 {
 //grab datasource data and do something.
 foreach(d, i; dataSources)
buffers[i] ~= to!float(*d); //or whatever
 }
   }

auto g = multiGraph!???(, , );

```

This is a kinda "dynamic language" feature but it feels like this 
information is theoretically, knowable at static, compile-time. I 
know what the variable types will be at compile-time, but I don't 
know how to put them all in one class and reference them 
automatically.




Template shenannigans with multiple datatypes

2022-05-13 Thread Chris Katko via Digitalmars-d-learn
I have an intrinsicGraph(T) class that is given a pointer to a T 
dataSource and automatically polls that variable every frame to 
add it to the graph, whether it's a float, double, integer, and 
maybe bool.


This all works fine if you have a single template type. But what 
if I want ... multiple graphs? I cannot do

D
class intrinsicGraph(T???)
{
(void*) dataSources[];
}

and have it become whatever datatype I want. Even if I'm always 
storing the values in a float buffer, the dataSources themselves 
cannot be multiple types.


Basically I'm wondering if there's a way to have
D
int FPS;
float frameTime;
//
graph myGraph;
myGraph.add();
myGraph.add();

and it enumerates through its dataSources array and adds to the 
relevant buffers.


There is a key that might help, they're all types that can 
resolve to integer or float. I'm not trying to add support for 
adding myRandomClass or networkPacket. Only things that can 
resolve down to float in some form.


Is there some kind of clue in having an array of Object (the 
fundamental superclass?)?


I don't think this is necessarily a "run time" reflection 
problem. Because I could make a graph at compile time, and know 
its of type, say, (T V U). Say, float, double, uint. Some sort of 
vardiac template.


But then how would you store that, unless you use some sort of 
mixins to write separate variables. (float\* dataSource0 and 
double\* dataSource1)


Or, wrap each pointer in some sort of fat pointer class that 
stores the type and a void*, and have an array of those fat 
pointers and and use some compile time voodoo to cast back  
cast(float)dataSource[0] (zero is always float), 
cast(uint)dataSource[2] (index 2 has cast(uint) put in).


Additional questions:

This may sound strange but is there a way to avoid having to 
specify the template type twice?

```D
instrinsicGraph!float testGraph;
instrinsicGraph!ulong testGraph2;
// later
testGraph = new intrinsic_graph!float(units[0].x, 100, 300, 
COLOR(1,0,0,1));
testGraph2 = new intrinsic_graph!ulong(g.stats.fps, 100, 500, 
COLOR(1,0,0,1));

```
It'd be nice if I only had to specify the type once.

It'd also be kinda nice if I could hide the fact I need to 
specify the type at all and have it automatically become whatever 
type the passed in value is:


D
instrinsicGraph testGraph(g.stats.fps) //automatically stores an 
integer buffer.







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

2022-05-12 Thread Chris Katko via Digitalmars-d-learn

On Thursday, 12 May 2022 at 16:04:09 UTC, Ali Çehreli wrote:
My view on private has changed over the years. I need to be 
convinced that there is usage that needs to be protected. :) I 
don't see people using types freely especially the ones that 
are in the same module. The only argument for private is to 
allow changing the implementation of published libraries in the 
future.


I use private as part of my rapid dev process. You write code, 
you get things working with no real worry for correctness or 
careful interfaces. You cannot make an interface until you 
actually know what you're making.


So you make things, with "bad" connections. Then you remove those 
connections.


1. Get system working with lots of direct access to class 
variables.

2. Make those variables forbidden (through private in C++).
3. The compiler now shows you every instance of your new 
interface encapsulation violations. No human decision to opt-in. 
No remembering to search. You have an automatically generated 
list of violations to fix.


I do the same thing with a module called "g" (for globals). I 
write new code into g, get it working. I can see how "dirty" a 
file is by simply searching for how many references to the module 
g there are. Then if I move the code into a proper new module, 
all references to g magically fail. It is impossible for me to 
leave dangling old code touching naughty internals, and I get a 
nice error view of all areas that need attention. If the uses are 
all over the place and not in only a few areas (instead of just 
in logic() and draw(), but all over the place) then I know I need 
to rewrite and introduce a system so everything is mostly in one 
place.


In D, I can do the module based method, but nothing short of 
renaming variables gives me a list of violations and, that also 
makes all the correct internal accesses wrong. Because private 
doesn't work.


Call it whatever keyword you want, I really want a 'private' 
specifier for classes. It's incredibly useful.


A template construct like using()

2022-04-26 Thread Chris Katko via Digitalmars-d-learn
I swear I asked something like this before years ago but it 
doesn't show up in my previous forum posts.


I'm looking for a construct that mimics using(var)/with(var)

D
bitmap* b;

draw_with(b)
  {
  draw_pixel(red, 16, 16); //draw red pixel to bitmap b (b is 
implied above)

  }


But the code ends up being:
D
bitmap* b;

set_target_bitmap(b); //entry code
draw_pixel(red, 16, 16); // body
set_target_bitmap(original_target); // exit code


The essence is wrapping something the code up in a kind of 
RAII-like entry and exit code that references a given target 
variable.


Perhaps a mixin is what I'm looking for?


Re: std.typecons Typedef initializers?

2022-04-25 Thread Chris Katko via Digitalmars-d-learn

On Monday, 25 April 2022 at 12:53:14 UTC, Mike Parker wrote:

On Monday, 25 April 2022 at 08:54:52 UTC, Chris Katko wrote:

D
struct pair
{
float x,y;
}

alias sPair = Typedef!pair; // pair of xy in screen space 
coordinates
alias vPair = Typedef!pair; // pair of xy in viewport space 
coordinates

//etc



How do you initialize a typedef'd struct?


``d
vPair v1 = vPair(pair(1f, 2f));
```


So to use a typedef'd struct... I have to basically add the 
original type on top of the typedef'd type every time? Surely 
it's not this clunky?


I mean, why even use a typedef then. Why not use just pair, 
sPair, vPair, etc as  separate types with identical members and 
cast as necessary? I'm not sure what the benefit typedef is 
adding here.


Thanks


std.typecons Typedef initializers?

2022-04-25 Thread Chris Katko via Digitalmars-d-learn

D
struct pair
{
float x,y;
}

alias sPair = Typedef!pair; // pair of xy in screen space 
coordinates
alias vPair = Typedef!pair; // pair of xy in viewport space 
coordinates

//etc

void test()
{
pair v0 = pair(1f, 2f); // works fine, but what about the 
typedefs?


vPair v1 = vPair(1f, 2f); //nope

vPair v2 = Typedef!vPair(1f, 2f); //nope
}



How do you initialize a typedef'd struct?


save and load a 2d array to a file

2022-04-18 Thread Chris Katko via Digitalmars-d-learn

D
struct map_t{
int data[50][50];
} map;

//save
std.file.write("save.map", map.data); // compiles

//load
map.data = std.file.read("save.map", map.data.sizeof); // error

main.d(536): Error: cannot implicitly convert expression 
`read("save.map", 2500LU)` of type `void[]` to `ubyte[50][]`



I'm guessing here, that internally we've got an array of arrays 
(which means array of pointers), and D doesn't know how to split 
by one of the axis. So how do I do that? If I know it's exactly 
packed as it was before, can I smash it somehow by direct writing 
a bunch of ubytes?


What is the 'smash' way to do it, and if better, what's the 
elegant way to do it? (In case I need either going forward).


Thanks,
--Chris


Nested function requires forward declaration?

2022-04-14 Thread Chris Katko via Digitalmars-d-learn

Using DMD. v2.098-beta-2

Not sure if right terminology. But I just wrote a nested function 
that uses a variable outside its body. The capture (right term?) 
is obvious where the invocation is. However, I have to move the 
declaration of the variable to above the nested function for it 
to compile.


Here is the code that wont compile:
D
void execute()
{
bool isKey(ALLEGRO_KEY key)
{
return (event.keyboard.keycode == key);
}
ALLEGRO_EVENT event;
// later
isKey(ALLEGRO_KEY_W);

// main.d(491): Error: undefined identifier `event`


This however, will compile:
D
void execute()
{
ALLEGRO_EVENT event; // <--Only change
bool isKey(ALLEGRO_KEY key)
{
return (event.keyboard.keycode == key);
}
// later
isKey(ALLEGRO_KEY_W);


It appears the nested function's variable capture depends on 
forward declaration (the right term?). Whereas, I was under the 
impression most/all of D worked on a multiple pass compilation so 
the order of declarations shouldn't matter.


Is this a D spec, or a compiler parsing error/oversight?

I guess if I had two different variables called event, this could 
become confusing code to read except that, mentally these should 
still link up, right?


Hypothetical:
D
void execute()
{
bool isKey(ALLEGRO_KEY key)
{
return (event.keyboard.keycode == key);
}

   {
   ALLEGRO_EVENT event;
   isKey(ALLEGRO_KEY_W);
   } //lets say this does some memory housekeeping/deleting so 
that's why we use scope

   {
   ALLEGRO_EVENT event; //new 'event', same name, new memory
   isKey(ALLEGRO_KEY_W);
   }
}


in this case, 'event' under-the-hood could be renamed, say, 
"event2" and have the same expected compile time symbol linking 
occur. The second isKey call is obviously connected to the second 
'event' variable.


I imagine this is a really odd edge case but it's piqued my 
interest.


Re: Write UTF-8 bytes directly to stack buffer

2022-03-13 Thread Chris Piker via Digitalmars-d-learn

On Thursday, 10 March 2022 at 17:59:33 UTC, H. S. Teoh wrote:
Probably what you're looking for is std.format.formattedWrite. 
For example:


```d
import std;
void main() {
ubyte[65536] buf;
char[] usable_buf = cast(char[]) buf[];
	usable_buf.formattedWrite!"Blah %d blah %s"(123, "Это UTF-8 
строка.");

auto used = buf.length - usable_buf.length;
writefln("%(%02X %)", buf[0 .. used]);
}
```


Hey thanks!  That does work with recent versions of dmd+phobos, 
but doesn't work in gdc-10.  For some reason it produces this 
error:


```d
error: static assert  "Cannot put a const(char)[] into a char[]."
```

Is there a work around involving `.representation` as alluded to 
in this 
[thread](https://forum.dlang.org/post/zmehmpithifbgfuef...@forum.dlang.org) ?


To get around the issue I built gdc-11.2 from source code at the 
GNU site but the old version of phobos is still included, so no 
dice.






Re: gdc or ldc for faster programs?

2022-03-10 Thread Chris Piker via Digitalmars-d-learn

On Tuesday, 25 January 2022 at 20:04:04 UTC, Adam D Ruppe wrote:
Not surprising at all: gdc is excellent and underrated in the 
community.


The performance metrics are just a bonus.  Gdc is the main reason 
I can get my worksite to take D seriously since we're a 
traditional unix shop (solaris -> linux).  The gcd crew are doing 
a *huge* service for the community.





Write UTF-8 bytes directly to stack buffer

2022-03-10 Thread Chris Piker via Digitalmars-d-learn

Hi D

There are quite a few string, array and range functions in phobos 
so I'm getting confused as to the right way to encode string data 
as UTF-8 directly into a stack buffer while keeping track of the 
write point.


I have some output packets I'm building up in a tight loop.  For 
speed I'm using the a priori knowledge that output packets will 
never be larger then 64K.   So what's the best way to do this:


```d
ubyte[65536] buf;
ubyte[] usable_buf = buf;

  // part of some tight loop, how to create function writef_utf8 ?
  foreach(input_thing; things){
 usable_buf.writef_utf8!"format str"(input_thing.fieldA, 
input_thing.fieldB);

  }

size_t used = buf.length - usable_buf.length;
stdout.write(buf[0.. used]);

```


Re: Source code for vibe.d listenTCP()

2022-03-08 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 27 February 2022 at 01:45:35 UTC, Adam D Ruppe wrote:
My dpldocs.info search engine is not great right now but it can 
sometimes help find these things:


http://search.dpldocs.info/?q=listenTCP


Hi Adam

Your site has been super helpful given the state of the vibe.d 
docs.  It only has one issue from my point of view.  The source 
code listing pages, for example this one:


https://vibe-core.dpldocs.info/source/vibe.core.stream.d.html#L288

don't expand horizontally to use the given space in the browser 
window.


Since the vibe.d sources contain many long lines I have to scroll 
down, find the horizontal scroll bar at the bottom of the page, 
and then scroll back up and find the function I was looking at. 
Do you observe the same behavior in your preferred browser, or is 
this just a problem in Firefox 91?


No matter what, thanks for the site. I've been using it a lot!




Re: Set output location for dub --single

2022-02-28 Thread Chris Piker via Digitalmars-d-learn

On Monday, 28 February 2022 at 08:03:24 UTC, Basile B. wrote:


That 's not exactly what you ask for but you can define the 
path in the embedded recipe (targetPath)


```d
#!/usr/bin/env dub
/+ dub.sdl:
   dependency "mypackage" version="*" path=".."
   targetPath "./bin"
+/
```


Hey thanks!  Not perfect, but it'll probably work.

I'll bring up the idea of overriding some settings (such as 
targetPath) on the command line in a similar manner to ssh in the 
dub [discussions](https://github.com/dlang/dub/discussions) area 
and see how well that goes over.


Set output location for dub --single

2022-02-27 Thread Chris Piker via Digitalmars-d-learn

Hi D

Coming from a python background it's worked well to organize my D 
projects as a dub `sourceLibrary` and then to put top level 
programs in a directory named `scripts` that are just dub single 
file projects.  So the layout looks like this:


```
rootdir/
  |
  +- mypackage/
  ||
  |+- libfile1.d
  |+- libfile2.d
  |
  +- scripts/
  ||
  |+- prog1.d
  |+- prog2.d
  |
  +- dub.json
```
In dub.json "scripts" are ignored via 
`"excludedSourceFiles":["scripts/*"]`.  Each "script" includes 
`mypackage` via:

```d
#!/usr/bin/env dub
/+ dub.sdl:
   dependency "mypackage" version="*" path=".."
   dependency (other nonlocal packages)
+/
```

...and all seems rather familiar to a python programmer and I 
avoid the complexities of dub sub-projects.


For building the individual "scripts" as binaries, it be nice 
output the binaries to another directory, say `bin`.  Is there an 
override for the dub command line that would specify the output 
location?  Maybe something like:

```bash
dub --single -o targetPath=./bin ./script/prog1.d
```
?
(Here the mythical argument `-o` overrides a single build 
configuration setting.)


After reading over the dub documentation I don't see a general 
way to override project options via the command line, but maybe 
it's there and I couldn't understand what the dub docs were 
trying to say.




Simple way to handle rvalues and templates.

2022-02-26 Thread Chris Piker via Digitalmars-d-learn

Hi D

I have bit of code that was tripping me up.  I need to parse 
small fields out of a big binary read, and it looks like some 
operations just can't be composed when it comes to

using templates.  So this works:
```d
import std.bitmanip, std.system;
ubyte[8192] data;

ubyte[] temp = data[4..6];
ushort us = temp.read!(ushort, Endian.bigEndian);
// intentionally provided the default byte order for readability
```
But this doesn't work:
```d
import std.bitmanip, std.system;
ubyte[8192] data;

ushort us = data[4..6].read!(ushort, Endian.bigEndian);
```
The reasons for this are probably old hat for seasoned D 
programmers by this is really confusing for newbies.


Is there a better way to handle this instead of making a bunch of 
temporary variables that I don't care about?  Matlab has this 
behavior too, statements that should be composable aren't, and it 
drives me crazy since Java and Python don't seem to suffer from 
this problem near a much.


Re: Source code for vibe.d listenTCP()

2022-02-26 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 27 February 2022 at 01:45:35 UTC, Adam D Ruppe wrote:
and my website also offers a "see implementation" link at the 
bottom which has some inline code navigation jump links too to 
help.

Yes! Freaking awesome!

This needs to be a link on the regular D pages, or at least in
the package index pages.  (Maybe it is already?)



Re: Source code for vibe.d listenTCP()

2022-02-26 Thread Chris Piker via Digitalmars-d-learn

On Saturday, 26 February 2022 at 22:25:46 UTC, Chris Piker wrote:
Anyway if someone can just help me find the source code to 
listenTCP inside vibe.d I'd be grateful.


Sorry to reply to myself, but I found the function.  It was 
separated
out into a separate package: https://github.com/vibe-d/vibe-core 
on
which vibe-d now depends.  D has so many code obscuring features 
that

I didn't think to check for dependencies first.



Source code for vibe.d listenTCP()

2022-02-26 Thread Chris Piker via Digitalmars-d-learn

Hi D

I'm trying out the vibe.d framework for the first time and it 
looks like many of the functions mutate some hidden global state. 
 Take for example `listenTCP`.  To help me build a mental 
picuture of the framework I'd like to see what global state is 
mutated, but for the life of me I can't even find the source code 
to listenTCP().  The obvious method of:

```bash
git clone g...@github.com:vibe-d/vibe.d.git
cd vibe.d
grep -R -n listenTCP
```
returns many instances where listenTCP is used, but none that 
look like a definition.  It's quite possible I just overlooked 
it, or maybe it's implemented as a mixin or something weird like 
that.


Anyway if someone can just help me find the source code to 
listenTCP inside vibe.d I'd be grateful.


Thanks for your time,




Re: Tips on TCP socket to postgresql middleware

2022-02-22 Thread Chris Piker via Digitalmars-d-learn

On Monday, 21 February 2022 at 07:00:52 UTC, eugene wrote:

On Monday, 21 February 2022 at 04:46:53 UTC, Chris Piker wrote:

On Sunday, 20 February 2022 at 18:00:26 UTC, eugene wrote:
I'm adverse to reading it closely since there was no license 
file and don't want to accidentally violate copyright.


:) I think WTFPL will do :)

If you want to add this file (or similar) to your sources, 
http://www.wtfpl.net/txt/copying/, but with your name in the 
copyright line I'd be happy to put the D version through it's 
paces and credit you for the basic ideas.  I would not have 
thought of this formalism on my own (at least not right away) and 
want to give credit where it's due.




Re: Tips on TCP socket to postgresql middleware

2022-02-20 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 20 February 2022 at 18:36:21 UTC, eugene wrote:


I often use two connections, one for perform main task
(upload some data and alike) and the second for getting
notifications from PG, 'cause it very incovinient to
do both in a single connection.


Ah, a very handy tip.  It would be convoluted to multiplex 
notifications

on the data connection.




Re: Tips on TCP socket to postgresql middleware

2022-02-20 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 20 February 2022 at 18:00:26 UTC, eugene wrote:


Yes, here is my engine with example (echo client/server pair):

- [In D (for Linux & 
FreeBSD)](http://zed.karelia.ru/0/e/edsm-2022-02-20.tar.gz)


The code is terse and clean, thanks for sharing :)  I'm adverse 
to reading it closely since there was no license file and don't 
want to accidentally violate copyright.


I noticed there were no dub files in the package.  Not surprised. 
 Dub is such a restrictive tool compared to say, setup.py/.cfg in 
python.




Re: Tips on TCP socket to postgresql middleware

2022-02-20 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 20 February 2022 at 17:58:41 UTC, Ali Çehreli wrote:


Another one is to set the message box sizes to throttle.


Message sizes and rates are relatively well know so it will be
easy to pick a throttle point that's unlikely to backup the
source yet provide for some quick DB maintenance in the middle
of a testing session.

In case you haven't seen yet, the recipe for std.concurrency 
that works for me is summarized here:


  https://www.youtube.com/watch?v=dRORNQIB2wA=1735s


Thanks!  I like your simple exception wrapping pattern, will use 
that.




Re: Tips on TCP socket to postgresql middleware

2022-02-20 Thread Chris Piker via Digitalmars-d-learn

On Sunday, 20 February 2022 at 15:20:17 UTC, eugene wrote:

Most people will probably say this is crazy,
but as to PG, one can do without libraries.

I am doing so during years (in C, not D) and
did not expierienced extremely complex troubles.
I mean I do not use libpq  - instead I implement some
subset of the protocol, which is needed for particular program.


Very interesting.  I need to stand-up this program and two others 
in one week, so it looks like dpq2 and message passing is the 
good short term solution to reduce implementation effort.  But I 
would like to return to your idea in a couple months so that I 
can try a fiber based implementation instead.



Usually I design more or less complex (network) programs using
event-driven paradigm (reactor pattern) plus state machines.
In other words programs designed this way are, so to say,
hierarchical team of state machines, interacting with
each other as well as with outer world (signals,
timers, events from sockets etc)


It sounds like you might have a rigorous way of defining and 
keeping track of your state machines.  I could probably learn 
quite a bit from reading your source code, or the source for 
similarly implemented programs.  Are there examples you would 
recommend?






  1   2   3   4   5   6   7   8   9   10   >