semobjconstr.nim 17 KB

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