cgmeth.nim 10 KB

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