special_ops.txt 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. Special Operators
  2. =================
  3. dot operators
  4. -------------
  5. **Note**: Dot operators are still experimental and so need to be enabled
  6. via ``{.experimental.}``.
  7. Nim offers a special family of dot operators that can be used to
  8. intercept and rewrite proc call and field access attempts, referring
  9. to previously undeclared symbol names. They can be used to provide a
  10. fluent interface to objects lying outside the static confines of the
  11. type system such as values from dynamic scripting languages
  12. or dynamic file formats such as JSON or XML.
  13. When Nim encounters an expression that cannot be resolved by the
  14. standard overload resolution rules, the current scope will be searched
  15. for a dot operator that can be matched against a re-written form of
  16. the expression, where the unknown field or proc name is converted to
  17. an additional static string parameter:
  18. .. code-block:: nim
  19. a.b # becomes `.`(a, "b")
  20. a.b(c, d) # becomes `.`(a, "b", c, d)
  21. The matched dot operators can be symbols of any callable kind (procs,
  22. templates and macros), depending on the desired effect:
  23. .. code-block:: nim
  24. proc `.` (js: PJsonNode, field: string): JSON = js[field]
  25. var js = parseJson("{ x: 1, y: 2}")
  26. echo js.x # outputs 1
  27. echo js.y # outputs 2
  28. The following dot operators are available:
  29. operator `.`
  30. ------------
  31. This operator will be matched against both field accesses and method calls.
  32. operator `.()`
  33. ---------------
  34. This operator will be matched exclusively against method calls. It has higher
  35. precedence than the `.` operator and this allows one to handle expressions like
  36. `x.y` and `x.y()` differently if one is interfacing with a scripting language
  37. for example.
  38. operator `.=`
  39. -------------
  40. This operator will be matched against assignments to missing fields.
  41. .. code-block:: nim
  42. a.b = c # becomes `.=`(a, "b", c)