vmmarshal.nim 9.2 KB

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