semobjconstr.nim 20 KB

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