concepts.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2020 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## New styled concepts for Nim. See https://github.com/nim-lang/RFCs/issues/168
  10. ## for details. Note this is a first implementation and only the "Concept matching"
  11. ## section has been implemented.
  12. import ast, astalgo, semdata, lookups, lineinfos, idents, msgs, renderer, types, intsets
  13. from magicsys import addSonSkipIntLit
  14. when defined(nimPreviewSlimSystem):
  15. import std/assertions
  16. const
  17. logBindings = false
  18. ## Code dealing with Concept declarations
  19. ## --------------------------------------
  20. proc declareSelf(c: PContext; info: TLineInfo) =
  21. ## Adds the magical 'Self' symbols to the current scope.
  22. let ow = getCurrOwner(c)
  23. let s = newSym(skType, getIdent(c.cache, "Self"), nextSymId(c.idgen), ow, info)
  24. s.typ = newType(tyTypeDesc, nextTypeId(c.idgen), ow)
  25. s.typ.flags.incl {tfUnresolved, tfPacked}
  26. s.typ.add newType(tyEmpty, nextTypeId(c.idgen), ow)
  27. addDecl(c, s, info)
  28. proc isSelf*(t: PType): bool {.inline.} =
  29. ## Is this the magical 'Self' type?
  30. t.kind == tyTypeDesc and tfPacked in t.flags
  31. proc makeTypeDesc*(c: PContext, typ: PType): PType =
  32. if typ.kind == tyTypeDesc and not isSelf(typ):
  33. result = typ
  34. else:
  35. result = newTypeS(tyTypeDesc, c)
  36. incl result.flags, tfCheckedForDestructor
  37. result.addSonSkipIntLit(typ, c.idgen)
  38. proc semConceptDecl(c: PContext; n: PNode): PNode =
  39. ## Recursive helper for semantic checking for the concept declaration.
  40. ## Currently we only support (possibly empty) lists of statements
  41. ## containing 'proc' declarations and the like.
  42. case n.kind
  43. of nkStmtList, nkStmtListExpr:
  44. result = shallowCopy(n)
  45. for i in 0..<n.len:
  46. result[i] = semConceptDecl(c, n[i])
  47. of nkProcDef..nkIteratorDef, nkFuncDef:
  48. result = c.semExpr(c, n, {efWantStmt})
  49. of nkTypeClassTy:
  50. result = shallowCopy(n)
  51. for i in 0..<n.len-1:
  52. result[i] = n[i]
  53. result[^1] = semConceptDecl(c, n[^1])
  54. of nkCommentStmt:
  55. discard
  56. else:
  57. localError(c.config, n.info, "unexpected construct in the new-styled concept: " & renderTree(n))
  58. result = n
  59. proc semConceptDeclaration*(c: PContext; n: PNode): PNode =
  60. ## Semantic checking for the concept declaration. Runs
  61. ## when we process the concept itself, not its matching process.
  62. assert n.kind == nkTypeClassTy
  63. inc c.inConceptDecl
  64. openScope(c)
  65. declareSelf(c, n.info)
  66. result = semConceptDecl(c, n)
  67. rawCloseScope(c)
  68. dec c.inConceptDecl
  69. ## Concept matching
  70. ## ----------------
  71. type
  72. MatchCon = object ## Context we pass around during concept matching.
  73. inferred: seq[(PType, PType)] ## we need a seq here so that we can easily undo inferences \
  74. ## that turned out to be wrong.
  75. marker: IntSet ## Some protection against wild runaway recursions.
  76. potentialImplementation: PType ## the concrete type that might match the concept we try to match.
  77. magic: TMagic ## mArrGet and mArrPut is wrong in system.nim and
  78. ## cannot be fixed that easily.
  79. ## Thus we special case it here.
  80. proc existingBinding(m: MatchCon; key: PType): PType =
  81. ## checks if we bound the type variable 'key' already to some
  82. ## concrete type.
  83. for i in 0..<m.inferred.len:
  84. if m.inferred[i][0] == key: return m.inferred[i][1]
  85. return nil
  86. proc conceptMatchNode(c: PContext; n: PNode; m: var MatchCon): bool
  87. proc matchType(c: PContext; f, a: PType; m: var MatchCon): bool =
  88. ## The heart of the concept matching process. 'f' is the formal parameter of some
  89. ## routine inside the concept that we're looking for. 'a' is the formal parameter
  90. ## of a routine that might match.
  91. const
  92. ignorableForArgType = {tyVar, tySink, tyLent, tyOwned, tyGenericInst, tyAlias, tyInferred}
  93. case f.kind
  94. of tyAlias:
  95. result = matchType(c, f.lastSon, a, m)
  96. of tyTypeDesc:
  97. if isSelf(f):
  98. #let oldLen = m.inferred.len
  99. result = matchType(c, a, m.potentialImplementation, m)
  100. #echo "self is? ", result, " ", a.kind, " ", a, " ", m.potentialImplementation, " ", m.potentialImplementation.kind
  101. #m.inferred.setLen oldLen
  102. #echo "A for ", result, " to ", typeToString(a), " to ", typeToString(m.potentialImplementation)
  103. else:
  104. if a.kind == tyTypeDesc and f.len == a.len:
  105. for i in 0..<a.len:
  106. if not matchType(c, f[i], a[i], m): return false
  107. return true
  108. of tyGenericInvocation:
  109. if a.kind == tyGenericInst and a[0].kind == tyGenericBody:
  110. if sameType(f[0], a[0]) and f.len == a.len-1:
  111. for i in 1 ..< f.len:
  112. if not matchType(c, f[i], a[i], m): return false
  113. return true
  114. of tyGenericParam:
  115. let ak = a.skipTypes({tyVar, tySink, tyLent, tyOwned})
  116. if ak.kind in {tyTypeDesc, tyStatic} and not isSelf(ak):
  117. result = false
  118. else:
  119. let old = existingBinding(m, f)
  120. if old == nil:
  121. if f.len > 0 and f[0].kind != tyNone:
  122. # also check the generic's constraints:
  123. let oldLen = m.inferred.len
  124. result = matchType(c, f[0], a, m)
  125. m.inferred.setLen oldLen
  126. if result:
  127. when logBindings: echo "A adding ", f, " ", ak
  128. m.inferred.add((f, ak))
  129. elif m.magic == mArrGet and ak.kind in {tyArray, tyOpenArray, tySequence, tyVarargs, tyCstring, tyString}:
  130. when logBindings: echo "B adding ", f, " ", lastSon ak
  131. m.inferred.add((f, lastSon ak))
  132. result = true
  133. else:
  134. when logBindings: echo "C adding ", f, " ", ak
  135. m.inferred.add((f, ak))
  136. #echo "binding ", typeToString(ak), " to ", typeToString(f)
  137. result = true
  138. elif not m.marker.containsOrIncl(old.id):
  139. result = matchType(c, old, ak, m)
  140. if m.magic == mArrPut and ak.kind == tyGenericParam:
  141. result = true
  142. #echo "B for ", result, " to ", typeToString(a), " to ", typeToString(m.potentialImplementation)
  143. of tyVar, tySink, tyLent, tyOwned:
  144. # modifiers in the concept must be there in the actual implementation
  145. # too but not vice versa.
  146. if a.kind == f.kind:
  147. result = matchType(c, f.sons[0], a.sons[0], m)
  148. elif m.magic == mArrPut:
  149. result = matchType(c, f.sons[0], a, m)
  150. else:
  151. result = false
  152. of tyEnum, tyObject, tyDistinct:
  153. result = sameType(f, a)
  154. of tyEmpty, tyString, tyCstring, tyPointer, tyNil, tyUntyped, tyTyped, tyVoid:
  155. result = a.skipTypes(ignorableForArgType).kind == f.kind
  156. of tyBool, tyChar, tyInt..tyUInt64:
  157. let ak = a.skipTypes(ignorableForArgType)
  158. result = ak.kind == f.kind or ak.kind == tyOrdinal or
  159. (ak.kind == tyGenericParam and ak.len > 0 and ak[0].kind == tyOrdinal)
  160. of tyConcept:
  161. let oldLen = m.inferred.len
  162. let oldPotentialImplementation = m.potentialImplementation
  163. m.potentialImplementation = a
  164. result = conceptMatchNode(c, f.n.lastSon, m)
  165. m.potentialImplementation = oldPotentialImplementation
  166. if not result:
  167. m.inferred.setLen oldLen
  168. of tyArray, tyTuple, tyVarargs, tyOpenArray, tyRange, tySequence, tyRef, tyPtr,
  169. tyGenericInst:
  170. let ak = a.skipTypes(ignorableForArgType - {f.kind})
  171. if ak.kind == f.kind and f.len == ak.len:
  172. for i in 0..<ak.len:
  173. if not matchType(c, f[i], ak[i], m): return false
  174. return true
  175. of tyOr:
  176. let oldLen = m.inferred.len
  177. if a.kind == tyOr:
  178. # say the concept requires 'int|float|string' if the potentialImplementation
  179. # says 'int|string' that is good enough.
  180. var covered = 0
  181. for i in 0..<f.len:
  182. for j in 0..<a.len:
  183. let oldLenB = m.inferred.len
  184. let r = matchType(c, f[i], a[j], m)
  185. if r:
  186. inc covered
  187. break
  188. m.inferred.setLen oldLenB
  189. result = covered >= a.len
  190. if not result:
  191. m.inferred.setLen oldLen
  192. else:
  193. for i in 0..<f.len:
  194. result = matchType(c, f[i], a, m)
  195. if result: break # and remember the binding!
  196. m.inferred.setLen oldLen
  197. of tyNot:
  198. if a.kind == tyNot:
  199. result = matchType(c, f[0], a[0], m)
  200. else:
  201. let oldLen = m.inferred.len
  202. result = not matchType(c, f[0], a, m)
  203. m.inferred.setLen oldLen
  204. of tyAnything:
  205. result = true
  206. of tyOrdinal:
  207. result = isOrdinalType(a, allowEnumWithHoles = false) or a.kind == tyGenericParam
  208. else:
  209. result = false
  210. proc matchReturnType(c: PContext; f, a: PType; m: var MatchCon): bool =
  211. ## Like 'matchType' but with extra logic dealing with proc return types
  212. ## which can be nil or the 'void' type.
  213. if f.isEmptyType:
  214. result = a.isEmptyType
  215. elif a == nil:
  216. result = false
  217. else:
  218. result = matchType(c, f, a, m)
  219. proc matchSym(c: PContext; candidate: PSym, n: PNode; m: var MatchCon): bool =
  220. ## Checks if 'candidate' matches 'n' from the concept body. 'n' is a nkProcDef
  221. ## or similar.
  222. # watch out: only add bindings after a completely successful match.
  223. let oldLen = m.inferred.len
  224. let can = candidate.typ.n
  225. let con = n[0].sym.typ.n
  226. if can.len < con.len:
  227. # too few arguments, cannot be a match:
  228. return false
  229. let common = min(can.len, con.len)
  230. for i in 1 ..< common:
  231. if not matchType(c, con[i].typ, can[i].typ, m):
  232. m.inferred.setLen oldLen
  233. return false
  234. if not matchReturnType(c, n[0].sym.typ.sons[0], candidate.typ.sons[0], m):
  235. m.inferred.setLen oldLen
  236. return false
  237. # all other parameters have to be optional parameters:
  238. for i in common ..< can.len:
  239. assert can[i].kind == nkSym
  240. if can[i].sym.ast == nil:
  241. # has too many arguments one of which is not optional:
  242. m.inferred.setLen oldLen
  243. return false
  244. return true
  245. proc matchSyms(c: PContext, n: PNode; kinds: set[TSymKind]; m: var MatchCon): bool =
  246. ## Walk the current scope, extract candidates which the same name as 'n[namePos]',
  247. ## 'n' is the nkProcDef or similar from the concept that we try to match.
  248. let candidates = searchInScopesAllCandidatesFilterBy(c, n[namePos].sym.name, kinds)
  249. for candidate in candidates:
  250. #echo "considering ", typeToString(candidate.typ), " ", candidate.magic
  251. m.magic = candidate.magic
  252. if matchSym(c, candidate, n, m): return true
  253. result = false
  254. proc conceptMatchNode(c: PContext; n: PNode; m: var MatchCon): bool =
  255. ## Traverse the concept's AST ('n') and see if every declaration inside 'n'
  256. ## can be matched with the current scope.
  257. case n.kind
  258. of nkStmtList, nkStmtListExpr:
  259. for i in 0..<n.len:
  260. if not conceptMatchNode(c, n[i], m):
  261. return false
  262. return true
  263. of nkProcDef, nkFuncDef:
  264. # procs match any of: proc, template, macro, func, method, converter.
  265. # The others are more specific.
  266. # XXX: Enforce .noSideEffect for 'nkFuncDef'? But then what are the use cases...
  267. const filter = {skProc, skTemplate, skMacro, skFunc, skMethod, skConverter}
  268. result = matchSyms(c, n, filter, m)
  269. of nkTemplateDef:
  270. result = matchSyms(c, n, {skTemplate}, m)
  271. of nkMacroDef:
  272. result = matchSyms(c, n, {skMacro}, m)
  273. of nkConverterDef:
  274. result = matchSyms(c, n, {skConverter}, m)
  275. of nkMethodDef:
  276. result = matchSyms(c, n, {skMethod}, m)
  277. of nkIteratorDef:
  278. result = matchSyms(c, n, {skIterator}, m)
  279. else:
  280. # error was reported earlier.
  281. result = false
  282. proc conceptMatch*(c: PContext; concpt, arg: PType; bindings: var TIdTable; invocation: PType): bool =
  283. ## Entry point from sigmatch. 'concpt' is the concept we try to match (here still a PType but
  284. ## we extract its AST via 'concpt.n.lastSon'). 'arg' is the type that might fullfill the
  285. ## concept's requirements. If so, we return true and fill the 'bindings' with pairs of
  286. ## (typeVar, instance) pairs. ('typeVar' is usually simply written as a generic 'T'.)
  287. ## 'invocation' can be nil for atomic concepts. For non-atomic concepts, it contains the
  288. ## `C[S, T]` parent type that we look for. We need this because we need to store bindings
  289. ## for 'S' and 'T' inside 'bindings' on a successful match. It is very important that
  290. ## we do not add any bindings at all on an unsuccessful match!
  291. var m = MatchCon(inferred: @[], potentialImplementation: arg)
  292. result = conceptMatchNode(c, concpt.n.lastSon, m)
  293. if result:
  294. for (a, b) in m.inferred:
  295. if b.kind == tyGenericParam:
  296. var dest = b
  297. while true:
  298. dest = existingBinding(m, dest)
  299. if dest == nil or dest.kind != tyGenericParam: break
  300. if dest != nil:
  301. bindings.idTablePut(a, dest)
  302. when logBindings: echo "A bind ", a, " ", dest
  303. else:
  304. bindings.idTablePut(a, b)
  305. when logBindings: echo "B bind ", a, " ", b
  306. # we have a match, so bind 'arg' itself to 'concpt':
  307. bindings.idTablePut(concpt, arg)
  308. # invocation != nil means we have a non-atomic concept:
  309. if invocation != nil and arg.kind == tyGenericInst and invocation.len == arg.len-1:
  310. # bind even more generic parameters
  311. assert invocation.kind == tyGenericInvocation
  312. for i in 1 ..< invocation.len:
  313. bindings.idTablePut(invocation[i], arg[i])