twithin_macro.nim 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from system import string, int, seq, `&`, `$`, `*`, `@`, echo, add, items, RootObj
  2. import fixtures/mclass_macro
  3. class Animal of RootObj:
  4. var name: string
  5. var age: int
  6. method vocalize: string {.base.} = "..." # use `base` pragma to annonate base methods
  7. method age_human_yrs: int {.base.} = self.age # `this` is injected
  8. proc `$`: string = "animal:" & self.name & ":" & $self.age
  9. class Dog of Animal:
  10. method vocalize: string = "woof"
  11. method age_human_yrs: int = self.age * 7
  12. proc `$`: string = "dog:" & self.name & ":" & $self.age
  13. class Cat of Animal:
  14. method vocalize: string = "meow"
  15. proc `$`: string = "cat:" & self.name & ":" & $self.age
  16. class Rabbit of Animal:
  17. proc newRabbit(name: string, age: int) = # the constructor doesn't need a return type
  18. result = Rabbit(name: name, age: age)
  19. method vocalize: string = "meep"
  20. proc `$`: string =
  21. self.#[!]#
  22. result = "rabbit:" & self.name & ":" & $self.age
  23. # ---
  24. var animals: seq[Animal] = @[]
  25. animals.add(Dog(name: "Sparky", age: 10))
  26. animals.add(Cat(name: "Mitten", age: 10))
  27. for a in animals:
  28. echo a.vocalize()
  29. echo a.age_human_yrs()
  30. let r = newRabbit("Fluffy", 3)
  31. echo r.vocalize()
  32. echo r.age_human_yrs()
  33. echo r
  34. discard """
  35. $nimsuggest --tester --maxresults:5 $file
  36. >sug $1
  37. sug;;skField;;age;;int;;$file;;6;;6;;"";;100;;None
  38. sug;;skField;;name;;string;;$file;;5;;6;;"";;100;;None
  39. sug;;skMethod;;twithin_macro.age_human_yrs;;proc (self: Animal): int{.raises: <inferred> [].};;$file;;8;;9;;"";;100;;None
  40. sug;;skMethod;;twithin_macro.vocalize;;proc (self: Animal): string{.raises: <inferred> [].};;$file;;7;;9;;"";;100;;None
  41. sug;;skMethod;;twithin_macro.vocalize;;proc (self: Rabbit): string;;$file;;23;;9;;"";;100;;None
  42. """