idgen.nim 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains a simple persistent id generator.
  10. import idents, strutils, os, options, pathutils
  11. var gFrontEndId*: int
  12. const
  13. debugIds* = false
  14. when debugIds:
  15. import intsets
  16. var usedIds = initIntSet()
  17. proc registerID*(id: PIdObj) =
  18. when debugIds:
  19. if id.id == -1 or containsOrIncl(usedIds, id.id):
  20. internalError("ID already used: " & $id.id)
  21. proc getID*(): int {.inline.} =
  22. result = gFrontEndId
  23. inc(gFrontEndId)
  24. proc setId*(id: int) {.inline.} =
  25. gFrontEndId = max(gFrontEndId, id + 1)
  26. proc idSynchronizationPoint*(idRange: int) =
  27. gFrontEndId = (gFrontEndId div idRange + 1) * idRange + 1
  28. proc toGid(conf: ConfigRef; f: AbsoluteFile): string =
  29. # we used to use ``f.addFileExt("gid")`` (aka ``$project.gid``), but this
  30. # will cause strange bugs if multiple projects are in the same folder, so
  31. # we simply use a project independent name:
  32. result = options.completeGeneratedFilePath(conf, AbsoluteFile"nim.gid").string
  33. proc saveMaxIds*(conf: ConfigRef; project: AbsoluteFile) =
  34. var f = open(toGid(conf, project), fmWrite)
  35. f.writeLine($gFrontEndId)
  36. f.close()
  37. proc loadMaxIds*(conf: ConfigRef; project: AbsoluteFile) =
  38. var f: File
  39. if open(f, toGid(conf, project), fmRead):
  40. var line = newStringOfCap(20)
  41. if f.readLine(line):
  42. var frontEndId = parseInt(line)
  43. if f.readLine(line):
  44. # var backEndId = parseInt(line)
  45. gFrontEndId = max(gFrontEndId, frontEndId)
  46. f.close()