concepts.nim 13 KB

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