idetools_api.nim 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import unicode, sequtils, macros, re
  2. proc test_enums() =
  3. var o: Tfile
  4. if o.open("files " & "test.txt", fmWrite):
  5. o.write("test")
  6. o.close()
  7. proc test_iterators(filename = "tests.nim") =
  8. let
  9. input = readFile(filename)
  10. letters = toSeq(runes(string(input)))
  11. for letter in letters: echo int(letter)
  12. const SOME_SEQUENCE = @[1, 2]
  13. type
  14. bad_string = distinct string
  15. TPerson = object of TObject
  16. name*: bad_string
  17. age: int
  18. proc adder(a, b: int): int =
  19. result = a + b
  20. type
  21. PExpr = ref object of TObject ## abstract base class for an expression
  22. PLiteral = ref object of PExpr
  23. x: int
  24. PPlusExpr = ref object of PExpr
  25. a, b: PExpr
  26. # watch out: 'eval' relies on dynamic binding
  27. method eval(e: PExpr): int =
  28. # override this base method
  29. quit "to override!"
  30. method eval(e: PLiteral): int = e.x
  31. method eval(e: PPlusExpr): int = eval(e.a) + eval(e.b)
  32. proc newLit(x: int): PLiteral = PLiteral(x: x)
  33. proc newPlus(a, b: PExpr): PPlusExpr = PPlusExpr(a: a, b: b)
  34. echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))
  35. proc findVowelPosition(text: string) =
  36. var found = -1
  37. block loops:
  38. for i, letter in pairs(text):
  39. for j in ['a', 'e', 'i', 'o', 'u']:
  40. if letter == j:
  41. found = i
  42. break loops # leave both for-loops
  43. echo found
  44. findVowelPosition("Zerg") # should output 1, position of vowel.
  45. macro expect*(exceptions: varargs[expr], body: stmt): stmt {.immediate.} =
  46. ## Expect docstrings
  47. let exp = callsite()
  48. template expectBody(errorTypes, lineInfoLit: expr,
  49. body: stmt): NimNode {.dirty.} =
  50. try:
  51. body
  52. assert false
  53. except errorTypes:
  54. nil
  55. var body = exp[exp.len - 1]
  56. var errorTypes = newNimNode(nnkBracket)
  57. for i in countup(1, exp.len - 2):
  58. errorTypes.add(exp[i])
  59. result = getAst(expectBody(errorTypes, exp.lineinfo, body))
  60. proc err =
  61. raise newException(EArithmetic, "some exception")
  62. proc testMacro() =
  63. expect(EArithmetic):
  64. err()
  65. testMacro()
  66. let notAModule = re"(\w+)=(.*)"