rodfiles.nim 7.7 KB

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