rodfiles.nim 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2020 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Low level binary format used by the compiler to store and load various AST
  10. ## and related data.
  11. ##
  12. ## NB: this is incredibly low level and if you're interested in how the
  13. ## compiler works and less a storage format, you're probably looking for
  14. ## the `ic` or `packed_ast` modules to understand the logical format.
  15. from typetraits import supportsCopyMem
  16. when defined(nimPreviewSlimSystem):
  17. import std/[syncio, assertions]
  18. ## Overview
  19. ## ========
  20. ## `RodFile` represents a Rod File (versioned binary format), and the
  21. ## associated data for common interactions such as IO and error tracking
  22. ## (`RodFileError`). The file format broken up into sections (`RodSection`)
  23. ## and preceded by a header (see: `cookie`). The precise layout, section
  24. ## ordering and data following the section are determined by the user. See
  25. ## `ic.loadRodFile`.
  26. ##
  27. ## A basic but "wrong" example of the lifecycle:
  28. ## ---------------------------------------------
  29. ## 1. `create` or `open` - create a new one or open an existing
  30. ## 2. `storeHeader` - header info
  31. ## 3. `storePrim` or `storeSeq` - save your stuff
  32. ## 4. `close` - and we're done
  33. ##
  34. ## Now read the bits below to understand what's missing.
  35. ##
  36. ## ### Issues with the Example
  37. ## Missing Sections:
  38. ## This is a low level API, so headers and sections need to be stored and
  39. ## loaded by the user, see `storeHeader` & `loadHeader` and `storeSection` &
  40. ## `loadSection`, respectively.
  41. ##
  42. ## No Error Handling:
  43. ## The API is centered around IO and prone to error, each operation checks or
  44. ## sets the `RodFile.err` field. A user of this API needs to handle these
  45. ## appropriately.
  46. ##
  47. ## API Notes
  48. ## =========
  49. ##
  50. ## Valid inputs for Rod files
  51. ## --------------------------
  52. ## ASTs, hopes, dreams, and anything as long as it and any children it may have
  53. ## support `copyMem`. This means anything that is not a pointer and that does not contain a pointer. At a glance these are:
  54. ## * string
  55. ## * objects & tuples (fields are recursed)
  56. ## * sequences AKA `seq[T]`
  57. ##
  58. ## Note on error handling style
  59. ## ----------------------------
  60. ## A flag based approach is used where operations no-op in case of a
  61. ## preexisting error and set the flag if they encounter one.
  62. ##
  63. ## Misc
  64. ## ----
  65. ## * 'Prim' is short for 'primitive', as in a non-sequence type
  66. type
  67. RodSection* = enum
  68. versionSection
  69. configSection
  70. stringsSection
  71. checkSumsSection
  72. depsSection
  73. numbersSection
  74. exportsSection
  75. hiddenSection
  76. reexportsSection
  77. compilerProcsSection
  78. trmacrosSection
  79. convertersSection
  80. methodsSection
  81. pureEnumsSection
  82. toReplaySection
  83. topLevelSection
  84. bodiesSection
  85. symsSection
  86. typesSection
  87. typeInstCacheSection
  88. procInstCacheSection
  89. attachedOpsSection
  90. methodsPerTypeSection
  91. enumToStringProcsSection
  92. typeInfoSection # required by the backend
  93. backendFlagsSection
  94. aliveSymsSection # beware, this is stored in a `.alivesyms` file.
  95. RodFileError* = enum
  96. ok, tooBig, cannotOpen, ioFailure, wrongHeader, wrongSection, configMismatch,
  97. includeFileChanged
  98. RodFile* = object
  99. f*: File
  100. currentSection*: RodSection # for error checking
  101. err*: RodFileError # little experiment to see if this works
  102. # better than exceptions.
  103. const
  104. RodVersion = 1
  105. cookie = [byte(0), byte('R'), byte('O'), byte('D'),
  106. byte(sizeof(int)*8), byte(system.cpuEndian), byte(0), byte(RodVersion)]
  107. proc setError(f: var RodFile; err: RodFileError) {.inline.} =
  108. f.err = err
  109. #raise newException(IOError, "IO error")
  110. proc storePrim*(f: var RodFile; s: string) =
  111. ## Stores a string.
  112. ## The len is prefixed to allow for later retreival.
  113. if f.err != ok: return
  114. if s.len >= high(int32):
  115. setError f, tooBig
  116. return
  117. var lenPrefix = int32(s.len)
  118. if writeBuffer(f.f, addr lenPrefix, sizeof(lenPrefix)) != sizeof(lenPrefix):
  119. setError f, ioFailure
  120. else:
  121. if s.len != 0:
  122. if writeBuffer(f.f, unsafeAddr(s[0]), s.len) != s.len:
  123. setError f, ioFailure
  124. proc storePrim*[T](f: var RodFile; x: T) =
  125. ## Stores a non-sequence/string `T`.
  126. ## If `T` doesn't support `copyMem` and is an object or tuple then the fields
  127. ## are written -- the user from context will need to know which `T` to load.
  128. if f.err != ok: return
  129. when supportsCopyMem(T):
  130. if writeBuffer(f.f, unsafeAddr(x), sizeof(x)) != sizeof(x):
  131. setError f, ioFailure
  132. elif T is tuple:
  133. for y in fields(x):
  134. storePrim(f, y)
  135. elif T is object:
  136. for y in fields(x):
  137. when y is seq:
  138. storeSeq(f, y)
  139. else:
  140. storePrim(f, y)
  141. else:
  142. {.error: "unsupported type for 'storePrim'".}
  143. proc storeSeq*[T](f: var RodFile; s: seq[T]) =
  144. ## Stores a sequence of `T`s, with the len as a prefix for later retrieval.
  145. if f.err != ok: return
  146. if s.len >= high(int32):
  147. setError f, tooBig
  148. return
  149. var lenPrefix = int32(s.len)
  150. if writeBuffer(f.f, addr lenPrefix, sizeof(lenPrefix)) != sizeof(lenPrefix):
  151. setError f, ioFailure
  152. else:
  153. for i in 0..<s.len:
  154. storePrim(f, s[i])
  155. proc loadPrim*(f: var RodFile; s: var string) =
  156. ## Read a string, the length was stored as a prefix
  157. if f.err != ok: return
  158. var lenPrefix = int32(0)
  159. if readBuffer(f.f, addr lenPrefix, sizeof(lenPrefix)) != sizeof(lenPrefix):
  160. setError f, ioFailure
  161. else:
  162. s = newString(lenPrefix)
  163. if lenPrefix > 0:
  164. if readBuffer(f.f, unsafeAddr(s[0]), s.len) != s.len:
  165. setError f, ioFailure
  166. proc loadPrim*[T](f: var RodFile; x: var T) =
  167. ## Load a non-sequence/string `T`.
  168. if f.err != ok: return
  169. when supportsCopyMem(T):
  170. if readBuffer(f.f, unsafeAddr(x), sizeof(x)) != sizeof(x):
  171. setError f, ioFailure
  172. elif T is tuple:
  173. for y in fields(x):
  174. loadPrim(f, y)
  175. elif T is object:
  176. for y in fields(x):
  177. when y is seq:
  178. loadSeq(f, y)
  179. else:
  180. loadPrim(f, y)
  181. else:
  182. {.error: "unsupported type for 'loadPrim'".}
  183. proc loadSeq*[T](f: var RodFile; s: var seq[T]) =
  184. ## `T` must be compatible with `copyMem`, see `loadPrim`
  185. if f.err != ok: return
  186. var lenPrefix = int32(0)
  187. if readBuffer(f.f, addr lenPrefix, sizeof(lenPrefix)) != sizeof(lenPrefix):
  188. setError f, ioFailure
  189. else:
  190. s = newSeq[T](lenPrefix)
  191. for i in 0..<lenPrefix:
  192. loadPrim(f, s[i])
  193. proc storeHeader*(f: var RodFile) =
  194. ## stores the header which is described by `cookie`.
  195. if f.err != ok: return
  196. if f.f.writeBytes(cookie, 0, cookie.len) != cookie.len:
  197. setError f, ioFailure
  198. proc loadHeader*(f: var RodFile) =
  199. ## Loads the header which is described by `cookie`.
  200. if f.err != ok: return
  201. var thisCookie: array[cookie.len, byte]
  202. if f.f.readBytes(thisCookie, 0, thisCookie.len) != thisCookie.len:
  203. setError f, ioFailure
  204. elif thisCookie != cookie:
  205. setError f, wrongHeader
  206. proc storeSection*(f: var RodFile; s: RodSection) =
  207. ## update `currentSection` and writes the bytes value of s.
  208. if f.err != ok: return
  209. assert f.currentSection < s
  210. f.currentSection = s
  211. storePrim(f, s)
  212. proc loadSection*(f: var RodFile; expected: RodSection) =
  213. ## read the bytes value of s, sets and error if the section is incorrect.
  214. if f.err != ok: return
  215. var s: RodSection
  216. loadPrim(f, s)
  217. if expected != s and f.err == ok:
  218. setError f, wrongSection
  219. proc create*(filename: string): RodFile =
  220. ## create the file and open it for writing
  221. if not open(result.f, filename, fmWrite):
  222. setError result, cannotOpen
  223. proc close*(f: var RodFile) = close(f.f)
  224. proc open*(filename: string): RodFile =
  225. ## open the file for reading
  226. if not open(result.f, filename, fmRead):
  227. setError result, cannotOpen