cgmeth.nim 11 KB

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