vmmarshal.nim 9.3 KB

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