tdotlikeoperators.nim 859 B

12345678910111213141516171819202122232425262728293031
  1. discard """
  2. matrix: "-d:nimPreviewDotLikeOps"
  3. """
  4. # test for https://github.com/nim-lang/RFCs/issues/341
  5. import std/json
  6. import std/jsonutils
  7. import std/macros
  8. macro fn1(a: untyped): string = newLit a.lispRepr
  9. doAssert fn1(a.?b.c) == """(DotExpr (Infix (Ident ".?") (Ident "a") (Ident "b")) (Ident "c"))"""
  10. template `.?`(a: JsonNode, b: untyped{ident}): JsonNode =
  11. a[astToStr(b)]
  12. proc identity[T](a: T): T = a
  13. proc timesTwo[T](a: T): T = a * 2
  14. template main =
  15. let a = (a1: 1, a2: "abc", a3: (a4: 2.5))
  16. let j = a.toJson
  17. doAssert j.?a1.getInt == 1
  18. doAssert j.?a3.?a4.getFloat == 2.5
  19. doAssert j.?a3.?a4.getFloat.timesTwo == 5.0
  20. doAssert j.?a3.identity.?a4.getFloat.timesTwo == 5.0
  21. doAssert j.identity.?a3.identity.?a4.identity.getFloat.timesTwo == 5.0
  22. doAssert j.identity.?a3.?a4.identity.getFloat.timesTwo == 5.0
  23. static: main()
  24. main()