concepts.nim 13 KB

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