cgmeth.nim 9.9 KB

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