CTFE Evaluation with JSON Objects
Petar
Petar
Thu Jan 23 00:20:24 UTC 2020
On Wednesday, 22 January 2020 at 10:17:43 UTC, rbscott wrote:
> Hello,
>
> [snip]
>
> Any thoughts or ideas?
>
> thanks!
> rbscott
Hi,
I hope this helps:
```D
import std.json;
void main()
{
// 1) Use `enum` instead of `const` to
// guarantee that the value will be
// computed at compile-time.
// 2) Don't use `new` for enum values
// as we currently don't have a robust
// mechanism to materialize heap-allocated values.
enum jsonNumber = JSONValue(1);
pragma(msg, jsonNumber.integer);
// Q: Why does this work?
// A: Although reinterpretation through unions
// is (mostly?) forbidden during CTFE, you can
// still read union members that have been
// written to before.
const jsonObject = parseJSON(`{ "my key" : "some value",
"integer": 42 }`);
pragma(msg, jsonObject["my key"].str);
// Q: Why does this fail?
// A: Because of a slightly obscure implementation
// detail of std.json:
//
https://github.com/dlang/phobos/blob/45b2b0d1ad67ee041cf67e4e10c9e225b75acb18/std/json.d#L1275-L1281
// Basically, if the value read is a non-negative
// integer, the `uinteger` union member is set,
// however if the value is <= 2^^63,
// then the `JSONType.integer` type is set,
// which prevents reading through the uinteger() JSONValue
property.
// This can be worked around by directly accessing
// the `store` private field using `.tupleof[0]`:
pragma(msg, jsonObject["integer"].tupleof[0].uinteger);
}
```
Cheers,
Petar
More information about the Digitalmars-d
mailing list