rodfiles.nim 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 std/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. sideChannelSection
  96. namespaceSection
  97. symnamesSection
  98. RodFileError* = enum
  99. ok, tooBig, cannotOpen, ioFailure, wrongHeader, wrongSection, configMismatch,
  100. includeFileChanged
  101. RodFile* = object
  102. f*: File
  103. currentSection*: RodSection # for error checking
  104. err*: RodFileError # little experiment to see if this works
  105. # better than exceptions.
  106. const
  107. RodVersion = 2
  108. defaultCookie = [byte(0), byte('R'), byte('O'), byte('D'),
  109. byte(sizeof(int)*8), byte(system.cpuEndian), byte(0), byte(RodVersion)]
  110. proc setError(f: var RodFile; err: RodFileError) {.inline.} =
  111. f.err = err
  112. #raise newException(IOError, "IO error")
  113. proc storePrim*(f: var RodFile; s: string) =
  114. ## Stores a string.
  115. ## The len is prefixed to allow for later retreival.
  116. if f.err != ok: return
  117. if s.len >= high(int32):
  118. setError f, tooBig
  119. return
  120. var lenPrefix = int32(s.len)
  121. if writeBuffer(f.f, addr lenPrefix, sizeof(lenPrefix)) != sizeof(lenPrefix):
  122. setError f, ioFailure
  123. else:
  124. if s.len != 0:
  125. if writeBuffer(f.f, unsafeAddr(s[0]), s.len) != s.len:
  126. setError f, ioFailure
  127. proc storePrim*[T](f: var RodFile; x: T) =
  128. ## Stores a non-sequence/string `T`.
  129. ## If `T` doesn't support `copyMem` and is an object or tuple then the fields
  130. ## are written -- the user from context will need to know which `T` to load.
  131. if f.err != ok: return
  132. when supportsCopyMem(T):
  133. if writeBuffer(f.f, unsafeAddr(x), sizeof(x)) != sizeof(x):
  134. setError f, ioFailure
  135. elif T is tuple:
  136. for y in fields(x):
  137. storePrim(f, y)
  138. elif T is object:
  139. for y in fields(x):
  140. when y is seq:
  141. storeSeq(f, y)
  142. else:
  143. storePrim(f, y)
  144. else:
  145. {.error: "unsupported type for 'storePrim'".}
  146. proc storeSeq*[T](f: var RodFile; s: seq[T]) =
  147. ## Stores a sequence of `T`s, with the len as a prefix for later retrieval.
  148. if f.err != ok: return
  149. if s.len >= high(int32):
  150. setError f, tooBig
  151. return
  152. var lenPrefix = int32(s.len)
  153. if writeBuffer(f.f, addr lenPrefix, sizeof(lenPrefix)) != sizeof(lenPrefix):
  154. setError f, ioFailure
  155. else:
  156. for i in 0..<s.len:
  157. storePrim(f, s[i])
  158. proc loadPrim*(f: var RodFile; s: var string) =
  159. ## Read a string, the length was stored as a prefix
  160. if f.err != ok: return
  161. var lenPrefix = int32(0)
  162. if readBuffer(f.f, addr lenPrefix, sizeof(lenPrefix)) != sizeof(lenPrefix):
  163. setError f, ioFailure
  164. else:
  165. s = newString(lenPrefix)
  166. if lenPrefix > 0:
  167. if readBuffer(f.f, unsafeAddr(s[0]), s.len) != s.len:
  168. setError f, ioFailure
  169. proc loadPrim*[T](f: var RodFile; x: var T) =
  170. ## Load a non-sequence/string `T`.
  171. if f.err != ok: return
  172. when supportsCopyMem(T):
  173. if readBuffer(f.f, unsafeAddr(x), sizeof(x)) != sizeof(x):
  174. setError f, ioFailure
  175. elif T is tuple:
  176. for y in fields(x):
  177. loadPrim(f, y)
  178. elif T is object:
  179. for y in fields(x):
  180. when y is seq:
  181. loadSeq(f, y)
  182. else:
  183. loadPrim(f, y)
  184. else:
  185. {.error: "unsupported type for 'loadPrim'".}
  186. proc loadSeq*[T](f: var RodFile; s: var seq[T]) =
  187. ## `T` must be compatible with `copyMem`, see `loadPrim`
  188. if f.err != ok: return
  189. var lenPrefix = int32(0)
  190. if readBuffer(f.f, addr lenPrefix, sizeof(lenPrefix)) != sizeof(lenPrefix):
  191. setError f, ioFailure
  192. else:
  193. s = newSeq[T](lenPrefix)
  194. for i in 0..<lenPrefix:
  195. loadPrim(f, s[i])
  196. proc storeHeader*(f: var RodFile; cookie = defaultCookie) =
  197. ## stores the header which is described by `cookie`.
  198. if f.err != ok: return
  199. if f.f.writeBytes(cookie, 0, cookie.len) != cookie.len:
  200. setError f, ioFailure
  201. proc loadHeader*(f: var RodFile; cookie = defaultCookie) =
  202. ## Loads the header which is described by `cookie`.
  203. if f.err != ok: return
  204. var thisCookie: array[cookie.len, byte] = default(array[cookie.len, byte])
  205. if f.f.readBytes(thisCookie, 0, thisCookie.len) != thisCookie.len:
  206. setError f, ioFailure
  207. elif thisCookie != cookie:
  208. setError f, wrongHeader
  209. proc storeSection*(f: var RodFile; s: RodSection) =
  210. ## update `currentSection` and writes the bytes value of s.
  211. if f.err != ok: return
  212. assert f.currentSection < s
  213. f.currentSection = s
  214. storePrim(f, s)
  215. proc loadSection*(f: var RodFile; expected: RodSection) =
  216. ## read the bytes value of s, sets and error if the section is incorrect.
  217. if f.err != ok: return
  218. var s: RodSection = default(RodSection)
  219. loadPrim(f, s)
  220. if expected != s and f.err == ok:
  221. setError f, wrongSection
  222. proc create*(filename: string): RodFile =
  223. ## create the file and open it for writing
  224. result = default(RodFile)
  225. if not open(result.f, filename, fmWrite):
  226. setError result, cannotOpen
  227. proc close*(f: var RodFile) = close(f.f)
  228. proc open*(filename: string): RodFile =
  229. ## open the file for reading
  230. result = default(RodFile)
  231. if not open(result.f, filename, fmRead):
  232. setError result, cannotOpen