util.nim 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. ## INTERNAL FILE FOR USE ONLY BY nre.nim.
  2. import tables
  3. const Ident = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'}
  4. const StartIdent = Ident - {'0'..'9'}
  5. template formatStr*(howExpr, namegetter, idgetter): untyped =
  6. let how = howExpr
  7. var val = newStringOfCap(how.len)
  8. var i = 0
  9. var lastNum = 1
  10. while i < how.len:
  11. if how[i] != '$':
  12. val.add(how[i])
  13. i += 1
  14. else:
  15. if how[i + 1] == '$':
  16. val.add('$')
  17. i += 2
  18. elif how[i + 1] == '#':
  19. var id {.inject.} = lastNum
  20. val.add(idgetter)
  21. lastNum += 1
  22. i += 2
  23. elif how[i + 1] in {'0'..'9'}:
  24. i += 1
  25. var id {.inject.} = 0
  26. while i < how.len and how[i] in {'0'..'9'}:
  27. id += (id * 10) + (ord(how[i]) - ord('0'))
  28. i += 1
  29. val.add(idgetter)
  30. lastNum = id + 1
  31. elif how[i + 1] in StartIdent:
  32. i += 1
  33. var name {.inject.} = ""
  34. while i < how.len and how[i] in Ident:
  35. name.add(how[i])
  36. i += 1
  37. val.add(namegetter)
  38. elif how[i + 1] == '{':
  39. i += 2
  40. var name {.inject.} = ""
  41. while i < how.len and how[i] != '}':
  42. name.add(how[i])
  43. i += 1
  44. i += 1
  45. val.add(namegetter)
  46. else:
  47. raise newException(ValueError, "Syntax error in format string at " & $i)
  48. val