cgmeth.nim 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements code generation for methods.
  10. import
  11. intsets, options, ast, msgs, idents, renderer, types, magicsys,
  12. sempass2, modulegraphs, lineinfos
  13. when defined(nimPreviewSlimSystem):
  14. import std/assertions
  15. proc genConv(n: PNode, d: PType, downcast: bool; conf: ConfigRef): PNode =
  16. var dest = skipTypes(d, abstractPtrs)
  17. var source = skipTypes(n.typ, abstractPtrs)
  18. if (source.kind == tyObject) and (dest.kind == tyObject):
  19. var diff = inheritanceDiff(dest, source)
  20. if diff == high(int):
  21. # no subtype relation, nothing to do
  22. result = n
  23. elif diff < 0:
  24. result = newNodeIT(nkObjUpConv, n.info, d)
  25. result.add n
  26. if downcast: internalError(conf, n.info, "cgmeth.genConv: no upcast allowed")
  27. elif diff > 0:
  28. result = newNodeIT(nkObjDownConv, n.info, d)
  29. result.add n
  30. if not downcast:
  31. internalError(conf, n.info, "cgmeth.genConv: no downcast allowed")
  32. else:
  33. result = n
  34. else:
  35. result = n
  36. proc getDispatcher*(s: PSym): PSym =
  37. ## can return nil if is has no dispatcher.
  38. if dispatcherPos < s.ast.len:
  39. result = s.ast[dispatcherPos].sym
  40. doAssert sfDispatcher in result.flags
  41. proc methodCall*(n: PNode; conf: ConfigRef): PNode =
  42. result = n
  43. # replace ordinary method by dispatcher method:
  44. let disp = getDispatcher(result[0].sym)
  45. if disp != nil:
  46. result[0].typ = disp.typ
  47. result[0].sym = disp
  48. # change the arguments to up/downcasts to fit the dispatcher's parameters:
  49. for i in 1..<result.len:
  50. result[i] = genConv(result[i], disp.typ[i], true, conf)
  51. else:
  52. localError(conf, n.info, "'" & $result[0] & "' lacks a dispatcher")
  53. type
  54. MethodResult = enum No, Invalid, Yes
  55. proc sameMethodBucket(a, b: PSym; multiMethods: bool): MethodResult =
  56. if a.name.id != b.name.id: return
  57. if a.typ.len != b.typ.len:
  58. return
  59. for i in 1..<a.typ.len:
  60. var aa = a.typ[i]
  61. var bb = b.typ[i]
  62. while true:
  63. aa = skipTypes(aa, {tyGenericInst, tyAlias})
  64. bb = skipTypes(bb, {tyGenericInst, tyAlias})
  65. if aa.kind == bb.kind and aa.kind in {tyVar, tyPtr, tyRef, tyLent, tySink}:
  66. aa = aa.lastSon
  67. bb = bb.lastSon
  68. else:
  69. break
  70. if sameType(a.typ[i], b.typ[i]):
  71. if aa.kind == tyObject and result != Invalid:
  72. result = Yes
  73. elif aa.kind == tyObject and bb.kind == tyObject and (i == 1 or multiMethods):
  74. let diff = inheritanceDiff(bb, aa)
  75. if diff < 0:
  76. if result != Invalid:
  77. result = Yes
  78. else:
  79. return No
  80. elif diff != high(int) and sfFromGeneric notin (a.flags+b.flags):
  81. result = Invalid
  82. else:
  83. return No
  84. else:
  85. return No
  86. if result == Yes:
  87. # check for return type:
  88. if not sameTypeOrNil(a.typ[0], b.typ[0]):
  89. if b.typ[0] != nil and b.typ[0].kind == tyUntyped:
  90. # infer 'auto' from the base to make it consistent:
  91. b.typ[0] = a.typ[0]
  92. else:
  93. return No
  94. proc attachDispatcher(s: PSym, dispatcher: PNode) =
  95. if dispatcherPos < s.ast.len:
  96. # we've added a dispatcher already, so overwrite it
  97. s.ast[dispatcherPos] = dispatcher
  98. else:
  99. setLen(s.ast.sons, dispatcherPos+1)
  100. if s.ast[resultPos] == nil:
  101. s.ast[resultPos] = newNodeI(nkEmpty, s.info)
  102. s.ast[dispatcherPos] = dispatcher
  103. proc createDispatcher(s: PSym; g: ModuleGraph; idgen: IdGenerator): PSym =
  104. var disp = copySym(s, nextSymId(idgen))
  105. incl(disp.flags, sfDispatcher)
  106. excl(disp.flags, sfExported)
  107. let old = disp.typ
  108. disp.typ = copyType(disp.typ, nextTypeId(idgen), disp.typ.owner)
  109. copyTypeProps(g, idgen.module, disp.typ, old)
  110. # we can't inline the dispatcher itself (for now):
  111. if disp.typ.callConv == ccInline: disp.typ.callConv = ccNimCall
  112. disp.ast = copyTree(s.ast)
  113. disp.ast[bodyPos] = newNodeI(nkEmpty, s.info)
  114. disp.loc.r = ""
  115. if s.typ[0] != nil:
  116. if disp.ast.len > resultPos:
  117. disp.ast[resultPos].sym = copySym(s.ast[resultPos].sym, nextSymId(idgen))
  118. else:
  119. # We've encountered a method prototype without a filled-in
  120. # resultPos slot. We put a placeholder in there that will
  121. # be updated in fixupDispatcher().
  122. disp.ast.add newNodeI(nkEmpty, s.info)
  123. attachDispatcher(s, newSymNode(disp))
  124. # attach to itself to prevent bugs:
  125. attachDispatcher(disp, newSymNode(disp))
  126. return disp
  127. proc fixupDispatcher(meth, disp: PSym; conf: ConfigRef) =
  128. # We may have constructed the dispatcher from a method prototype
  129. # and need to augment the incomplete dispatcher with information
  130. # from later definitions, particularly the resultPos slot. Also,
  131. # the lock level of the dispatcher needs to be updated/checked
  132. # against that of the method.
  133. if disp.ast.len > resultPos and meth.ast.len > resultPos and
  134. disp.ast[resultPos].kind == nkEmpty:
  135. disp.ast[resultPos] = copyTree(meth.ast[resultPos])
  136. proc methodDef*(g: ModuleGraph; idgen: IdGenerator; s: PSym) =
  137. var witness: PSym
  138. for i in 0..<g.methods.len:
  139. let disp = g.methods[i].dispatcher
  140. case sameMethodBucket(disp, s, multimethods = optMultiMethods in g.config.globalOptions)
  141. of Yes:
  142. g.methods[i].methods.add(s)
  143. attachDispatcher(s, disp.ast[dispatcherPos])
  144. fixupDispatcher(s, disp, g.config)
  145. #echo "fixup ", disp.name.s, " ", disp.id
  146. when useEffectSystem: checkMethodEffects(g, disp, s)
  147. if {sfBase, sfFromGeneric} * s.flags == {sfBase} and
  148. g.methods[i].methods[0] != s:
  149. # already exists due to forwarding definition?
  150. localError(g.config, s.info, "method is not a base")
  151. return
  152. of No: discard
  153. of Invalid:
  154. if witness.isNil: witness = g.methods[i].methods[0]
  155. # create a new dispatcher:
  156. g.methods.add((methods: @[s], dispatcher: createDispatcher(s, g, idgen)))
  157. #echo "adding ", s.info
  158. if witness != nil:
  159. localError(g.config, s.info, "invalid declaration order; cannot attach '" & s.name.s &
  160. "' to method defined here: " & g.config$witness.info)
  161. elif sfBase notin s.flags:
  162. message(g.config, s.info, warnUseBase)
  163. proc relevantCol(methods: seq[PSym], col: int): bool =
  164. # returns true iff the position is relevant
  165. var t = methods[0].typ[col].skipTypes(skipPtrs)
  166. if t.kind == tyObject:
  167. for i in 1..high(methods):
  168. let t2 = skipTypes(methods[i].typ[col], skipPtrs)
  169. if not sameType(t2, t):
  170. return true
  171. proc cmpSignatures(a, b: PSym, relevantCols: IntSet): int =
  172. for col in 1..<a.typ.len:
  173. if contains(relevantCols, col):
  174. var aa = skipTypes(a.typ[col], skipPtrs)
  175. var bb = skipTypes(b.typ[col], skipPtrs)
  176. var d = inheritanceDiff(aa, bb)
  177. if (d != high(int)) and d != 0:
  178. return d
  179. proc sortBucket(a: var seq[PSym], relevantCols: IntSet) =
  180. # we use shellsort here; fast and simple
  181. var n = a.len
  182. var h = 1
  183. while true:
  184. h = 3 * h + 1
  185. if h > n: break
  186. while true:
  187. h = h div 3
  188. for i in h..<n:
  189. var v = a[i]
  190. var j = i
  191. while cmpSignatures(a[j - h], v, relevantCols) >= 0:
  192. a[j] = a[j - h]
  193. j = j - h
  194. if j < h: break
  195. a[j] = v
  196. if h == 1: break
  197. proc genDispatcher(g: ModuleGraph; methods: seq[PSym], relevantCols: IntSet; idgen: IdGenerator): PSym =
  198. var base = methods[0].ast[dispatcherPos].sym
  199. result = base
  200. var paramLen = base.typ.len
  201. var nilchecks = newNodeI(nkStmtList, base.info)
  202. var disp = newNodeI(nkIfStmt, base.info)
  203. var ands = getSysMagic(g, unknownLineInfo, "and", mAnd)
  204. var iss = getSysMagic(g, unknownLineInfo, "of", mOf)
  205. let boolType = getSysType(g, unknownLineInfo, tyBool)
  206. for col in 1..<paramLen:
  207. if contains(relevantCols, col):
  208. let param = base.typ.n[col].sym
  209. if param.typ.skipTypes(abstractInst).kind in {tyRef, tyPtr}:
  210. nilchecks.add newTree(nkCall,
  211. newSymNode(getCompilerProc(g, "chckNilDisp")), newSymNode(param))
  212. for meth in 0..high(methods):
  213. var curr = methods[meth] # generate condition:
  214. var cond: PNode = nil
  215. for col in 1..<paramLen:
  216. if contains(relevantCols, col):
  217. var isn = newNodeIT(nkCall, base.info, boolType)
  218. isn.add newSymNode(iss)
  219. let param = base.typ.n[col].sym
  220. isn.add newSymNode(param)
  221. isn.add newNodeIT(nkType, base.info, curr.typ[col])
  222. if cond != nil:
  223. var a = newNodeIT(nkCall, base.info, boolType)
  224. a.add newSymNode(ands)
  225. a.add cond
  226. a.add isn
  227. cond = a
  228. else:
  229. cond = isn
  230. let retTyp = base.typ[0]
  231. let call = newNodeIT(nkCall, base.info, retTyp)
  232. call.add newSymNode(curr)
  233. for col in 1..<paramLen:
  234. call.add genConv(newSymNode(base.typ.n[col].sym),
  235. curr.typ[col], false, g.config)
  236. var ret: PNode
  237. if retTyp != nil:
  238. var a = newNodeI(nkFastAsgn, base.info)
  239. a.add newSymNode(base.ast[resultPos].sym)
  240. a.add call
  241. ret = newNodeI(nkReturnStmt, base.info)
  242. ret.add a
  243. else:
  244. ret = call
  245. if cond != nil:
  246. var a = newNodeI(nkElifBranch, base.info)
  247. a.add cond
  248. a.add ret
  249. disp.add a
  250. else:
  251. disp = ret
  252. nilchecks.add disp
  253. nilchecks.flags.incl nfTransf # should not be further transformed
  254. result.ast[bodyPos] = nilchecks
  255. proc generateMethodDispatchers*(g: ModuleGraph, idgen: IdGenerator): PNode =
  256. result = newNode(nkStmtList)
  257. for bucket in 0..<g.methods.len:
  258. var relevantCols = initIntSet()
  259. for col in 1..<g.methods[bucket].methods[0].typ.len:
  260. if relevantCol(g.methods[bucket].methods, col): incl(relevantCols, col)
  261. if optMultiMethods notin g.config.globalOptions:
  262. # if multi-methods are not enabled, we are interested only in the first field
  263. break
  264. sortBucket(g.methods[bucket].methods, relevantCols)
  265. result.add newSymNode(genDispatcher(g, g.methods[bucket].methods, relevantCols, idgen))