vmmarshal.nim 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Implements marshaling for the VM.
  10. import streams, json, intsets, tables, ast, astalgo, idents, types, msgs,
  11. options, lineinfos
  12. proc ptrToInt(x: PNode): int {.inline.} =
  13. result = cast[int](x) # don't skip alignment
  14. proc getField(n: PNode; position: int): PSym =
  15. case n.kind
  16. of nkRecList:
  17. for i in 0..<n.len:
  18. result = getField(n[i], position)
  19. if result != nil: return
  20. of nkRecCase:
  21. result = getField(n[0], position)
  22. if result != nil: return
  23. for i in 1..<n.len:
  24. case n[i].kind
  25. of nkOfBranch, nkElse:
  26. result = getField(lastSon(n[i]), position)
  27. if result != nil: return
  28. else: discard
  29. of nkSym:
  30. if n.sym.position == position: result = n.sym
  31. else: discard
  32. proc storeAny(s: var string; t: PType; a: PNode; stored: var IntSet; conf: ConfigRef)
  33. proc storeObj(s: var string; typ: PType; x: PNode; stored: var IntSet; conf: ConfigRef) =
  34. assert x.kind == nkObjConstr
  35. let start = 1
  36. for i in start..<x.len:
  37. if i > start: s.add(", ")
  38. var it = x[i]
  39. if it.kind == nkExprColonExpr:
  40. if it[0].kind == nkSym:
  41. let field = it[0].sym
  42. s.add(escapeJson(field.name.s))
  43. s.add(": ")
  44. storeAny(s, field.typ, it[1], stored, conf)
  45. elif typ.n != nil:
  46. let field = getField(typ.n, i)
  47. s.add(escapeJson(field.name.s))
  48. s.add(": ")
  49. storeAny(s, field.typ, it, stored, conf)
  50. proc storeAny(s: var string; t: PType; a: PNode; stored: var IntSet;
  51. conf: ConfigRef) =
  52. case t.kind
  53. of tyNone: assert false
  54. of tyBool: s.add($(a.intVal != 0))
  55. of tyChar:
  56. let ch = char(a.intVal)
  57. if ch < '\128':
  58. s.add(escapeJson($ch))
  59. else:
  60. s.add($int(ch))
  61. of tyArray, tySequence:
  62. if t.kind == tySequence and a.kind == nkNilLit: s.add("null")
  63. else:
  64. s.add("[")
  65. for i in 0..<a.len:
  66. if i > 0: s.add(", ")
  67. storeAny(s, t.elemType, a[i], stored, conf)
  68. s.add("]")
  69. of tyTuple:
  70. s.add("{")
  71. for i in 0..<t.len:
  72. if i > 0: s.add(", ")
  73. s.add("\"Field" & $i)
  74. s.add("\": ")
  75. storeAny(s, t[i], a[i].skipColon, stored, conf)
  76. s.add("}")
  77. of tyObject:
  78. s.add("{")
  79. storeObj(s, t, a, stored, conf)
  80. s.add("}")
  81. of tySet:
  82. s.add("[")
  83. for i in 0..<a.len:
  84. if i > 0: s.add(", ")
  85. if a[i].kind == nkRange:
  86. var x = copyNode(a[i][0])
  87. storeAny(s, t.lastSon, x, stored, conf)
  88. while x.intVal+1 <= a[i][1].intVal:
  89. s.add(", ")
  90. storeAny(s, t.lastSon, x, stored, conf)
  91. inc x.intVal
  92. else:
  93. storeAny(s, t.lastSon, a[i], stored, conf)
  94. s.add("]")
  95. of tyRange, tyGenericInst, tyAlias, tySink:
  96. storeAny(s, t.lastSon, a, stored, conf)
  97. of tyEnum:
  98. # we need a slow linear search because of enums with holes:
  99. for e in items(t.n):
  100. if e.sym.position == a.intVal:
  101. s.add e.sym.name.s.escapeJson
  102. break
  103. of tyPtr, tyRef:
  104. var x = a
  105. if isNil(x) or x.kind == nkNilLit: s.add("null")
  106. elif stored.containsOrIncl(x.ptrToInt):
  107. # already stored, so we simply write out the pointer as an int:
  108. s.add($x.ptrToInt)
  109. else:
  110. # else as a [value, key] pair:
  111. # (reversed order for convenient x[0] access!)
  112. s.add("[")
  113. s.add($x.ptrToInt)
  114. s.add(", ")
  115. storeAny(s, t.lastSon, a, stored, conf)
  116. s.add("]")
  117. of tyString, tyCString:
  118. if a.kind == nkNilLit: s.add("null")
  119. else: s.add(escapeJson(a.strVal))
  120. of tyInt..tyInt64, tyUInt..tyUInt64: s.add($a.intVal)
  121. of tyFloat..tyFloat128: s.add($a.floatVal)
  122. else:
  123. internalError conf, a.info, "cannot marshal at compile-time " & t.typeToString
  124. proc storeAny*(s: var string; t: PType; a: PNode; conf: ConfigRef) =
  125. var stored = initIntSet()
  126. storeAny(s, t, a, stored, conf)
  127. proc loadAny(p: var JsonParser, t: PType,
  128. tab: var Table[BiggestInt, PNode];
  129. cache: IdentCache;
  130. conf: ConfigRef): PNode =
  131. case t.kind
  132. of tyNone: assert false
  133. of tyBool:
  134. case p.kind
  135. of jsonFalse: result = newIntNode(nkIntLit, 0)
  136. of jsonTrue: result = newIntNode(nkIntLit, 1)
  137. else: raiseParseErr(p, "'true' or 'false' expected for a bool")
  138. next(p)
  139. of tyChar:
  140. if p.kind == jsonString:
  141. var x = p.str
  142. if x.len == 1:
  143. result = newIntNode(nkIntLit, ord(x[0]))
  144. next(p)
  145. return
  146. elif p.kind == jsonInt:
  147. result = newIntNode(nkIntLit, getInt(p))
  148. next(p)
  149. return
  150. raiseParseErr(p, "string of length 1 expected for a char")
  151. of tyEnum:
  152. if p.kind == jsonString:
  153. for e in items(t.n):
  154. if e.sym.name.s == p.str:
  155. result = newIntNode(nkIntLit, e.sym.position)
  156. next(p)
  157. return
  158. raiseParseErr(p, "string expected for an enum")
  159. of tyArray:
  160. if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for an array")
  161. next(p)
  162. result = newNode(nkBracket)
  163. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  164. result.add loadAny(p, t.elemType, tab, cache, conf)
  165. if p.kind == jsonArrayEnd: next(p)
  166. else: raiseParseErr(p, "']' end of array expected")
  167. of tySequence:
  168. case p.kind
  169. of jsonNull:
  170. result = newNode(nkNilLit)
  171. next(p)
  172. of jsonArrayStart:
  173. next(p)
  174. result = newNode(nkBracket)
  175. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  176. result.add loadAny(p, t.elemType, tab, cache, conf)
  177. if p.kind == jsonArrayEnd: next(p)
  178. else: raiseParseErr(p, "")
  179. else:
  180. raiseParseErr(p, "'[' expected for a seq")
  181. of tyTuple:
  182. if p.kind != jsonObjectStart: raiseParseErr(p, "'{' expected for an object")
  183. next(p)
  184. result = newNode(nkTupleConstr)
  185. var i = 0
  186. while p.kind != jsonObjectEnd and p.kind != jsonEof:
  187. if p.kind != jsonString:
  188. raiseParseErr(p, "string expected for a field name")
  189. next(p)
  190. if i >= t.len:
  191. raiseParseErr(p, "too many fields to tuple type " & typeToString(t))
  192. result.add loadAny(p, t[i], tab, cache, conf)
  193. inc i
  194. if p.kind == jsonObjectEnd: next(p)
  195. else: raiseParseErr(p, "'}' end of object expected")
  196. of tyObject:
  197. if p.kind != jsonObjectStart: raiseParseErr(p, "'{' expected for an object")
  198. next(p)
  199. result = newNode(nkObjConstr)
  200. result.sons = @[newNode(nkEmpty)]
  201. while p.kind != jsonObjectEnd and p.kind != jsonEof:
  202. if p.kind != jsonString:
  203. raiseParseErr(p, "string expected for a field name")
  204. let ident = getIdent(cache, p.str)
  205. let field = lookupInRecord(t.n, ident)
  206. if field.isNil:
  207. raiseParseErr(p, "unknown field for object of type " & typeToString(t))
  208. next(p)
  209. let pos = field.position + 1
  210. if pos >= result.len:
  211. setLen(result.sons, pos + 1)
  212. let fieldNode = newNode(nkExprColonExpr)
  213. fieldNode.add newSymNode(newSym(skField, ident, nil, unknownLineInfo))
  214. fieldNode.add loadAny(p, field.typ, tab, cache, conf)
  215. result[pos] = fieldNode
  216. if p.kind == jsonObjectEnd: next(p)
  217. else: raiseParseErr(p, "'}' end of object expected")
  218. of tySet:
  219. if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for a set")
  220. next(p)
  221. result = newNode(nkCurly)
  222. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  223. result.add loadAny(p, t.lastSon, tab, cache, conf)
  224. next(p)
  225. if p.kind == jsonArrayEnd: next(p)
  226. else: raiseParseErr(p, "']' end of array expected")
  227. of tyPtr, tyRef:
  228. case p.kind
  229. of jsonNull:
  230. result = newNode(nkNilLit)
  231. next(p)
  232. of jsonInt:
  233. result = tab.getOrDefault(p.getInt)
  234. if result.isNil:
  235. raiseParseErr(p, "cannot load object with address " & $p.getInt)
  236. next(p)
  237. of jsonArrayStart:
  238. next(p)
  239. if p.kind == jsonInt:
  240. let idx = p.getInt
  241. next(p)
  242. result = loadAny(p, t.lastSon, tab, cache, conf)
  243. tab[idx] = result
  244. else: raiseParseErr(p, "index for ref type expected")
  245. if p.kind == jsonArrayEnd: next(p)
  246. else: raiseParseErr(p, "']' end of ref-address pair expected")
  247. else: raiseParseErr(p, "int for pointer type expected")
  248. of tyString, tyCString:
  249. case p.kind
  250. of jsonNull:
  251. result = newNode(nkNilLit)
  252. next(p)
  253. of jsonString:
  254. result = newStrNode(nkStrLit, p.str)
  255. next(p)
  256. else: raiseParseErr(p, "string expected")
  257. of tyInt..tyInt64, tyUInt..tyUInt64:
  258. if p.kind == jsonInt:
  259. result = newIntNode(nkIntLit, getInt(p))
  260. next(p)
  261. return
  262. raiseParseErr(p, "int expected")
  263. of tyFloat..tyFloat128:
  264. if p.kind == jsonFloat:
  265. result = newFloatNode(nkFloatLit, getFloat(p))
  266. next(p)
  267. return
  268. raiseParseErr(p, "float expected")
  269. of tyRange, tyGenericInst, tyAlias, tySink:
  270. result = loadAny(p, t.lastSon, tab, cache, conf)
  271. else:
  272. internalError conf, "cannot marshal at compile-time " & t.typeToString
  273. proc loadAny*(s: string; t: PType; cache: IdentCache; conf: ConfigRef): PNode =
  274. var tab = initTable[BiggestInt, PNode]()
  275. var p: JsonParser
  276. open(p, newStringStream(s), "unknown file")
  277. next(p)
  278. result = loadAny(p, t, tab, cache, conf)
  279. close(p)