Re: Poor Carlos does not manage to find where to eat
On Saturday, 21 September 2024 at 04:29:15 UTC, user1234 wrote: ```d module m; [...] Beside the childish example... D could use a system of "constraint matching score" to help Carlos. Three AndAndExps verified should have a better score than two and finally determine the selection.
Re: assert
On Wednesday, 11 September 2024 at 10:08:29 UTC, ryuukk_ wrote: On Wednesday, 11 September 2024 at 09:14:39 UTC, Nick Treleaven wrote: On Wednesday, 11 September 2024 at 08:08:45 UTC, ryuukk_ wrote: [...] I again apologies for being wrong and i apologies again for trying to improve things, i didn't meant to do that, i now may leave again Oh no please stay, your unrecognisable passive aggressive style is so useful.
Re: How to Humanize Numerical Input|Output
On Monday, 9 September 2024 at 20:02:48 UTC, Jabari Zakiya wrote: I have this code to input integer values: ``` ulong[] x; foreach (_; 0 .. 2) { ulong a; readf!" %d"(a); x ~= a; } end_num = max(x[0], 3); start_num = max(x[1], 3); if (start_num > end_num) swap(start_num, end_num); start_num = start_num | 1; // if start_num even add 1 end_num = (end_num - 1) | 1; // if end_num even subtract 1 if (end_num - start_num < 2) { start_num = 7; end_num = 7; } ``` Currently I have to enter data as: 123456 789102 I'd like to enter data as: 123_456 789_10 How do I do that? Also for output, I do this: ``` writeln("total twins = ", twinscnt, "; last twin = ", last_twin - 1, "+/-1"); ``` I'd also like to output data as: 123,987 or 123_987 About the input, see https://issues.dlang.org/show_bug.cgi?id=20568. A remedy is to use a `myInputText.filter!(a => a != '_').to!int()` etc. ```d import std; void main(string[] args) { // string[] inputs = args[1..$]; // let's not use stdin for now string[] inputs = ["123_456", "789_10"]; auto filtered = inputs.map!(i => i.filter!(n => n != '_')); auto values = filtered.map!(f => f.to!int()); writeln(values.array); } ``` About the output I see someone just post the solution ;)
Re: D feature request
On Monday, 5 August 2024 at 03:09:41 UTC, IchorDev wrote: On Sunday, 4 August 2024 at 10:32:38 UTC, Richard (Rikki) Andrew Cattermole wrote: Chuck it into the ideas forum. If it interests somebody, somebody else can work on it. Also sometimes if a feature is very minor you can submit a ‘feature request’ issue. "enhancement" is the bugzilla word for this. IIRC it's in the "severity" field.
Re: Any way to automatically convert structs on return?
On Thursday, 1 August 2024 at 10:59:03 UTC, IchorDev wrote: On Thursday, 1 August 2024 at 09:55:08 UTC, user1234 wrote: The problem would be that sorting the candidates of an overload set would be more complicated. Also in certain cases it would be less obvious to get which one is selected. Please elaborate about how this would interact with function overloads at all? That was a general criticism of implicit construction. The classic example is ```d struct S {int i;} function f(S s); function f(int i); unittest { f(0); } // both match ``` unless the idea would rather be to allow implicit construction only in the context of initialization.
Re: Any way to automatically convert structs on return?
On Thursday, 1 August 2024 at 08:46:00 UTC, IchorDev wrote: [...] I’m pretty sure this is intentional to prevent ambiguity, but I can’t quite remember what the point of that is. The problem would be that sorting the candidates of an overload set would be more complicated. Also in certain cases it would be less obvious to get which one is selected.
Re: Weird std.path API?
On Monday, 8 July 2024 at 07:29:27 UTC, aberba wrote: On Sunday, 7 July 2024 at 15:35:36 UTC, Andrey Zherikov wrote: On Sunday, 7 July 2024 at 14:49:52 UTC, Anonymouse wrote: On Sunday, 7 July 2024 at 14:41:31 UTC, Andrey Zherikov wrote: ```d import std.path; // Error: no property `asNormaliedPath` for `dirName("/sandbox/onlineapp.d")` of type `string` auto p = __FILE_FULL_PATH__.dirName.asNormaliedPath; ``` `asNormalizedPath` is misspelled. My bad, sorry :) My blurred eyes didn't catch that I use a plugin called Code Spell Checker in VS code...or maybe spell checker which highlights spelling mistakes in methods and strings. Does it help in this case ?
Re: Wrapper around a recursive data type
On Monday, 8 July 2024 at 08:56:51 UTC, drug007 wrote: I need to generate some meta info of my data types. I do it this [...] How can I "break" this recursion or some other work around to fix it? Use `Node*[]` for the children type. That way the compiler knows the size of the (previously) problematic member. In other words, instead of the need to know `Node` size, the compiler will not look further, it's a pointer.
Re: Weird std.path API?
On Sunday, 7 July 2024 at 15:35:36 UTC, Andrey Zherikov wrote: On Sunday, 7 July 2024 at 14:49:52 UTC, Anonymouse wrote: On Sunday, 7 July 2024 at 14:41:31 UTC, Andrey Zherikov wrote: ```d import std.path; // Error: no property `asNormaliedPath` for `dirName("/sandbox/onlineapp.d")` of type `string` auto p = __FILE_FULL_PATH__.dirName.asNormaliedPath; ``` `asNormalizedPath` is misspelled. My bad, sorry :) My blurred eyes didn't catch that In first place I would have expected the spellcheck to find the error but it looks like that does not work with UFCS. https://issues.dlang.org/show_bug.cgi?id=9997
Re: Why is Phobos `Flag` so overthought ?
On Monday, 6 May 2024 at 18:06:53 UTC, Julian Fondren wrote: On Monday, 6 May 2024 at 17:55:49 UTC, user1234 wrote: I think this just works: ```d enum Flag : bool { no, yes } alias AllowVancancy = Flag; // example usage ``` ```d import std.stdio : writeln; enum Flag : bool { no, yes } alias Traditional = Flag; alias Color = Flag; void hello(Traditional traditional, Color color) { if (traditional && color) { writeln("\x1b[31;1mhello world\x1b[0m"); } else if (traditional && !color) { writeln("hello world"); } else if (!traditional && color) { writeln("\x1b[31;1mHello, world!\x1b[0m"); } else { writeln("Hello, world!"); } } void main() { hello(Color.yes, Traditional.yes); // this is wrong, but accepted } ``` Ah yes I see, strongly typed bools. Thanks 👍.
Why is Phobos `Flag` so overthought ?
I think this just works: ```d enum Flag : bool { no, yes } alias AllowVancancy = Flag; // example usage ``` Also this is completion friendly whereas Phobos version does not permit DCD completion as it's based on opDispatch. Compare to phobos version: ```d template Flag(string name) { enum Flag : bool { no = false, yes = true } } struct Yes { template opDispatch(string name) { enum opDispatch = Flag!name.yes; } } struct No { template opDispatch(string name) { enum opDispatch = Flag!name.no; } } ``` must be a reason but I cant find it RN ;)
Re: Deprecation: foreach: loop index implicitly converted from size_t to int
On Friday, 3 May 2024 at 15:19:13 UTC, user1234 wrote: On Friday, 3 May 2024 at 14:59:57 UTC, BoQsc wrote: On Friday, 3 May 2024 at 13:18:02 UTC, user1234 wrote: [...] So how would you update this example, what is the right index type here to choose? ``` import std.stdio : writefln; void main() { auto arr = [ [5, 15], // 20 [2, 3, 2, 3], // 10 [3, 6, 2, 9], // 20 ]; foreach (i, row; arr) { double total = 0.0; foreach (e; row) total += e; auto avg = total / row.length; writefln("AVG [row=%d]: %.2f", i, avg); } } ``` Example taken from https://tour.dlang.org/tour/en/basics/foreach Isn't that obvious ? ```d foreach (const size_t i, row; arr) ``` `arr` is not a static array, it is a dynamic one, consequently its `.length` type is `size_t`, even if you have the feeling that, in the present situation, `int` bitwidth would be sufficient. even better: ```d foreach (const typeof(arr.length) i, row; arr) ``` Otherwise I respect your POV, it's just that here I have no problem with the way that works. I dont see any issue with the type system. D type system is static, strong, but optionally inferred. And that's it.
Re: Deprecation: foreach: loop index implicitly converted from size_t to int
On Friday, 3 May 2024 at 14:59:57 UTC, BoQsc wrote: On Friday, 3 May 2024 at 13:18:02 UTC, user1234 wrote: On Friday, 3 May 2024 at 10:50:03 UTC, BoQsc wrote: [...] **You can specify the index type, just choose the right one.** For now there's a deprecation message but after some while you'll get a proper error message, e.g _"index type for arr must be of type T because arr.length type is T"_. What's is happening now is to help people updating their code and prevent abrupt breakages. So how would you update this example, what is the right index type here to choose? ``` import std.stdio : writefln; void main() { auto arr = [ [5, 15], // 20 [2, 3, 2, 3], // 10 [3, 6, 2, 9], // 20 ]; foreach (i, row; arr) { double total = 0.0; foreach (e; row) total += e; auto avg = total / row.length; writefln("AVG [row=%d]: %.2f", i, avg); } } ``` Example taken from https://tour.dlang.org/tour/en/basics/foreach Isn't that obvious ? ```d foreach (const size_t i, row; arr) ``` `arr` is not a static array, it is a dynamic one, consequently its `.length` type is `size_t`, even if you have the feeling that, in the present situation, `int` bitwidth would be sufficient.
Re: Deprecation: foreach: loop index implicitly converted from size_t to int
On Friday, 3 May 2024 at 10:50:03 UTC, BoQsc wrote: Why am I forced to visit this D Lang thread, why this deprecation warning still appears in my console window in the latest version of DMD. Does not make any sense from the developer's perspective to show this warning and pollute the already polluted logging entries of the compiler. How am I suppose to program anything effectively if half of the screen are some nonsensical deprecation warnings without guidance or sane explanations. This is not better ``` foreach (i, row; arr) ``` than ``` foreach (int i, row; arr) ``` Hides the datatype and makes the D language appear in-explicit and annoying. What is this language becoming. A completely weak typed language or something? I would use JavaScript if I would want that. How are we suppose to make whole sane Operating Systems with such syntaxes. Do everyone just enjoy having bugs with some implicit size_t, or do everyone just enjoy deprecation warnings in their logging systems when there are way more important problems to solve, that are actually project related. You can specify the index type, just choose the right one. For now there's a deprecation message but after some while you'll get a proper error message, e.g _"index type for arr must be of type T because arr.length type is T"_. What's is happening now is to help people updating their code and prevent abrupt breakages.
Re: aliasing private
On Wednesday, 1 May 2024 at 12:07:26 UTC, NotYouAgain wrote: I want to do a C like #define on private, but I can't ie. #define private fileprivate // --- module m; alias fileprivate = private; // grr! class myClass { fileprivate int n; } // --- You cant. That is simply not supported.
Re: How to add a character literal to a string without ~ operator?
On Thursday, 4 April 2024 at 19:56:50 UTC, Ferhat Kurtulmuş wrote: On Thursday, 4 April 2024 at 18:14:54 UTC, BoQsc wrote: I'm looking for more readable standard function to add a **character** literal to a **string**. The `~` operator is clearly not great while reading a source code. I'm not here to discuss that. I'm looking for a function inside standard library. The function should be straightforward, up to two words. Here is what I expect from a programming language: Pseudo example: ``` import std; void main(){ string word = hello; join(word, 'f', " ", "World"); writeln(word); // output: hellof World } ``` My favorite d feature is lazy ranges. No allocation here. ``` auto s = chain("as ", "df ", "j"); // s is lazy writeln(s); ``` Of course you can allocate a new string from the chained range: ``` string str = cast(string)s.array.assumeUnique; // without a cast it is a dstring (why though?) ``` ```d module runnable; import std.stdio : writeln; import std.range : chain; void main() @nogc { auto s = chain("as ", "df ", "j"); // s is lazy writeln(s); } ``` Bad example. The range is indeed a `@nogc` lazy input range but `writeln` is not a `@nogc` consumer. /tmp/temp_7F91F8531AB0.d(9,12): Error: `@nogc` function `D main` cannot call non-@nogc function `std.stdio.writeln!(Result).writeln` /bin/ldc2-/bin/../import/std/stdio.d(4292,6):which calls `std.stdio.trustedStdout` The input range consumer has to be @nogc as well.
Re: static functions?
On Monday, 11 March 2024 at 16:51:48 UTC, Andy Valencia wrote: On Monday, 11 March 2024 at 16:25:13 UTC, Jonathan M Davis wrote: ... But what exactly static means varies based on the context. Thank you for the list! But none of those appear to apply to a function defined in the outermost scope of the module. Is static accepted here--but has no actual effect? Yes module-level `static` (for what is aka "free-functions", but also variables) is a noop. Module-level is implicitly static. I will look at the privacy controls--thanks again. No need to ;) D `static` is a storage class, not a visibility attribute. Andy
Re: New update fix
On Saturday, 2 March 2024 at 08:41:40 UTC, Salih Dincer wrote: SLM, What exactly did this patch with the new update fix? Nothing, it looks like what happened is that the issue was wrongly referenced by a dlang.org PR (https://github.com/dlang/dlang.org/pull/3701/commits/4e8db30f0bf3c330c3431e83fe8a75f843b40857).
Safety is not what you think
I want to share a stupid program to show you that D safety is more complex than you might think: ```d module test; void test() @safe { int i; int b = (*&(*&++i))++; } void main() @safe { test(); } ``` I'm not showing a deficiency of D, that program is undeniably safe ;)
Re: Function Composition
On Wednesday, 24 January 2024 at 21:30:23 UTC, user1234 wrote: On Wednesday, 24 January 2024 at 21:12:20 UTC, atzensepp wrote: [...] what a bummer! Have you tried https://dlang.org/phobos/std_functional.html#compose ? Well this violates the second requirement: the composition itself requires additional lambda expressions I would like to write compose(f,g) I just realize, as this requires template specialization with `!`. But this is how D works with these kind of things.
Re: Function Composition
On Wednesday, 24 January 2024 at 21:12:20 UTC, atzensepp wrote: [...] what a bummer! Have you tried https://dlang.org/phobos/std_functional.html#compose ?
Re: Understanding the Use of Nested Import and Selective Import in D
On Tuesday, 16 January 2024 at 13:37:59 UTC, user1234 wrote: Implementation detail. D frontend resolves identifiers using associative arrays (that's called symtabs in the compiler IIRC), hence the only complexity is the scope (plus the import decls found while going back to the module scope). oops forgot to say: so it's fast.
Re: Understanding the Use of Nested Import and Selective Import in D
On Tuesday, 16 January 2024 at 13:19:59 UTC, Orfeo wrote: I found myself a bit perplexed when it comes to the usage of "nested imports" and selective imports. It seems that prominent D programmers have varied opinions on the matter. I would love to hear your insights and experiences on this topic. Here's a quick summary of what I've come across from three influential D programmers: - Adam Ruppe: In his blog post titled [D's selective imports have effects you may not want](http://dpldocs.info/this-week-in-arsd/Blog.Posted_2023_11_06.html) have effects you may not want, Adam advises against the use of selective imports. He highlights potential unwanted side effects and suggests caution when employing them. - Atila Neves: At DConf 2023, Atila Neves recommended the use of nested imports. He argues that nested imports can make refactoring easier and help in assessing the dependencies a function has. - Rober Schadek: Also at DConf 2023, Rober Schadek discouraged the use of nested imports, taking a stance different from Atila Neves. Now, the big question is: What's your preferred approach? Another point is that the use of selective imports tends to be "a refactoring". You start with a global or local import. Once everything is fine you'll think that's it's a good idea to make the import selective, i.e "because I only use that in there". Problem is, if someone else at some point work on your code: 1. he needs to add more to the selection 2. completion may not work anymore (will only show what's selected) So it's a bit a thing of expert. Given these arguments I think that global imports should not be selective, only local ones should. Implementation detail. D frontend resolves identifiers using associative arrays (that's called symtabs in the compiler IIRC), hence the only complexity is the scope (plus the import decls found while going back to the module scope).
Re: `static` function ... cannot access variable in frame of ...
On Monday, 15 January 2024 at 18:34:58 UTC, H. S. Teoh wrote: On Mon, Jan 15, 2024 at 06:16:44PM +, Bastiaan Veelo via Digitalmars-d-learn wrote: Hey people, I can use some help understanding why the last line produces a compile error. ```d import std.stdio; struct S { static void foo(alias len)() [...] The trouble is with the `static` here. A context pointer is necessary in order to have access to the context of main() from the body of this function; but `static` precludes this possibility. T I dont agree, problem is S_foo that get automagically monomorphized in `main` scope. That's a very classic D problem.
Re: `static` function ... cannot access variable in frame of ...
On Monday, 15 January 2024 at 18:16:44 UTC, Bastiaan Veelo wrote: [...] It seems to me this should just work. Thanks! --Bastiaan. The two calls are not equivalent. To be equivalent you need to set `S_foo` static too, otherwise `S_Foo` is instanciated in `main` scope, proof: ```d import std.stdio; struct S { static void foo(alias len)() { writeln(len); } } static void S_foo(alias len)() { writeln(len); } void main() { const five = 5; S_foo!five; // Error too now S.foo!five; // Error } ``` so what is passed as alias need to be static too. But to be frank, I agree this is a less ideal situation. There are like 20 bugs reports opened related to that. The way a non-static `S_foo` behaves is under-specified.
Re: Synchronisation help
On Tuesday, 2 January 2024 at 11:39:12 UTC, Anonymouse wrote: On Tuesday, 2 January 2024 at 11:05:33 UTC, user1234 wrote: Do not use `shared` AA. Use `__gshared` + sync primitives. `shared` AA will lead to all sort of bugs: - https://issues.dlang.org/show_bug.cgi?id=20484#c1 - https://issues.dlang.org/show_bug.cgi?id=17088 - https://issues.dlang.org/show_bug.cgi?id=16597 - etc. Hmm, I see. Is `shared` safe to use with AAs *provided* I use sync primitives, or should I favour `__gshared` over `shared`? I was under the impression `__gshared` was only really meant for interfacing with C. The semantics of __gshared in this context is "no-TLS". You meant to access the AA in several threads right ? So you dont want each thread to have its own copy.
Re: Synchronisation help
On Monday, 1 January 2024 at 15:48:16 UTC, Anonymouse wrote: I have a `shared string[int]` AA that I access from two different threads. The function I spawn to start the second thread takes the AA as an argument. [...] What is the common solution here? Do I add a module-level `Object thing` and move everything accessing the AA into `synchronized(.thing)` statements? Or maybe add a `shared static` something to `Foo` and synchronise with `synchronize(Foo.thing)`? Do not use `shared` AA. Use `__gshared` + sync primitives. `shared` AA will lead to all sort of bugs: - https://issues.dlang.org/show_bug.cgi?id=20484#c1 - https://issues.dlang.org/show_bug.cgi?id=17088 - https://issues.dlang.org/show_bug.cgi?id=16597 - etc.
Re: Indirect access to variables.
On Friday, 29 December 2023 at 17:11:49 UTC, DLearner wrote: Compile-time: [...] Is there a 'foo1' that yields 1 from the snippet below? [...] Similarly, execution-time, is there a foo2 that wields 2 from the snippet below: [...] **compile-tome** ```d void main() { import std.stdio; size_t var1 = 1; size_t var2 = 8; writeln(mixin(var1.stringof)); writeln(mixin(var2.stringof)); } ``` **run-tome** Given the information you provide I'd say you can use an associative array: ```d size_t*[string] registry; void main() { import std.stdio; size_t var1 = 1; size_t var2 = 8; registry[var1.stringof] = &var1; registry[var2.stringof] = &var2; writeln(*registry[var1.stringof]); writeln(*registry[var2.stringof]); } ``` but take care to the entries lifetime, that's basically not safe as this escapes stack addresses.
Re: How to hash SHA256 from string?
On Saturday, 2 December 2023 at 16:17:08 UTC, user1234 wrote: On Saturday, 2 December 2023 at 15:30:39 UTC, zoujiaqing wrote: [...] sign is binary, you have to use the toHexString utility : ```d import std.stdio; import std.digest.sha; void main() { SHA256 sha256; sha256.start(); string appKey = "1"; sha256.put(cast(ubyte[])appKey); ubyte[32] sign = sha256.finish(); writeln("sign: %s", toHexString(sign)); } ``` also you add a range error on data assignment. and a last error I have not initially catch, use writefln: ```d writefln("sign: %s", toHexString(sign)); ```
Re: How to hash SHA256 from string?
On Saturday, 2 December 2023 at 15:30:39 UTC, zoujiaqing wrote: ```D import std.stdio; import std.digest.sha; void main() { SHA256 sha256; sha256.start(); string appKey = "1"; ubyte[1024] data = cast(ubyte[])(appKey.dup[0..$]); sha256.put(data); ubyte[32] sign = sha256.finish(); string sign1 = cast(string) sign[0..$]; writeln("sign: %s", sign1); } ``` The result varies when you run the code repeatedly and the display is garbled: ``` zoujiaqing@mac test % ./test Getui access sign: %s>tM?a?j,???ߥm?8l~??uzU?|9?~ˡ zoujiaqing@mac test % ./test Getui access sign: %s1-??U? ?d<3^3??נ? ??P%u/Iv zoujiaqing@mac test % ./test Getui access sign: %s1?ϻN?ށ?`O?p!?O?4U :8J~%ʬ zoujiaqing@mac test % ./test Getui access sign: %s??k#O?;?ڋ?5T?"=??;???e ``` sign is binary, you have to use the toHexString utility : ```d import std.stdio; import std.digest.sha; void main() { SHA256 sha256; sha256.start(); string appKey = "1"; sha256.put(cast(ubyte[])appKey); ubyte[32] sign = sha256.finish(); writeln("sign: %s", toHexString(sign)); } ``` also you add a range error on data assignment.
Re: Inversion of conditional compilation statements
On Saturday, 2 December 2023 at 13:16:26 UTC, Johannes Miesenhardt wrote: Hello, [...] I see the way why it doesn't work, but I think it should. Considering that `version (Test) {} else {` works without any issue but looks very ugly. Can somebody explain if this is an intended decision or what I should do instead of using my ugly replacement? It's an intended decision that's often debated, a.k.a "version algebra". The official position on version algebra is that complex conditions (think `&&` and `||`) would be a source of bugs.
Re: Is a shorter statement possible in this case?
On Sunday, 5 November 2023 at 18:36:40 UTC, Ctn-Dev wrote: I wrote this earlier: [...] if runs when both "One" and "Two" are in the given array as intended, but its conditional statement looks verbose. Is there a more concise way of getting the same result? Yes, assuming you accept to drop your string arrays then one is to use bit flags: ```d enum NumTraitBits { Empty, One = 0x01, Two = 0x02, Three = 0x04, // ... _ = 0xF0 } NumTraitBits numeric_traits_1 = NumTraitBits.Empty; NumTraitBits numeric_traits_2 = NumTraitBits.Two; NumTraitBits numeric_traits_3 = NumTraitBits.One; NumTraitBits numeric_traits_4 = NumTraitBits.Two | NumTraitBits.One; void main() { import std.stdio, std.traits; void numeric_traits_contains(NumTraitBits numeric) { write("contains: "); foreach (i; EnumMembers!NumTraitBits) if (numeric & i) write(" ", i); writeln(); } numeric_traits_contains(numeric_traits_1); numeric_traits_contains(numeric_traits_2); numeric_traits_contains(numeric_traits_3); numeric_traits_contains(numeric_traits_4); } ```
Re: extern (c)
On Wednesday, 11 October 2023 at 13:36:16 UTC, Paul wrote: On Wednesday, 11 October 2023 at 12:54:53 UTC, user1234 wrote: `extern(C)` on module level functions affect the mangling and the calling convention. - Mangling is used by the linker to link symbols between objects. - Calling convention affects the compiler backend in how code is generated for a CALL instruction. So C doesn't use name mangling I see what you mean. I just consider no mangling as a kind of mangling, that is "just the symbol name". and extern (C) in a D prog would turn off D mangling thereby allowing C and D object files to be linked together? I didn't know C and D had different calling conventions...i.e. different ABI's? They are mostly similar but according to https://dlang.org/spec/abi.html#function_calling_conventions there are differences.
Re: extern (c)
On Wednesday, 11 October 2023 at 12:36:58 UTC, Paul wrote: What does the extern (c) attribute(?) do? Does it tell the compiler/linker to build the function like a C compiler would build a C function? If so what does that mean? Does it tell the compiler/linker to let C functions know it exists? If so what does that mean? Is it meant for the compiler or linker or both? Thanks for any assistance. `extern(C)` on module level functions affect the mangling and the calling convention. - Mangling is used by the linker to link symbols between objects. - Calling convention affects the compiler backend in how code is generated for a CALL instruction.
Re: Getting all struct members and values with introspection avoiding string mixins
On Thursday, 5 October 2023 at 22:24:06 UTC, mw wrote: On Thursday, 5 October 2023 at 21:41:38 UTC, cc wrote: If you have `T info`, T.tupleof[n] will always match up with info.tupleof[n]. You can think of `info.tupleof[n]` as being rewritten by the compiler in-place as info.whateverFieldThatIs. You might try this version (note the double {{ }} with static foreach): ```d void printStructInfo( T )( T info ) { static foreach( i, A; info.tupleof ) {{ enum attribName = T.tupleof[i].stringof; writefln( "%s : %s", attribName, info.tupleof[i] ); }} } ``` Be advised that T.tupleof and __traits(allMembers, T) return two different sets of things. allMembers will probably get you a lot of stuff you don't want and will need to write checks to avoid. Using .tupleof is a perfectly acceptable practice. Thanks, this version does not include the alias. Be aware however that `.tupleof[i]` create at compile time the tuple, just to read a single element, when finally just one is required.
Re: How to get all modules in a package at CT?
On Thursday, 5 October 2023 at 20:42:26 UTC, mw wrote: On Thursday, 5 October 2023 at 20:07:38 UTC, user1234 wrote: No. Sorry. Generally compile time code cannot interact with the system. To be evaluable at compile time code has to be strongly pure, that is not the case of the function you would need. Otherwise you'd need a new traits for that... but that traits would violate the rule explained before. If you want to iterate the package for modules imported in it, I'm not sure. __traits(allMembers, package) will list names of imported packages but not which modules. static reflection on import decls is broken, that wont work well So how about at runtime? I just want the compiler to help to list them, instead of doing manually. I dont have in mind what info are provided by TypeInfoModule but maybe.
Re: How to get all modules in a package at CT?
On Thursday, 5 October 2023 at 18:40:36 UTC, mw wrote: On Saturday, 24 November 2018 at 15:21:57 UTC, Anonymouse wrote: On Saturday, 24 November 2018 at 08:44:19 UTC, Domain wrote: I have a package named command, and many modules inside it, such as command.build, command.pack, command.help... I want to get all these modules at compile time so that I know what command is available. If you just want static if expressions of whether *known* modules are available or not, then test if __traits(identifier, package.module) compiles. --- // Two-step workaround for https://issues.dlang.org/show_bug.cgi?id=19409 enum hasBuild = __traits(compiles, __traits(identifier, command.build)); enum hasPack = __traits(compiles, __traits(identifier, command.pack)); enum hasHelp = __traits(compiles, __traits(identifier, command.help)); static if (hasBuild) { /* ... */ } static if (hasPack) { /* ... */ } static if (hasHelp) { /* ... */ } --- __traits(compiles, { import package.module; }) mostly works, but I ran into problems when the module was available and merely did not compile. If you want to iterate the package for modules imported in it, I'm not sure. __traits(allMembers, package) will list names of imported packages but not which modules. How to list unknown sub-modules? (and not walking the source tree dir). Is there a compile time solution to this problem? Thanks. No. Sorry. Generally compile time code cannot interact with the system. To be evaluable at compile time code has to be strongly pure, that is not the case of the function you would need. Otherwise you'd need a new traits for that... but that traits would violate the rule explained before. If you want to iterate the package for modules imported in it, I'm not sure. __traits(allMembers, package) will list names of imported packages but not which modules. static reflection on import decls is broken, that wont work well
Re: parallelism with delegate
On Friday, 22 September 2023 at 04:33:44 UTC, Vitaliy Fadeev wrote: On Friday, 22 September 2023 at 04:24:19 UTC, Vitaliy Fadeev wrote: ... Skip this thread. I see solution. How to delete missed posts on this forum ? It's there forever, you have to live with that error ;) See https://forum.dlang.org/help#about
Re: C to D: please help translate this weird macro
On Thursday, 21 September 2023 at 16:28:25 UTC, Nick Treleaven wrote: (Untested) There might be a `need this` error
Re: Dinamyc arrays
On Sunday, 17 September 2023 at 17:15:34 UTC, Timofey wrote: I`ve just started learning d and have a question. What should I write to set dinamyc rectangular array length in both dimentions? For example, I have declareted an array: ```d int[][] matrix; ``` and want set it as n*n matrix. Thanks You can flatten the mat and use operator overloads. Here's a some basic code to get started: ```d struct SquaredMat(T) { size_t dim; T[] array; this(usize dim) { this.dim = dim; array.length = dim * dim; } auto opIndex(size_t x, size_t y) { return array[x * dim + y]; } auto opIndexAssign(size_t x, size_t y, T value) { array[x * dim + y] = value; return this; } } ``` Those kind of type should already exist in 3rd part native D libraries, e.g "MIR" has something called "NDSlice" IIRC.
Re: pipeProcess output to hash string
On Monday, 11 September 2023 at 22:08:54 UTC, Christian Köstlin wrote: Just three remarks: First I would recommend to use `std.process : execute` instead of `pipeProcess` in this usecase, as this will wait properly for the process to exit and it also will collect its output. Second its always good to test the exit status of the process ... just in case. Third I would not look at `stderr` too much .. well behaved commandline tools should not put data for machines there. Kind regards, Christian I'll add that the way pipeProcess is overloaded does not help. One take the whole command line as a string the other each element as an array. Very easy to get it wrong.
Re: pipeProcess output to hash string
On Saturday, 9 September 2023 at 15:44:44 UTC, Vino wrote: Hi All, Request your help on how to convert the output of std.process.pipeProcess to hash string ``` auto test(in Redirect redirect=Redirect.stdout | Redirect.stderr) { import std.process; import std.digest.crc; import std.stdio: writeln; result = std.process.pipeProcess("whoami" ~ "/?", redirect); auto content = result.stdout.readln; auto hash = crc32Of(content); return hash; } void main() { writeln(test); } ``` Output: All writes the below. ``` [0, 0, 0, 0] ``` Required: Read the completed output and convert it to a single hash string. From, Vino.B With a slightly modified command line that works on linux here : ```d import std.process, std.stdio; auto test(in Redirect redirect=Redirect.stdout | Redirect.stderr) { import std.digest.crc; import std.stdio: writeln; auto result = std.process.pipeProcess(["whoami"], redirect); auto content = result.stdout.readln; auto hash = crc32Of(content); return hash; } void main() { writeln(test); } ``` not sure why you append "/?" to the program name.
Re: Is sizeof() available in D language?
On Monday, 4 September 2023 at 09:41:54 UTC, BoQsc wrote: I've seen everyone using **datatype**`.sizeof` property. https://dlang.org/spec/property.html#sizeof It's great, but I wonder if it differ in any way from the standard C function `sizeof()`. https://www.geeksforgeeks.org/sizeof-operator-c/ https://en.cppreference.com/w/cpp/language/sizeof I'm seeking for some speed/performance, so that's why the question. Overall I'm alright with continuing using it. In both case it's replaced at compile-time by an IntegerExpression (the ast node for an integer literal) I would not loose too much time comparing the "postfix" style (D) with the "intrinsic" style (C). Possibly there might a few micro ops difference... so only significant compile-time difference for 1 Billion `sizeof` ;)
Re: Cool pattern or tragic?
On Friday, 25 August 2023 at 21:00:08 UTC, Guillaume Piolat wrote: The idea is to deliberately mark @system functions that need special scrutiny to use, regardless of their memory-safety. Function that would typically be named `assumeXXX`. ```d class MyEncodedThing { Encoding encoding; /// Unsafe cast of encoding. void assumeEncoding (Encoding encoding) /* here */ @system /* here */ { this.encoding = encoding; } } char* assumeZeroTerminated(char[] str) @system { return str.ptr; } ``` That way, @safe code will still need to manually @trust them. I think it's smart for `assumeZeroTerminated` because you cannot use assertions or contracts to verify that. I'd like to think the same for `assumeEncoding` but actually I dont see where is the unsafe cast.
Re: Implicit type conversion depending on assignment
On Thursday, 23 March 2023 at 14:17:25 UTC, user1234 wrote: not exactly thing goal yet. The doc example you have put a link for is different, the struct with alias this a redefinition of the "alias this"'ed thing, that just cant work in what you ask in the first post. omg, let's rewrite this... not exactly the same thing as the goal yet. The doc example you have put a link for is different, the struct with "alias this" is a redefinition of the "alias this"'ed thing, that just cant work in what you ask in the first post because the type is different.
Re: Implicit type conversion depending on assignment
On Thursday, 23 March 2023 at 14:05:07 UTC, Alexander Zhirov wrote: On Thursday, 23 March 2023 at 13:38:51 UTC, Alexander Zhirov wrote: Is it possible to convert such records inside the structure to the assigned type? ```d struct MyVal { string value; // Here it would be possible to use an alias to this, but it can only be used 1 time } auto a = MyVal("100"); auto b = MyVal("11.2"); int MyInt = a;// Implicitly convert to target type float myFloat = b;// Implicitly convert to target type ``` Here is an [example from the documentation](https://dlang.org/spec/struct.html#alias-this), but for "several" types, for example, with a cast check and a return of the default value. The best I can think of ATM ``` struct MyVal { string value; auto opCast(T)() { import std.conv : to; return to!T(value); } } void main() { auto a = MyVal("100"); auto b = MyVal("11.2"); int MyInt = cast(int)a; float myFloat = cast(float)b; } ``` not exactly thing goal yet. The doc example you have put a link for is different, the struct with alias this a redefinition of the "alias this"'ed thing, that just cant work in what you ask in the first post.
Re: Preventing the Compiler from Optimizing Away Benchmarks
On Monday, 13 March 2023 at 14:17:57 UTC, jmh530 wrote: I was looking at [1] for ways to prevent the compiler from optimizing away code when trying to benchmark. It has the following C++ code as a simpler version: ``` inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) { asm volatile("" : "+r,m"(value) : : "memory"); } ``` I made an attempt to make a D version of it, but failed. Apparently DMD doesn't like the `""` in the first part of the asm instruction. I'm also not sure the `volatileLoad` command is right, but I didn't know of any other way to have volatile work in D (and I couldn't figure out how it actually worked from looking at the code). ``` void DoNotOptimize(T)(T* ptr) { import core.volatile: volatileLoad; T value = volatileLoad(ptr); asm {"" : "+r,m"(value) : : "memory";} } ``` [1] https://theunixzoo.co.uk/blog/2021-10-14-preventing-optimisations.html that's illegal code. You mix GCC/LLVM syntax with D asm block and the front-end wont recognize that. LDC recognizes a syntax similar to what is described in your link, see https://wiki.dlang.org/LDC_inline_assembly_expressions. GDC has it too (since that the syntax invented by GCC in first place) but I cant find the documentation ATM.
Re: Can nice D code get a bit slow?
On Wednesday, 8 March 2023 at 12:46:53 UTC, Hipreme wrote: On Wednesday, 8 March 2023 at 10:49:32 UTC, Markus wrote: Hi, sorry for the broad and vague question. I have read in some reddit post about benchmarks, that some code didn't use the final keyword on methods in a sense that final would make it faster, I believe. [...] Don't bother with it. This kind of optimization is done when compiling with -O, No they are not, simple example : https://godbolt.org/z/xfPqnWrrv Obviously in a library `test` might be called with a derived so `v1()` target address must be read in the vtbl of the argument. and I really doubt about your bottleneck being that you're calling a virtual call. That is more true. vcalls dont add complexity. Wait when you actually need to optimize before making your code ugly.
Re: Template alias parameter: error: need 'this' for ...
On Friday, 24 February 2023 at 12:00:41 UTC, Elfstone wrote: Seems like the same bug is still there after ten years. ```d struct Bar { @("hello") int t; } static bool hasAttribute(alias F, T)() { bool result = false; foreach (a; __traits(getAttributes, F)) { static if (is(typeof(a) : T)) { result = true; // couldn't simply return true, 'cause the compiler complains about "unreachable code". } } return result; } void main() { import std.stdio; writeln(hasAttribute!(Bar.t, string)); } ``` you can break using `goto`, restore `static` everywhere, and using local introspection determine whether the result exists. ```d struct Bar { @("hello") int t; } static bool hasAttribute(alias F, T)() { static foreach (a; __traits(getAttributes, F)) { static if (is(typeof(a) : T)) { enum result = true; goto L0; } } L0: static if (is(typeof(result))) return result; else return false; } void main() { import std.stdio; writeln(hasAttribute!(Bar.t, string)); } ```
Re: ELIZA Chatbot Implementation From C to D Lang
On Friday, 17 February 2023 at 17:03:34 UTC, ron77 wrote: Hello, I succeeded in converting an ELIZA code from C to D, and here are the results. although I'm sure there are better ways to code it or to convert it... [...] Among the things to do the first is to drop C-style strings, so that you can get rid of `strlen()` and `strcat()` for example. Then maybe try to rewrite your for-loops as UFCS pipes. Have fun.
Re: compile: link dynamic OR static library in Windows
On Sunday, 5 February 2023 at 11:52:01 UTC, Alexander Zhirov wrote: On Saturday, 4 February 2023 at 15:56:41 UTC, Richard (Rikki) Andrew Cattermole wrote: [...] I don't understand why the compiler doesn't see the library. ```sh User@WIN-D3SHRBHN7F6 MINGW64 /home/user/pxe-restore/source # ls -la "C:\Program Files\PostgreSQL\15\lib\libpq.lib" -rw-r--r-- 1 User Отсутствует 37002 Nov 9 06:45 'C:\Program Files\PostgreSQL\15\lib\libpq.lib' User@WIN-D3SHRBHN7F6 MINGW64 /home/user/pxe-restore/source # dmd -i app.d -L'C:\Program Files\PostgreSQL\15\lib\libpq.lib' lld-link: error: could not open 'pq.lib': no such file or directory Error: linker exited with status 1 ``` try ``` dmd -i app.d -L'-LC:\Program Files\PostgreSQL\15\lib' -Llpq ``` the first linker command gives a search path, the second a libname.
Re: _Symbols _with _leading _underscores
On Saturday, 17 December 2022 at 02:42:22 UTC, Paul wrote: I see code like this from time to time. Are the leading underscores significant, in general, in the D language? Is it just programmer preference? Is it a coding practice, in general, that is common...even outside of D? Thanks for any assistance. The only important thing you should know about is that doubly leading underscores are reserved for symbols generated by the D front-end, so you should avoid them. This is specified here: https://dlang.org/spec/lex.html#identifiers.
Re: How to pass noncopyable variadic arguments with ref?
On Thursday, 20 October 2022 at 16:34:34 UTC, user1234 wrote: On Thursday, 20 October 2022 at 14:03:10 UTC, tchaloupka wrote: Hi, I've found strange behavior where: [...] Shouldn't it at least protest that objects can't be passed to the function as they aren't copyable? it's clearly a compiler bug to me. Something is not checked when the call is verified. however (forgot to say) this form of variadic was proposed for deprecation. So maybe the bug is more an argument to drop them.
Re: How to pass noncopyable variadic arguments with ref?
On Thursday, 20 October 2022 at 14:03:10 UTC, tchaloupka wrote: Hi, I've found strange behavior where: [...] Shouldn't it at least protest that objects can't be passed to the function as they aren't copyable? it's clearly a compiler bug to me. Something is not checked when the call is verified.
Re: Generate a pointer to a method of a struct
On Saturday, 15 October 2022 at 01:48:15 UTC, kdevel wrote: Is this consistent? I think all the compilers should error on expressions like `Type.nonStaticMethod` and instead there should be a new __traits dedicated to that, especially because `this` is not a formal parameter.
Re: How to workaround assignment not allowed in a condition?
On Wednesday, 12 October 2022 at 02:15:55 UTC, Steven Schveighoffer wrote: Porting some C code to D This results in an error: ```d int x; while(!(x = 5)) { break; } ``` Error is: assignment cannot be used as a condition, perhaps `==` was meant? ... I think D should relax the restriction and allows the AssignExp as condition they are enclosed between parentheses.
Re: Example for multi level template composition
On Monday, 10 October 2022 at 06:30:05 UTC, Arun wrote: Stumbled upon this question on HN https://news.ycombinator.com/item?id=33142751#33147401 Can I write template A and then apply it to itself to get template B and then apply that onto template C to get template D. Does anyone have an example for this? Recursive templates can make other templates with themselves. I dont feel to provide an example ATM tho.
Re: Explicit cast to @system?
On Saturday, 8 October 2022 at 23:06:13 UTC, Anonymouse wrote: I have some nested templated code that takes function pointers. In many cases I pass it functions of identical signatures, except some are `@safe` and others are `@system`. In those cases the templates end up getting instantiated twice. I don't care about the `@safe`-ness and I'd really like to just have them all treated as `@system`, with one instantiation per unique signature. To illustrate: [...] ...but there are a lot of different signatures and I need a general approach. There doesn't seem to be such a thing as `cast(@system)fp`. My current solution involves some very gnarly string mixins. I see what you mean, in the past I wanted `cast(pure)`, `cast(nothrow)`, similarly to avoid using metaprog (or maybe was that delegates) in certain case. [...] But surely there has to be a better way? No.
Re: cannot gdb LDC build binary: Segmentation fault
On Friday, 7 October 2022 at 04:40:34 UTC, mw wrote: Hi, I have a LDC (1.30.0) built binary on Ubuntu 18.04.5 LTS x86_64, the program core dumps somewhere, so I want to debug it. However under gdb, the program fails as soon as I start it: [...] Try the non-stop mode maybe : https://sourceware.org/gdb/onlinedocs/gdb/Non_002dStop-Mode.html
Re: to delete the '\0' characters
On Thursday, 22 September 2022 at 10:53:32 UTC, Salih Dincer wrote: Is there a more accurate way to delete the '\0' characters at the end of the string? I tried functions in this module: https://dlang.org/phobos/std_string.html ```d auto foo(string s) { string r; foreach(c; s) { if(c > 0) { r ~= c; } } return r; } ``` SDB@79 Two remarks: 1. The zero implicitly added to literals is not part of the string. for example s[$-1] will not give 0 unless you added it explictly to a literal 2. you code remove all the 0, not the one at the end. As it still ensure what you want to achieve, maybe try [`stripRight()`](https://dlang.org/phobos/std_string.html#.stripRight). The second overload allows to specify the characters to remove.
Re: Validate static asserts
On Friday, 9 September 2022 at 17:35:44 UTC, Dennis wrote: On Friday, 9 September 2022 at 16:41:54 UTC, Andrey Zherikov wrote: What's about new `compileOutput` trait that returns compiler output? ```d static assert(__traits(compileOutput, { }) == "message"); ``` As a compiler dev, that sounds terrifying. It would make basically every change to dmd a breaking change. Ah yes, it is so stupid that error message are part of the semantics
Re: Programs in D are huge
On Tuesday, 16 August 2022 at 08:25:18 UTC, Diego wrote: Hello everyone, I'm a Java programmer at work but i'm learning D for pleasure. I'm reading _The D Programming Language by Ali Çehreli_. I noticed that DMD creates very huge executable, for example an empty program: ``` empty.d: void main() { } ``` after a compilation with these flags `dmd -de -w empty.d` i have an executable of 869KiB It seams huge in my opinion for an empty program What are the best practices to reduce the size? This is normal, by default you have plenty of typeinfo (static data allowing dynamic introspection), code located in implicit import object.d, the runtime (e.g code for the GC). You can really get rid of that, excepted using -betterC, but you see all the stuff that make the default main program big will actually be useful in a real program. It's just that D is not as much "pay as you go" as that, for now.
Re: code review: splitIds from DConf '22 day 3: saving a sort and "getting performance"
On Thursday, 4 August 2022 at 13:18:40 UTC, kdevel wrote: At DConf '22 day 3 Robert Schadek presented at around 07:22:00 in the YT video the function `splitIds`. Given an HTML page from bugzilla containing a list of issues `splitIds` aims at extracting all bug-ids referenced within a specific url context: ``` long [] splitIds (string page) { enum re = ctRegex!(`"show_bug.cgi\?id=[0-9]+"`); auto m = page.matchAll (re); return m .filter!(it => it.length > 0) // what is this? .map!(it => it.front) // whole match, it[0] .map!(it => it.find!(isNumber)) // searches fist number .map!(it => it.until!(it => !it.isNumber ())) // last number .filter!(it => !it.empty) // again an empty check??? why? .map!(it => it.to!long ()) .uniq // .sort is missing. IMHO saving at the wrong things? .array; } ``` `m` contains all matches. It is a "list of lists" as one would say in Perl. The "inner lists" contains as first element ("`front`") the string which matches the whole pattern. So my first question is: What is the purpose of the first filter call? Since the element of `m` is a match it cannot have a length of 0. [...] I think that the first one is to prevent to call `front()` on an empty range, excepted that according to the regex that should not happen. BTW I haven't washed the video but I suppose this is related to the migration of bugzilla to GH issues. I wonder why https://bugzilla.readthedocs.io/en/5.0/api/index.html#apis is not used instead.
Re: Build for i586
On Thursday, 28 July 2022 at 06:12:49 UTC, Alexander Zhirov wrote: On Thursday, 28 July 2022 at 06:01:17 UTC, Alexander Zhirov > x86- 32-bit X86: Pentium-Pro and above I also tried with `i586` and `pentium` - the result is the same. Pentium Pro and above means at least i686. i586 is Pentium1 which is less featured. That means that you cant do much, however you can try to tune the i686 target and disable emiting of the instructions that were added from the Pentium Pro. Maybe that the produced instruction will then be compatible. that would be something like `--mcpu=i686 --mattrs=-mmx,-sse` and maybe more to be sure. Other things: "Registered Targets: ... " means that maybe the LDC developers could add the i586 target but did not consider useful to add this is old processor (e.g Pentium1). For that you should ask them if you can and how activate the target when you build ldc2 on your old Geode.
Re: Build for i586
On Thursday, 28 July 2022 at 07:16:13 UTC, user1234 wrote: On Thursday, 28 July 2022 at 06:12:49 UTC, Alexander Zhirov wrote: [...] Pentium Pro and above means at least i686. i586 is Pentium1 which is less featured. That means that you cant do much, however you can try to tune the i686 target and disable emiting of the instructions that were added from the Pentium Pro. Maybe that the produced instruction will then be compatible. that would be something like `--mcpu=i686 --mattrs=-mmx,-sse` and maybe more to be sure. Other things: "Registered Targets: ... " means that maybe the LDC developers could add the i586 target but did not consider useful to add this is old processor (e.g Pentium1). For that you should ask them if you can and how activate the target when you build ldc2 on your old Geode. ask here https://forum.dlang.org/group/ldc for better answers
Re: null == "" is true?
On Tuesday, 12 July 2022 at 19:55:46 UTC, ag0aep6g wrote: On Tuesday, 12 July 2022 at 19:02:01 UTC, user1234 wrote: On Tuesday, 12 July 2022 at 16:40:38 UTC, H. S. Teoh wrote: [...] Do not rely on this, however; Absolutely. I'd like to add: especially as default parameter value that's an array. Never use null. use `[]` (empty array literal). Just to be clear: `[]` and `null` are the exact same thing (null pointer, zero length). The reason to prefer `[]` over `null` is purely for readability. The meaning is exactly the same. ah yes. The case I thought to was actually ```d void test1(string s = null) { assert(s is null); } void test2(string s = "") // s is null term'ed, i.e not null { assert(s is null); } void main() { test1(); test2(); // fails } ``` the rule of thumb is to use `stuff.length` as condition, always, and not `stuff` itself, to prevent natyx, hard to find bugs.
Re: null == "" is true?
On Tuesday, 12 July 2022 at 16:40:38 UTC, H. S. Teoh wrote: On Tue, Jul 12, 2022 at 04:27:44PM +, Antonio via Digitalmars-d-learn wrote: It works ```d void main() { assert(null==""); } ``` why? Because an empty string is, by default, represented by an empty slice of the null pointer. Do not rely on this, however; Absolutely. I'd like to add: especially as default parameter value that's an array. Never use null. use `[]` (empty array literal).
Re: How to check if something can be null
On Friday, 1 July 2022 at 13:53:28 UTC, Antonio wrote: On Friday, 1 July 2022 at 13:48:25 UTC, Antonio wrote: -Why? I realized Json is an struct (not an object)... and I supose, it is managing null asignation manually (as a way to build Json(null)). -Whats the correct whay to test if something can be null? That's my question :-p Something like this does the job: ```d enum canBeNull(T) = is(typeof({T t; t = null;})); static assert(canBeNull!(Object)); static assert(!canBeNull!(int)); ``` and that should handle opAssign and opCmp overloads.
Re: Bug in dmd?
On Tuesday, 14 June 2022 at 13:39:12 UTC, Andrey Zherikov wrote: I have [pretty simple code in my library](https://github.com/andrey- [Line (2) produces](https://github.com/andrey-zherikov/argparse/runs/6880350900?check_suite_focus=true#step:5:12) `undefined reference to '_D3std7sumtype__T7SumTypeTS8argparse4help2AATSQtQm2BBZQBl6__dtorMFNaNbNiNfZv'` (it demangles to `pure nothrow @nogc @safe void std.sumtype.SumType!(argparse.help.AA, argparse.help.BB).SumType.__dtor()`) If I comment line (2) then everything is good (no link errors). Note that there is the same code at (1) which doesn't produce any error. Any idea what's going on? That can be a template instance that's emitted somewhere else, i.e the thing is there but the mangle is different. maybe try to find if the dtor is there with `mn -S` on each object. Another thing to try in these situations is to see if that works with `-allinst`.
Re: Generating unique identifiers at compile time
On Monday, 13 June 2022 at 07:38:54 UTC, user1234 wrote: On Thursday, 9 June 2022 at 23:50:10 UTC, user1234 wrote: On Thursday, 9 June 2022 at 21:20:27 UTC, JG wrote: [...] No, for now there if there are other ways they are as hacky as yours. The compiler usually uses a global counter to generate temporaries. There's [been attempts] to expose it, exactly so that users can generate unique names, but that did not found its path in the compiler. [been attempts]: https://github.com/dlang/dmd/pull/10131 Here's another one. That's nice if people are able to find tricks but there's a need to have a clean way to do that. i.e language feature. Damnit, forgot [the link] [the link]: https://github.com/dlang/dmd/pull/5633
Re: Generating unique identifiers at compile time
On Thursday, 9 June 2022 at 23:50:10 UTC, user1234 wrote: On Thursday, 9 June 2022 at 21:20:27 UTC, JG wrote: [...] No, for now there if there are other ways they are as hacky as yours. The compiler usually uses a global counter to generate temporaries. There's [been attempts] to expose it, exactly so that users can generate unique names, but that did not found its path in the compiler. [been attempts]: https://github.com/dlang/dmd/pull/10131 Here's another one. That's nice if people are able to find tricks but there's a need to have a clean way to do that. i.e language feature.
Re: Generating unique identifiers at compile time
On Thursday, 9 June 2022 at 21:20:27 UTC, JG wrote: Hi, As an experiment I have implemented the following kind of pattern matching (by parsing the part of the string before '='). ```d struct S { int x; int y; } struct T { int w; S s; } void main() { mixin(matchAssign(q{auto T(first,S(second,third)) = T(1,S(2,3));})); first.writeln; // 1 second.writeln; // 2 third.writeln; // 3 } ``` In doing so I wanted to produce unique identifiers (something like gensym in racket.) I did this in a very hacky way: ```d auto hopefullyUniqueName(size_t n, size_t line=__LINE__) { return format!"var___%s%s"(n,line); } ``` where I pass in the hash of the right hand side in the assignment in place of n. Is there some way to ask the compiler for a unique name or a better way of achieving this? No, for now there if there are other ways they are as hacky as yours. The compiler usually uses a global counter to generate temporaries. There's [been attempts] to expose it, exactly so that users can generate unique names, but that did not found its path in the compiler. [been attempts]: https://github.com/dlang/dmd/pull/10131
Re: Why is the compiled file size so huge?
On Friday, 27 May 2022 at 13:40:25 UTC, Alexander Zhirov wrote: I'm trying to compile a file that weighs 3 kilobytes. I'm also linking a self-written dynamic library. I don't understand why the resulting executable file is so huge? After all, all libraries are present: I'd take a look with IDA or hydra to check the details (maybe something is statically linked after all, that should be visible by inspecting the names view) but one thing to understand in a first time is that 1. even if druntime and phobos are dynamic libraries all the template instances are generated in your binary. 2. use of some module has for effect to create huge static tables. I think to all the UTF stuff and also std regex.
Re: Inferred attributes errors in template function.
On Friday, 27 May 2022 at 09:41:32 UTC, user1234 wrote: [...] on a side note that's funny how dmd manages to systematically print the less interesting message in both case. They are actually correct, I dont know why at some point I thought there was a problem. For the float one it's oviously not pure and for the int one it's not safe... OP wants better error message.
Re: Inferred attributes errors in template function.
On Friday, 27 May 2022 at 08:39:08 UTC, vit wrote: Hello, I have this problem: ```d static int i; void bar(T)(){ static if(is(T == int)) (()@system => 1)(); static if(is(T == float)) i = 42; } void foo(T)(){ bar!T(); } void main()@safe pure{ foo!long(); foo!float(); //Error: `pure` function `D main` cannot call impure function `onlineapp.foo!float.foo` foo!int(); //Error: `@safe` function `D main` cannot call `@system` function `onlineapp.foo!int.foo` } ``` [...] on a side note that's funny how dmd manages to systematically print the less interesting message in both case.
Re: Cannot check function address
On Wednesday, 25 May 2022 at 06:04:10 UTC, frame wrote: On Wednesday, 25 May 2022 at 05:56:28 UTC, Steven Schveighoffer wrote: It's a case where the compiler can't divine what you were thinking when you wrote that code ;) I see not in all cases but in mine. If the compiler sees the function isn't callable without arguments and it is inside an if-statement or `assert()` then it could at least suggest a pointer or ask: are you dumb? ;-) As suggested by others, the reduction is not correct, you have stripped too muchbecause this compiles just fine: a.d: ```d alias F = void function(int); F f; static this() { assert(!f); assert(f is null); } ``` b.d: ```d import a; static this() { assert(!f); assert(f is null); } ``` ```sh $ dmd a.d b.d -main $ echo $? $ 0 ```
Re: Odd construct idea. Splitting arguments inside a parameter list.
On Monday, 23 May 2022 at 08:53:27 UTC, user1234 wrote: On Monday, 23 May 2022 at 08:52:12 UTC, vit wrote: On Monday, 23 May 2022 at 08:34:21 UTC, Chris Katko wrote: D struct pair { float x,y; } [...] This work too: ```d myFunction(taco, p.tupleof, burrito); ``` and you can pass a std.typecons.Tuple as well, it will expand x y well actually std Tuple is a struct but that works without excplicit `.tupleof`.
Re: Odd construct idea. Splitting arguments inside a parameter list.
On Monday, 23 May 2022 at 08:52:12 UTC, vit wrote: On Monday, 23 May 2022 at 08:34:21 UTC, Chris Katko wrote: D struct pair { float x,y; } [...] This work too: ```d myFunction(taco, p.tupleof, burrito); ``` and you can pass a std.typecons.Tuple as well, it will expand x y
Re: template? mixin? template mixins? for modifying a struct setup
On Thursday, 19 May 2022 at 10:15:32 UTC, 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); ``` average is a bad way to grayscale FYI ;)
Re: String Literals
On Tuesday, 3 May 2022 at 17:21:47 UTC, JG wrote: Hi, The specification of string literals has either some errors or I don't understand what is meant by a Character. [...] Which to me means that e.g. r""" should be a WysiwygString, which the compiler thinks is not (not surprisingly). Am I misunderstanding something? The rule is not correct but the implementation in the lexer is. That's a valid issue for dlang.org
Re: generic function instance without call
On Wednesday, 27 April 2022 at 17:22:14 UTC, vit wrote: This work for types but not for attributes like `scope`, `return` and `auto ref`. Oh sorry... auto ref... I totally forgot [this old bug] [this old bug]: https://issues.dlang.org/show_bug.cgi?id=8204
Re: generic function instance without call
On Wednesday, 27 April 2022 at 15:23:26 UTC, vit wrote: Hi, is it possible to get address of generic function instance for specified arguments without calling the function? Example: ```d auto foo(alias fn, Args...)(auto ref Args args){ ///return function/delegate type of `fn` for arguments `args` } void main(){ long x; auto fn = foo!((a, b) => true)(new int(42), x); static assert(is(typeof(fn) == bool function(int*, scope ref long)@safe pure nothrow @nogc )); } ``` yeah sure; declare an alias that (fully) specialize the generic func and take the address using the alias Identifier.
Re: A template construct like using()
On Tuesday, 26 April 2022 at 21:33:43 UTC, Chris Katko wrote: 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? assuming `set_target_bitmap` returns the previous target : ```d struct Bitmap { } struct PushPopBitmap { Bitmap* bitmap; Bitmap* old; alias bitmap this; this(Bitmap* bmp) { old = set_target_bitmap(bitmap = bmp); } ~this() { set_target_bitmap(old); } } Bitmap* set_target_bitmap(Bitmap* bmp); void draw_pixel(); void main() { Bitmap* bmp; with (PushPopBitmap(bmp)) draw_pixel(); } ``` At the end of the WithStatement block that restores the previous context.
Re: Create a wrapper around larger c-libraries
On Sunday, 24 April 2022 at 15:13:15 UTC, Alain De Vos wrote: I'm currenlty experimenting about binding to C. I have : C-library: mylib.h: ``` void libprintme(char *s); ``` mylib.c: ``` #include #include "mylib.h" void libprintme(char *s){printf("%s",s);} ``` [...] Can this procedure be used for larger C-libraries ? What is good , what is bad , what can be better. Feel free to elaborate ? (It's the C-preprocessor with macro expansion which gives me sometimes a bit of a headache.) Why not just ```d extern(C) @nogc nothrow { void libprintme(char *s); alias cprintme = libprintme; } ``` ? The function pointer looks totally superfluous to me.
Re: Static struct initialization syntax behavior & it being disabled upon adding a constructor
On Monday, 18 April 2022 at 10:26:16 UTC, HuskyNator wrote: On a sidenote, I'm surprised D did not choose 0 as the default floating value. Doesn't almost every language do this? I understand the thinking behind it, but when the type one uses in a template influences the behavior of the code, that seems like a pretty big red flag to me. (Any non-floating type defaults to 0, but using floats/doubles suddenly introduces NaN, surely I'm not the only one that sees a problem with this 😅) Especially when it's basically a standard 0 is used for this. Sorry for the rant. Let me explain the why: D default initialization is not designed to replace user-defined initialization, it's rather made to make bugs related to non-initialized variables stable, e.g not UB. The easiest way to get that is to think to references and pointers. A random garbage value pointed by an alloca may work to some point (e.g access to member), if it's set to `null` right after the alloca then you have a stable segfault that always happens at the same time and is easy to debug. Similarly, for floating point numbers the D designers considered that `NaN` was the best choice because FP operations will not wrongly appear valid when starting operations with NaN. With integral types, this system does not work as well, as `0` doesn't create bugs as easily as `null` and `NaN`. The confusion about the real role of default initialization comes from integral types I believe.
Re: How to use Vector Extensions in an opBinary
On Sunday, 17 April 2022 at 11:16:25 UTC, HuskyNator wrote: I recently found out there is [support for vector extensions](https://dlang.org/spec/simd.html) But I have found I don't really understand how to use it, not even mentioning the more complex stuff. I couldn't find any good examples either. I'm trying to figure out how to implement the following opBinary using vector extensions. ```dlang alias MatType = typeof(this); union{ T[rows*columns] vec; T[rows][columns] mat; } MatType opBinary(string op, T)(const T right) const { MatType result = this; mixin("result.vec[] = this.vec[] " ~ op ~ " right;"); return result; } ``` Or alternatively, as I'm not sure which is more efficient/faster: ```dlang MatType opBinary(string op, T)(const T right) const { MatType result; static foreach(i; 0..rows*columns) mixin("result.vec[i] = this.vec[i] " ~ op ~ " right;"); return result; } ``` But going off the documentation, I have no idea how to use vector extensions to achieve something like this. As a small disclaimer; I don't know to what extent the compiler already automates these kind of operations, and mostly want to use this as a learning experience. Kind regards, HN I'd experiment with CompilerExplorer. For example [this](https://godbolt.org/z/a51r8GEv4) shows that the codegen is identical for both opBinary version for "+". About time spent to compile, `static foreach` is known not to scale well.
Re: Lambdas Scope
On Monday, 11 April 2022 at 09:11:06 UTC, Salih Dincer wrote: How is this possible? Why is it compiled? Don't the same names in the same scope conflict? ```d int function(int) square; void main() { square = (int a) => a * a; int square = 5.square; assert(square == 25); } ``` Thanks, SDB@79 you can use explicit call parenthesis to make the difference between the local var and the global func. Also you have the module access operator and the fully qualified name as alternatives to select the one you wish to.
Re: Why do immutable variables need reference counting?
On Sunday, 10 April 2022 at 23:05:24 UTC, norm wrote: Hi All, I am clearly misunderstanding something fundamental, and probably obvious :D Reading some of the discussions on __metadata I was wondering if someone could explain why a immutable reference counting type is needed. By definition a reference counter cannot be immutable, so what would be the use case that requires it? It cannot really be pure nor safe either because the ref goes out of scope and the allocation is freed. How is this immutable? Thanks, Norm refcounting would require a concept of "tail const" / "tail immutable" so that transitivity of the qualifier does not affect the data used to refcount (basically the field that hold the count) but only the data that **are** refcounted.
Re: Where I download Digital Mars C Preprocessor sppn.exe?
On Saturday, 2 April 2022 at 21:57:02 UTC, Marcone wrote: Where I download Digital Mars C Preprocessor sppn.exe? I need it to use ImportC it's part of the [DMC] toolchain. [DMC]: http://ftp.digitalmars.com/Digital_Mars_C++/Patch/dm857c.zip
Re: Nested Classes with inheritance
On Saturday, 19 March 2022 at 05:25:01 UTC, Era Scarecrow wrote: On Saturday, 19 March 2022 at 00:16:48 UTC, user1234 wrote: That crashes because of the creation of `Bar b` member, which itself has a Bar b member, which itself... Mhmm... So There's Foo with Bar b, which has Bar b which has Bar b which... just keeps going over and over again. It appears to me that it only crashes when you fully run out of memory then. Much like a function calling itself and you exhaust all your stack space. I'd suggest avoiding self-inheritance. No one wants to be their own Grandpa I think OP is learning OOP. His error looks like that for the least.
Re: Nested Classes with inheritance
On Saturday, 19 March 2022 at 00:05:54 UTC, Salih Dincer wrote: Greetings to all... There are nested classes as below. But beware, there's also inheritance, extra! If you construct ```Bar b``` from main(), it's okay. But if declare the constructor in Foo(), the program crashes with a segmentation error. Is this not legal? Like two mirrors are facing each other, that I do? ```d class Foo { Bar b; int i; this(int n) { this.i = n; //this.b = new Bar(this.i); // compiles but crashes } class Bar : Foo { int i; this(int n) { this.i = n; super(this.i); } } } void main() { auto foo = new Foo(1); auto bar = foo.new Bar(1); foo.b = bar; assert(foo.i == foo.b.i); } ``` SDB@79 That crashes because of the creation of `Bar b` member, which itself has a Bar b member, which itself... One solution is to create the member depending on some condition, example: ```d if (typeid(this) !is typeid(Bar)) this.b = new Bar(this.i); ```
Re: static init c struct with array filed
On Wednesday, 16 March 2022 at 14:42:02 UTC, Era Scarecrow wrote: On Wednesday, 16 March 2022 at 11:27:20 UTC, user1234 wrote: assuming the c library takes by reference My experience all arrays are effectively just pointers I meant the function that takes the Test2 as parameter, but to be honest I dont get exactly what does OP want actually... that's true that passing a Test2 is somewhat strange as there's no info for the array length.
Re: static init c struct with array filed
On Wednesday, 16 March 2022 at 07:27:06 UTC, test wrote: ```c struct Test { int32_t a; } struct Test2 { int32_t a; Test arr[]; } ``` I need static const init Test2, then pass it to c library late(third library, can not change the type def). I am not sure how to do it in D. ```d extern(C) struct Test { int a; } extern(C) struct Test2 { int a; Test* arr; } static const Test2 t2 = Test2(2, null); void main(){ to_c_library(&t2); to_c_library(new Test2(2, null)); Test2 local; to_c_library(&local); } ``` assuming the c library takes by reference
Re: initializing struct containing user defined type
On Friday, 18 February 2022 at 23:46:51 UTC, forkit wrote: On Friday, 18 February 2022 at 16:45:24 UTC, Ali Çehreli wrote: ... I think that syntax will be obviated when D will have named arguments. Ali Huh? D doesn't have named arguments, already? That's an important component for safe(r) programming. Do you know if there is a DIP for this, and if so, it's current status. The DIP is [accepted] but not implemented. [accepted]: https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1030.md
Re: Filling an array at compile time
On Wednesday, 9 February 2022 at 10:25:34 UTC, bauss wrote: Is it guaranteed that the value is initialized at compiletime however? yes, D guarentees this at 100%.
Re: how to handle very large array?
On Wednesday, 9 February 2022 at 10:29:03 UTC, ag0aep6g wrote: Try to think of a more efficient way of storing the information. I cant agree more. The problem of OP is not dynamic arrays, it's that he uses an inadequate data structure.
Re: template ctor overload Segmentation fault
On Sunday, 12 December 2021 at 11:57:43 UTC, vit wrote: Hello, why does this code fail to compile? ```d struct Foo(T){ this(Rhs, this This)(scope Rhs rhs){ } this(ref scope typeof(this) rhs){ } } struct Bar{ Foo!int foo; } void main(){ } ``` error: Segmentation fault (core dumped) Firstly, report the crash with the keyword "ice". Then, there might be something not allowed (in some situations the compiler cant decide which ctor to use) but you cant see it for now.
Re: Debugging D code with GDB
On Sunday, 28 November 2021 at 16:44:38 UTC, russhy wrote: On Sunday, 28 November 2021 at 14:53:17 UTC, user1234 wrote: ... there is a plugin to demangle things automatically https://github.com/ANtlord/gdb-ddemangle That's off-topic. The point here is that you can (unfortunately) **only** evaluate the call using the mangled form, it's not about transforming the output. Actually what would be useful is a plugin the mangle the call in custom expression before passing it to gdb ;)
Re: Debugging D code with GDB
On Saturday, 27 November 2021 at 14:17:11 UTC, Eduard Staniloiu wrote: Hello, I'm trying to use `gdb` to debug D binaries, but I'm having trouble accessing the methods of a struct or class. It seems that `gdb` doesn't see them. [...] Looking forward to your answers, Edi [0] - https://sourceware.org/bugzilla/show_bug.cgi?id=22480 Hello, while I never evaluate calls during debugging I've managed to find a way : you can call the mangled name so for ```d #!dmd -g module a; import std.stdio; struct S { int myPrint(){return 8;} } pragma(msg, S.myPrint.mangleof); int main(string[] args) { S s; return 0; } ``` in gdb CLI ```bash p (int) _D1a1S7myPrintMFZi(s) $1 = 8 ``` works. Note that for some reasons writefln causes a crash, that's why I've modified the example. The problem is that my workaround does not scale better than your.
Re: New developments on topic of memset, memcpy and similar
On Saturday, 27 November 2021 at 11:15:45 UTC, Igor wrote: Two years ago there was a [Google Summer of Code project](https://forum.dlang.org/thread/izaufklyvmktnwsrm...@forum.dlang.org) to implement these primitives in pure D for various reason. It was concluded the project isn't viable and was abandoned, but there were some interesting learnings. I now stumbled on some new work in C land about these that might be interesting to people that were following the original project so I am sharing it here: Custom ASM implementation that outperforms libc: https://github.com/nadavrot/memset_benchmark Paper on automatic implementation of these primitives: https://dl.acm.org/doi/pdf/10.1145/3459898.3463904 Also LLVM has intrinsics or special instructions for those libc stuff. I suppose that there are special optimz that are tried and if not possible that falls back to the libc version.