twithin_macro_prefix.nim 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from system import string, int, seq, `&`, `$`, `*`, `@`, echo, add, 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.ag#[!]#
  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 $file
  36. >sug $1
  37. sug;;skField;;age;;int;;$file;;6;;6;;"";;100;;Prefix
  38. sug;;skMethod;;twithin_macro_prefix.age_human_yrs;;proc (self: Animal): int;;$file;;8;;9;;"";;100;;Prefix
  39. """