semobjconstr.nim 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. InitStatus = enum
  13. initUnknown
  14. initFull # All of the fields have been initialized
  15. initPartial # Some of the fields have been initialized
  16. initNone # None of the fields have been initialized
  17. initConflict # Fields from different branches have been initialized
  18. proc mergeInitStatus(existing: var InitStatus, newStatus: InitStatus) =
  19. case newStatus
  20. of initConflict:
  21. existing = newStatus
  22. of initPartial:
  23. if existing in {initUnknown, initFull, initNone}:
  24. existing = initPartial
  25. of initNone:
  26. if existing == initUnknown:
  27. existing = initNone
  28. elif existing == initFull:
  29. existing = initPartial
  30. of initFull:
  31. if existing == initUnknown:
  32. existing = initFull
  33. elif existing == initNone:
  34. existing = initPartial
  35. of initUnknown:
  36. discard
  37. proc invalidObjConstr(c: PContext, n: PNode) =
  38. if n.kind == nkInfix and n[0].kind == nkIdent and n[0].ident.s[0] == ':':
  39. localError(c.config, n.info, "incorrect object construction syntax; use a space after the colon")
  40. else:
  41. localError(c.config, n.info, "incorrect object construction syntax")
  42. proc locateFieldInInitExpr(c: PContext, field: PSym, initExpr: PNode): PNode =
  43. # Returns the assignment nkExprColonExpr node or nil
  44. let fieldId = field.name.id
  45. for i in 1 ..< initExpr.len:
  46. let assignment = initExpr[i]
  47. if assignment.kind != nkExprColonExpr:
  48. invalidObjConstr(c, assignment)
  49. continue
  50. if fieldId == considerQuotedIdent(c, assignment[0]).id:
  51. return assignment
  52. proc semConstrField(c: PContext, flags: TExprFlags,
  53. field: PSym, initExpr: PNode): PNode =
  54. let assignment = locateFieldInInitExpr(c, field, initExpr)
  55. if assignment != nil:
  56. if nfSem in assignment.flags: return assignment[1]
  57. if not fieldVisible(c, field):
  58. localError(c.config, initExpr.info,
  59. "the field '$1' is not accessible." % [field.name.s])
  60. return
  61. var initValue = semExprFlagDispatched(c, assignment[1], flags)
  62. if initValue != nil:
  63. initValue = fitNode(c, field.typ, initValue, assignment.info)
  64. assignment.sons[0] = newSymNode(field)
  65. assignment.sons[1] = initValue
  66. assignment.flags.incl nfSem
  67. return initValue
  68. proc caseBranchMatchesExpr(branch, matched: PNode): bool =
  69. for i in 0 .. branch.len-2:
  70. if branch[i].kind == nkRange:
  71. if overlap(branch[i], matched): return true
  72. elif exprStructuralEquivalent(branch[i], matched):
  73. return true
  74. return false
  75. template processBranchVals(b, op) =
  76. if b.kind != nkElifBranch:
  77. for i in 0 .. b.len-2:
  78. if b[i].kind == nkIntLit:
  79. result.op(b[i].intVal.int)
  80. elif b[i].kind == nkRange:
  81. for i in b[i][0].intVal .. b[i][1].intVal:
  82. result.op(i.int)
  83. proc allPossibleValues(c: PContext, t: PType): IntSet =
  84. result = initIntSet()
  85. if t.enumHasHoles:
  86. let t = t.skipTypes(abstractRange)
  87. for field in t.n.sons:
  88. result.incl(field.sym.position)
  89. else:
  90. for i in firstOrd(c.config, t) .. lastOrd(c.config, t):
  91. result.incl(i.int)
  92. proc branchVals(c: PContext, caseNode: PNode, caseIdx: int,
  93. isStmtBranch: bool): IntSet =
  94. if caseNode[caseIdx].kind == nkOfBranch:
  95. result = initIntSet()
  96. processBranchVals(caseNode[caseIdx], incl)
  97. else:
  98. result = allPossibleValues(c, caseNode.sons[0].typ)
  99. for i in 1 .. caseNode.len-2:
  100. processBranchVals(caseNode[i], excl)
  101. proc formatUnsafeBranchVals(t: PType, diffVals: IntSet): string =
  102. if diffVals.len <= 32:
  103. var strs: seq[string]
  104. let t = t.skipTypes(abstractRange)
  105. if t.kind in {tyEnum, tyBool}:
  106. var i = 0
  107. for val in diffVals:
  108. while t.n.sons[i].sym.position < val: inc(i)
  109. strs.add(t.n.sons[i].sym.name.s)
  110. else:
  111. for val in diffVals:
  112. strs.add($val)
  113. result = "{" & strs.join(", ") & "} "
  114. proc findUsefulCaseContext(c: PContext, discrimator: PNode): (PNode, int) =
  115. for i in countdown(c.p.caseContext.high, 0):
  116. let
  117. (caseNode, index) = c.p.caseContext[i]
  118. skipped = caseNode[0].skipHidden
  119. if skipped.kind == nkSym and skipped.sym == discrimator.sym:
  120. return (caseNode, index)
  121. proc pickCaseBranch(caseExpr, matched: PNode): PNode =
  122. # XXX: Perhaps this proc already exists somewhere
  123. let endsWithElse = caseExpr[^1].kind == nkElse
  124. for i in 1 .. caseExpr.len - 1 - int(endsWithElse):
  125. if caseExpr[i].caseBranchMatchesExpr(matched):
  126. return caseExpr[i]
  127. if endsWithElse:
  128. return caseExpr[^1]
  129. iterator directFieldsInRecList(recList: PNode): PNode =
  130. # XXX: We can remove this case by making all nkOfBranch nodes
  131. # regular. Currently, they try to avoid using nkRecList if they
  132. # include only a single field
  133. if recList.kind == nkSym:
  134. yield recList
  135. else:
  136. doAssert recList.kind == nkRecList
  137. for field in recList:
  138. if field.kind != nkSym: continue
  139. yield field
  140. template quoteStr(s: string): string = "'" & s & "'"
  141. proc fieldsPresentInInitExpr(c: PContext, fieldsRecList, initExpr: PNode): string =
  142. result = ""
  143. for field in directFieldsInRecList(fieldsRecList):
  144. let assignment = locateFieldInInitExpr(c, field.sym, initExpr)
  145. if assignment != nil:
  146. if result.len != 0: result.add ", "
  147. result.add field.sym.name.s.quoteStr
  148. proc missingMandatoryFields(c: PContext, fieldsRecList, initExpr: PNode): string =
  149. for r in directFieldsInRecList(fieldsRecList):
  150. if {tfNotNil, tfNeedsInit} * r.sym.typ.flags != {}:
  151. let assignment = locateFieldInInitExpr(c, r.sym, initExpr)
  152. if assignment == nil:
  153. if result.len == 0:
  154. result = r.sym.name.s
  155. else:
  156. result.add ", "
  157. result.add r.sym.name.s
  158. proc checkForMissingFields(c: PContext, recList, initExpr: PNode) =
  159. let missing = missingMandatoryFields(c, recList, initExpr)
  160. if missing.len > 0:
  161. localError(c.config, initExpr.info, "fields not initialized: $1.", [missing])
  162. proc semConstructFields(c: PContext, recNode: PNode,
  163. initExpr: PNode, flags: TExprFlags): InitStatus =
  164. result = initUnknown
  165. case recNode.kind
  166. of nkRecList:
  167. for field in recNode:
  168. let status = semConstructFields(c, field, initExpr, flags)
  169. mergeInitStatus(result, status)
  170. of nkRecCase:
  171. template fieldsPresentInBranch(branchIdx: int): string =
  172. let branch = recNode[branchIdx]
  173. let fields = branch[branch.len - 1]
  174. fieldsPresentInInitExpr(c, fields, initExpr)
  175. template checkMissingFields(branchNode: PNode) =
  176. let fields = branchNode[branchNode.len - 1]
  177. checkForMissingFields(c, fields, initExpr)
  178. let discriminator = recNode.sons[0]
  179. internalAssert c.config, discriminator.kind == nkSym
  180. var selectedBranch = -1
  181. for i in 1 ..< recNode.len:
  182. let innerRecords = recNode[i][^1]
  183. let status = semConstructFields(c, innerRecords, initExpr, flags)
  184. if status notin {initNone, initUnknown}:
  185. mergeInitStatus(result, status)
  186. if selectedBranch != -1:
  187. let prevFields = fieldsPresentInBranch(selectedBranch)
  188. let currentFields = fieldsPresentInBranch(i)
  189. localError(c.config, initExpr.info,
  190. ("The fields '$1' and '$2' cannot be initialized together, " &
  191. "because they are from conflicting branches in the case object.") %
  192. [prevFields, currentFields])
  193. result = initConflict
  194. else:
  195. selectedBranch = i
  196. if selectedBranch != -1:
  197. template badDiscriminatorError =
  198. let fields = fieldsPresentInBranch(selectedBranch)
  199. localError(c.config, initExpr.info,
  200. ("you must provide a compile-time value for the discriminator '$1' " &
  201. "in order to prove that it's safe to initialize $2.") %
  202. [discriminator.sym.name.s, fields])
  203. mergeInitStatus(result, initNone)
  204. template wrongBranchError(i) =
  205. let fields = fieldsPresentInBranch(i)
  206. localError(c.config, initExpr.info,
  207. "a case selecting discriminator '$1' with value '$2' " &
  208. "appears in the object construction, but the field(s) $3 " &
  209. "are in conflict with this value.",
  210. [discriminator.sym.name.s, discriminatorVal.renderTree, fields])
  211. let branchNode = recNode[selectedBranch]
  212. let flags = flags*{efAllowDestructor} + {efPreferStatic,
  213. efPreferNilResult}
  214. var discriminatorVal = semConstrField(c, flags,
  215. discriminator.sym, initExpr)
  216. if discriminatorVal != nil:
  217. discriminatorVal = discriminatorVal.skipHidden
  218. if discriminatorVal == nil:
  219. badDiscriminatorError()
  220. elif discriminatorVal.kind == nkSym:
  221. let (ctorCase, ctorIdx) = findUsefulCaseContext(c, discriminatorVal)
  222. if ctorCase == nil:
  223. badDiscriminatorError()
  224. elif discriminatorVal.sym.kind notin {skLet, skParam} or
  225. discriminatorVal.sym.typ.kind == tyVar:
  226. localError(c.config, discriminatorVal.info,
  227. "runtime discriminator must be immutable if branch fields are " &
  228. "initialized, a 'let' binding is required.")
  229. elif not isOrdinalType(discriminatorVal.sym.typ, true) or
  230. lengthOrd(c.config, discriminatorVal.sym.typ) > MaxSetElements:
  231. localError(c.config, discriminatorVal.info,
  232. "branch initialization with a runtime discriminator only " &
  233. "supports ordinal types with 2^16 elements or less.")
  234. elif ctorCase[ctorIdx].kind == nkElifBranch:
  235. localError(c.config, discriminatorVal.info, "branch initialization " &
  236. "with a runtime discriminator is not supported inside of an " &
  237. "`elif` branch.")
  238. else:
  239. var
  240. ctorBranchVals = branchVals(c, ctorCase, ctorIdx, true)
  241. recBranchVals = branchVals(c, recNode, selectedBranch, false)
  242. branchValsDiff = ctorBranchVals - recBranchVals
  243. if branchValsDiff.len != 0:
  244. localError(c.config, discriminatorVal.info, ("possible values " &
  245. "$2are in conflict with discriminator values for " &
  246. "selected object branch $1.") % [$selectedBranch,
  247. formatUnsafeBranchVals(recNode.sons[0].typ, branchValsDiff)])
  248. else:
  249. if branchNode.kind != nkElse:
  250. if not branchNode.caseBranchMatchesExpr(discriminatorVal):
  251. wrongBranchError(selectedBranch)
  252. else:
  253. # With an else clause, check that all other branches don't match:
  254. for i in 1 .. (recNode.len - 2):
  255. if recNode[i].caseBranchMatchesExpr(discriminatorVal):
  256. wrongBranchError(i)
  257. break
  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. checkMissingFields branchNode
  262. else:
  263. result = initNone
  264. let discriminatorVal = semConstrField(c, flags + {efPreferStatic},
  265. discriminator.sym, initExpr)
  266. if discriminatorVal == nil:
  267. # None of the branches were explicitly selected by the user and no
  268. # value was given to the discrimator. We can assume that it will be
  269. # initialized to zero and this will select a particular branch as
  270. # a result:
  271. let matchedBranch = recNode.pickCaseBranch newIntLit(c.graph, initExpr.info, 0)
  272. checkMissingFields matchedBranch
  273. else:
  274. result = initPartial
  275. if discriminatorVal.kind == nkIntLit:
  276. # When the discriminator is a compile-time value, we also know
  277. # which brach will be selected:
  278. let matchedBranch = recNode.pickCaseBranch discriminatorVal
  279. if matchedBranch != nil: checkMissingFields matchedBranch
  280. else:
  281. # All bets are off. If any of the branches has a mandatory
  282. # fields we must produce an error:
  283. for i in 1 ..< recNode.len: checkMissingFields recNode[i]
  284. of nkSym:
  285. let field = recNode.sym
  286. let e = semConstrField(c, flags, field, initExpr)
  287. result = if e != nil: initFull else: initNone
  288. else:
  289. internalAssert c.config, false
  290. proc semConstructType(c: PContext, initExpr: PNode,
  291. t: PType, flags: TExprFlags): InitStatus =
  292. var t = t
  293. result = initUnknown
  294. while true:
  295. let status = semConstructFields(c, t.n, initExpr, flags)
  296. mergeInitStatus(result, status)
  297. if status in {initPartial, initNone, initUnknown}:
  298. checkForMissingFields c, t.n, initExpr
  299. let base = t.sons[0]
  300. if base == nil: break
  301. t = skipTypes(base, skipPtrs)
  302. proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags): PNode =
  303. var t = semTypeNode(c, n.sons[0], nil)
  304. result = newNodeIT(nkObjConstr, n.info, t)
  305. for child in n: result.add child
  306. if t == nil:
  307. localError(c.config, n.info, errGenerated, "object constructor needs an object type")
  308. return
  309. t = skipTypes(t, {tyGenericInst, tyAlias, tySink, tyOwned})
  310. if t.kind == tyRef:
  311. t = skipTypes(t.sons[0], {tyGenericInst, tyAlias, tySink, tyOwned})
  312. if optNimV2 in c.config.globalOptions:
  313. result.typ = makeVarType(c, result.typ, tyOwned)
  314. if t.kind != tyObject:
  315. localError(c.config, n.info, errGenerated, "object constructor needs an object type")
  316. return
  317. # Check if the object is fully initialized by recursively testing each
  318. # field (if this is a case object, initialized fields in two different
  319. # branches will be reported as an error):
  320. let initResult = semConstructType(c, result, t, flags)
  321. # It's possible that the object was not fully initialized while
  322. # specifying a .requiresInit. pragma.
  323. # XXX: Turn this into an error in the next release
  324. if tfNeedsInit in t.flags and initResult != initFull:
  325. # XXX: Disable this warning for now, because tfNeedsInit is propagated
  326. # too aggressively from fields to object types (and this is not correct
  327. # in case objects)
  328. when false: message(n.info, warnUser,
  329. "object type uses the 'requiresInit' pragma, but not all fields " &
  330. "have been initialized. future versions of Nim will treat this as " &
  331. "an error")
  332. # Since we were traversing the object fields, it's possible that
  333. # not all of the fields specified in the constructor was visited.
  334. # We'll check for such fields here:
  335. for i in 1..<result.len:
  336. let field = result[i]
  337. if nfSem notin field.flags:
  338. if field.kind != nkExprColonExpr:
  339. invalidObjConstr(c, field)
  340. continue
  341. let id = considerQuotedIdent(c, field[0])
  342. # This node was not processed. There are two possible reasons:
  343. # 1) It was shadowed by a field with the same name on the left
  344. for j in 1 ..< i:
  345. let prevId = considerQuotedIdent(c, result[j][0])
  346. if prevId.id == id.id:
  347. localError(c.config, field.info, errFieldInitTwice % id.s)
  348. return
  349. # 2) No such field exists in the constructed type
  350. localError(c.config, field.info, errUndeclaredFieldX % id.s)
  351. return