semobjconstr.nim 18 KB

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