semobjconstr.nim 20 KB

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