concepts.nim 13 KB

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