semobjconstr.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements Nim's object construction rules.
  10. # included from sem.nim
  11. type
  12. ObjConstrContext = object
  13. typ: PType # The constructed type
  14. initExpr: PNode # The init expression (nkObjConstr)
  15. needsFullInit: bool # A `requiresInit` derived type will
  16. # set this to true while visiting
  17. # parent types.
  18. missingFields: seq[PSym] # Fields that the user failed to specify
  19. InitStatus = enum # This indicates the result of object construction
  20. initUnknown
  21. initFull # All of the fields have been initialized
  22. initPartial # Some of the fields have been initialized
  23. initNone # None of the fields have been initialized
  24. initConflict # Fields from different branches have been initialized
  25. proc mergeInitStatus(existing: var InitStatus, newStatus: InitStatus) =
  26. case newStatus
  27. of initConflict:
  28. existing = newStatus
  29. of initPartial:
  30. if existing in {initUnknown, initFull, initNone}:
  31. existing = initPartial
  32. of initNone:
  33. if existing == initUnknown:
  34. existing = initNone
  35. elif existing == initFull:
  36. existing = initPartial
  37. of initFull:
  38. if existing == initUnknown:
  39. existing = initFull
  40. elif existing == initNone:
  41. existing = initPartial
  42. of initUnknown:
  43. discard
  44. proc invalidObjConstr(c: PContext, n: PNode) =
  45. if n.kind == nkInfix and n[0].kind == nkIdent and n[0].ident.s[0] == ':':
  46. localError(c.config, n.info, "incorrect object construction syntax; use a space after the colon")
  47. else:
  48. localError(c.config, n.info, "incorrect object construction syntax")
  49. proc locateFieldInInitExpr(c: PContext, field: PSym, initExpr: PNode): PNode =
  50. # Returns the assignment nkExprColonExpr node or nil
  51. let fieldId = field.name.id
  52. for i in 1..<initExpr.len:
  53. let assignment = initExpr[i]
  54. if assignment.kind != nkExprColonExpr:
  55. invalidObjConstr(c, assignment)
  56. continue
  57. if fieldId == considerQuotedIdent(c, assignment[0]).id:
  58. return assignment
  59. proc semConstrField(c: PContext, flags: TExprFlags,
  60. field: PSym, initExpr: PNode): PNode =
  61. let assignment = locateFieldInInitExpr(c, field, initExpr)
  62. if assignment != nil:
  63. if nfSem in assignment.flags: return assignment[1]
  64. if not fieldVisible(c, field):
  65. localError(c.config, initExpr.info,
  66. "the field '$1' is not accessible." % [field.name.s])
  67. return
  68. var initValue = semExprFlagDispatched(c, assignment[1], flags)
  69. if initValue != nil:
  70. initValue = fitNode(c, field.typ, initValue, assignment.info)
  71. assignment[0] = newSymNode(field)
  72. assignment[1] = initValue
  73. assignment.flags.incl nfSem
  74. return initValue
  75. proc caseBranchMatchesExpr(branch, matched: PNode): bool =
  76. for i in 0..<branch.len-1:
  77. if branch[i].kind == nkRange:
  78. if overlap(branch[i], matched): return true
  79. elif exprStructuralEquivalent(branch[i], matched):
  80. return true
  81. return false
  82. proc branchVals(c: PContext, caseNode: PNode, caseIdx: int,
  83. isStmtBranch: bool): IntSet =
  84. if caseNode[caseIdx].kind == nkOfBranch:
  85. result = initIntSet()
  86. for val in processBranchVals(caseNode[caseIdx]):
  87. result.incl(val)
  88. else:
  89. result = c.getIntSetOfType(caseNode[0].typ)
  90. for i in 1..<caseNode.len-1:
  91. for val in processBranchVals(caseNode[i]):
  92. result.excl(val)
  93. proc findUsefulCaseContext(c: PContext, discrimator: PNode): (PNode, int) =
  94. for i in countdown(c.p.caseContext.high, 0):
  95. let
  96. (caseNode, index) = c.p.caseContext[i]
  97. skipped = caseNode[0].skipHidden
  98. if skipped.kind == nkSym and skipped.sym == discrimator.sym:
  99. return (caseNode, index)
  100. proc pickCaseBranch(caseExpr, matched: PNode): PNode =
  101. # XXX: Perhaps this proc already exists somewhere
  102. let endsWithElse = caseExpr[^1].kind == nkElse
  103. for i in 1..<caseExpr.len - int(endsWithElse):
  104. if caseExpr[i].caseBranchMatchesExpr(matched):
  105. return caseExpr[i]
  106. if endsWithElse:
  107. return caseExpr[^1]
  108. iterator directFieldsInRecList(recList: PNode): PNode =
  109. # XXX: We can remove this case by making all nkOfBranch nodes
  110. # regular. Currently, they try to avoid using nkRecList if they
  111. # include only a single field
  112. if recList.kind == nkSym:
  113. yield recList
  114. else:
  115. doAssert recList.kind == nkRecList
  116. for field in recList:
  117. if field.kind != nkSym: continue
  118. yield field
  119. template quoteStr(s: string): string = "'" & s & "'"
  120. proc fieldsPresentInInitExpr(c: PContext, fieldsRecList, initExpr: PNode): string =
  121. result = ""
  122. for field in directFieldsInRecList(fieldsRecList):
  123. if locateFieldInInitExpr(c, field.sym, initExpr) != nil:
  124. if result.len != 0: result.add ", "
  125. result.add field.sym.name.s.quoteStr
  126. proc collectMissingFields(c: PContext, fieldsRecList: PNode,
  127. constrCtx: var ObjConstrContext) =
  128. for r in directFieldsInRecList(fieldsRecList):
  129. if constrCtx.needsFullInit or
  130. sfRequiresInit in r.sym.flags or
  131. r.sym.typ.requiresInit:
  132. let assignment = locateFieldInInitExpr(c, r.sym, constrCtx.initExpr)
  133. if assignment == nil:
  134. constrCtx.missingFields.add r.sym
  135. proc semConstructFields(c: PContext, n: PNode,
  136. constrCtx: var ObjConstrContext,
  137. flags: TExprFlags): InitStatus =
  138. result = initUnknown
  139. case n.kind
  140. of nkRecList:
  141. for field in n:
  142. let status = semConstructFields(c, field, constrCtx, flags)
  143. mergeInitStatus(result, status)
  144. of nkRecCase:
  145. template fieldsPresentInBranch(branchIdx: int): string =
  146. let branch = n[branchIdx]
  147. let fields = branch[^1]
  148. fieldsPresentInInitExpr(c, fields, constrCtx.initExpr)
  149. template collectMissingFields(branchNode: PNode) =
  150. if branchNode != nil:
  151. let fields = branchNode[^1]
  152. collectMissingFields(c, fields, constrCtx)
  153. let discriminator = n[0]
  154. internalAssert c.config, discriminator.kind == nkSym
  155. var selectedBranch = -1
  156. for i in 1..<n.len:
  157. let innerRecords = n[i][^1]
  158. let status = semConstructFields(c, innerRecords, constrCtx, flags)
  159. if status notin {initNone, initUnknown}:
  160. mergeInitStatus(result, status)
  161. if selectedBranch != -1:
  162. let prevFields = fieldsPresentInBranch(selectedBranch)
  163. let currentFields = fieldsPresentInBranch(i)
  164. localError(c.config, constrCtx.initExpr.info,
  165. ("The fields '$1' and '$2' cannot be initialized together, " &
  166. "because they are from conflicting branches in the case object.") %
  167. [prevFields, currentFields])
  168. result = initConflict
  169. else:
  170. selectedBranch = i
  171. if selectedBranch != -1:
  172. template badDiscriminatorError =
  173. let fields = fieldsPresentInBranch(selectedBranch)
  174. localError(c.config, constrCtx.initExpr.info,
  175. ("cannot prove that it's safe to initialize $1 with " &
  176. "the runtime value for the discriminator '$2' ") %
  177. [fields, discriminator.sym.name.s])
  178. mergeInitStatus(result, initNone)
  179. template wrongBranchError(i) =
  180. let fields = fieldsPresentInBranch(i)
  181. localError(c.config, constrCtx.initExpr.info,
  182. "a case selecting discriminator '$1' with value '$2' " &
  183. "appears in the object construction, but the field(s) $3 " &
  184. "are in conflict with this value.",
  185. [discriminator.sym.name.s, discriminatorVal.renderTree, fields])
  186. template valuesInConflictError(valsDiff) =
  187. localError(c.config, discriminatorVal.info, ("possible values " &
  188. "$2 are in conflict with discriminator values for " &
  189. "selected object branch $1.") % [$selectedBranch,
  190. valsDiff.renderAsType(n[0].typ)])
  191. let branchNode = n[selectedBranch]
  192. let flags = flags*{efAllowDestructor} + {efPreferStatic,
  193. efPreferNilResult}
  194. var discriminatorVal = semConstrField(c, flags,
  195. discriminator.sym,
  196. constrCtx.initExpr)
  197. if discriminatorVal != nil:
  198. discriminatorVal = discriminatorVal.skipHidden
  199. if discriminatorVal.kind notin nkLiterals and (
  200. not isOrdinalType(discriminatorVal.typ, true) or
  201. lengthOrd(c.config, discriminatorVal.typ) > MaxSetElements or
  202. lengthOrd(c.config, n[0].typ) > MaxSetElements):
  203. localError(c.config, discriminatorVal.info,
  204. "branch initialization with a runtime discriminator only " &
  205. "supports ordinal types with 2^16 elements or less.")
  206. if discriminatorVal == nil:
  207. badDiscriminatorError()
  208. elif discriminatorVal.kind == nkSym:
  209. let (ctorCase, ctorIdx) = findUsefulCaseContext(c, discriminatorVal)
  210. if ctorCase == nil:
  211. if discriminatorVal.typ.kind == tyRange:
  212. let rangeVals = c.getIntSetOfType(discriminatorVal.typ)
  213. let recBranchVals = branchVals(c, n, selectedBranch, false)
  214. let diff = rangeVals - recBranchVals
  215. if diff.len != 0:
  216. valuesInConflictError(diff)
  217. else:
  218. badDiscriminatorError()
  219. elif discriminatorVal.sym.kind notin {skLet, skParam} or
  220. discriminatorVal.sym.typ.kind in {tyVar}:
  221. localError(c.config, discriminatorVal.info,
  222. "runtime discriminator must be immutable if branch fields are " &
  223. "initialized, a 'let' binding is required.")
  224. elif ctorCase[ctorIdx].kind == nkElifBranch:
  225. localError(c.config, discriminatorVal.info, "branch initialization " &
  226. "with a runtime discriminator is not supported inside of an " &
  227. "`elif` branch.")
  228. else:
  229. var
  230. ctorBranchVals = branchVals(c, ctorCase, ctorIdx, true)
  231. recBranchVals = branchVals(c, n, selectedBranch, false)
  232. branchValsDiff = ctorBranchVals - recBranchVals
  233. if branchValsDiff.len != 0:
  234. valuesInConflictError(branchValsDiff)
  235. else:
  236. var failedBranch = -1
  237. if branchNode.kind != nkElse:
  238. if not branchNode.caseBranchMatchesExpr(discriminatorVal):
  239. failedBranch = selectedBranch
  240. else:
  241. # With an else clause, check that all other branches don't match:
  242. for i in 1..<n.len - 1:
  243. if n[i].caseBranchMatchesExpr(discriminatorVal):
  244. failedBranch = i
  245. break
  246. if failedBranch != -1:
  247. if discriminatorVal.typ.kind == tyRange:
  248. let rangeVals = c.getIntSetOfType(discriminatorVal.typ)
  249. let recBranchVals = branchVals(c, n, selectedBranch, false)
  250. let diff = rangeVals - recBranchVals
  251. if diff.len != 0:
  252. valuesInConflictError(diff)
  253. else:
  254. wrongBranchError(failedBranch)
  255. # When a branch is selected with a partial match, some of the fields
  256. # that were not initialized may be mandatory. We must check for this:
  257. if result == initPartial:
  258. collectMissingFields branchNode
  259. else:
  260. result = initNone
  261. let discriminatorVal = semConstrField(c, flags + {efPreferStatic},
  262. discriminator.sym,
  263. constrCtx.initExpr)
  264. if discriminatorVal == nil:
  265. # None of the branches were explicitly selected by the user and no
  266. # value was given to the discrimator. We can assume that it will be
  267. # initialized to zero and this will select a particular branch as
  268. # a result:
  269. let defaultValue = newIntLit(c.graph, constrCtx.initExpr.info, 0)
  270. let matchedBranch = n.pickCaseBranch defaultValue
  271. collectMissingFields matchedBranch
  272. else:
  273. result = initPartial
  274. if discriminatorVal.kind == nkIntLit:
  275. # When the discriminator is a compile-time value, we also know
  276. # which branch will be selected:
  277. let matchedBranch = n.pickCaseBranch discriminatorVal
  278. if matchedBranch != nil: collectMissingFields matchedBranch
  279. else:
  280. # All bets are off. If any of the branches has a mandatory
  281. # fields we must produce an error:
  282. for i in 1..<n.len: collectMissingFields n[i]
  283. of nkSym:
  284. let field = n.sym
  285. let e = semConstrField(c, flags, field, constrCtx.initExpr)
  286. result = if e != nil: initFull else: initNone
  287. else:
  288. internalAssert c.config, false
  289. proc semConstructTypeAux(c: PContext,
  290. constrCtx: var ObjConstrContext,
  291. flags: TExprFlags): InitStatus =
  292. result = initUnknown
  293. var t = constrCtx.typ
  294. while true:
  295. let status = semConstructFields(c, t.n, constrCtx, flags)
  296. mergeInitStatus(result, status)
  297. if status in {initPartial, initNone, initUnknown}:
  298. collectMissingFields c, t.n, constrCtx
  299. let base = t[0]
  300. if base == nil: break
  301. t = skipTypes(base, skipPtrs)
  302. if t.kind != tyObject:
  303. # XXX: This is not supposed to happen, but apparently
  304. # there are some issues in semtypinst. Luckily, it
  305. # seems to affect only `computeRequiresInit`.
  306. return
  307. constrCtx.needsFullInit = constrCtx.needsFullInit or
  308. tfNeedsFullInit in t.flags
  309. proc initConstrContext(t: PType, initExpr: PNode): ObjConstrContext =
  310. ObjConstrContext(typ: t, initExpr: initExpr,
  311. needsFullInit: tfNeedsFullInit in t.flags)
  312. proc computeRequiresInit(c: PContext, t: PType): bool =
  313. assert t.kind == tyObject
  314. var constrCtx = initConstrContext(t, newNode(nkObjConstr))
  315. let initResult = semConstructTypeAux(c, constrCtx, {})
  316. constrCtx.missingFields.len > 0
  317. proc defaultConstructionError(c: PContext, t: PType, info: TLineInfo) =
  318. var objType = t
  319. while objType.kind != tyObject:
  320. objType = objType.lastSon
  321. assert objType != nil
  322. var constrCtx = initConstrContext(objType, newNodeI(nkObjConstr, info))
  323. let initResult = semConstructTypeAux(c, constrCtx, {})
  324. assert constrCtx.missingFields.len > 0
  325. localError(c.config, info,
  326. "The $1 type doesn't have a default value. The following fields must be initialized: $2.",
  327. [typeToString(t), listSymbolNames(constrCtx.missingFields)])
  328. proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags): PNode =
  329. var t = semTypeNode(c, n[0], nil)
  330. result = newNodeIT(nkObjConstr, n.info, t)
  331. for child in n: result.add child
  332. if t == nil:
  333. localError(c.config, n.info, errGenerated, "object constructor needs an object type")
  334. return
  335. t = skipTypes(t, {tyGenericInst, tyAlias, tySink, tyOwned})
  336. if t.kind == tyRef:
  337. t = skipTypes(t[0], {tyGenericInst, tyAlias, tySink, tyOwned})
  338. if optOwnedRefs in c.config.globalOptions:
  339. result.typ = makeVarType(c, result.typ, tyOwned)
  340. # we have to watch out, there are also 'owned proc' types that can be used
  341. # multiple times as long as they don't have closures.
  342. result.typ.flags.incl tfHasOwned
  343. if t.kind != tyObject:
  344. localError(c.config, n.info, errGenerated, "object constructor needs an object type")
  345. return
  346. # Check if the object is fully initialized by recursively testing each
  347. # field (if this is a case object, initialized fields in two different
  348. # branches will be reported as an error):
  349. var constrCtx = initConstrContext(t, result)
  350. let initResult = semConstructTypeAux(c, constrCtx, flags)
  351. # It's possible that the object was not fully initialized while
  352. # specifying a .requiresInit. pragma:
  353. if constrCtx.missingFields.len > 0:
  354. localError(c.config, result.info,
  355. "The $1 type requires the following fields to be initialized: $2.",
  356. [t.sym.name.s, listSymbolNames(constrCtx.missingFields)])
  357. # Since we were traversing the object fields, it's possible that
  358. # not all of the fields specified in the constructor was visited.
  359. # We'll check for such fields here:
  360. for i in 1..<result.len:
  361. let field = result[i]
  362. if nfSem notin field.flags:
  363. if field.kind != nkExprColonExpr:
  364. invalidObjConstr(c, field)
  365. continue
  366. let id = considerQuotedIdent(c, field[0])
  367. # This node was not processed. There are two possible reasons:
  368. # 1) It was shadowed by a field with the same name on the left
  369. for j in 1..<i:
  370. let prevId = considerQuotedIdent(c, result[j][0])
  371. if prevId.id == id.id:
  372. localError(c.config, field.info, errFieldInitTwice % id.s)
  373. return
  374. # 2) No such field exists in the constructed type
  375. localError(c.config, field.info, errUndeclaredFieldX % id.s)
  376. return
  377. if initResult == initFull:
  378. incl result.flags, nfAllFieldsSet