semobjconstr.nim 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. proc pickCaseBranch(caseExpr, matched: PNode): PNode =
  76. # XXX: Perhaps this proc already exists somewhere
  77. let endsWithElse = caseExpr[^1].kind == nkElse
  78. for i in 1 .. caseExpr.len - 1 - int(endsWithElse):
  79. if caseExpr[i].caseBranchMatchesExpr(matched):
  80. return caseExpr[i]
  81. if endsWithElse:
  82. return caseExpr[^1]
  83. iterator directFieldsInRecList(recList: PNode): PNode =
  84. # XXX: We can remove this case by making all nkOfBranch nodes
  85. # regular. Currently, they try to avoid using nkRecList if they
  86. # include only a single field
  87. if recList.kind == nkSym:
  88. yield recList
  89. else:
  90. doAssert recList.kind == nkRecList
  91. for field in recList:
  92. if field.kind != nkSym: continue
  93. yield field
  94. template quoteStr(s: string): string = "'" & s & "'"
  95. proc fieldsPresentInInitExpr(c: PContext, fieldsRecList, initExpr: PNode): string =
  96. result = ""
  97. for field in directFieldsInRecList(fieldsRecList):
  98. let assignment = locateFieldInInitExpr(c, field.sym, initExpr)
  99. if assignment != nil:
  100. if result.len != 0: result.add ", "
  101. result.add field.sym.name.s.quoteStr
  102. proc missingMandatoryFields(c: PContext, fieldsRecList, initExpr: PNode): string =
  103. for r in directFieldsInRecList(fieldsRecList):
  104. if {tfNotNil, tfNeedsInit} * r.sym.typ.flags != {}:
  105. let assignment = locateFieldInInitExpr(c, r.sym, initExpr)
  106. if assignment == nil:
  107. if result.len == 0:
  108. result = r.sym.name.s
  109. else:
  110. result.add ", "
  111. result.add r.sym.name.s
  112. proc checkForMissingFields(c: PContext, recList, initExpr: PNode) =
  113. let missing = missingMandatoryFields(c, recList, initExpr)
  114. if missing.len > 0:
  115. localError(c.config, initExpr.info, "fields not initialized: $1.", [missing])
  116. proc semConstructFields(c: PContext, recNode: PNode,
  117. initExpr: PNode, flags: TExprFlags): InitStatus =
  118. result = initUnknown
  119. case recNode.kind
  120. of nkRecList:
  121. for field in recNode:
  122. let status = semConstructFields(c, field, initExpr, flags)
  123. mergeInitStatus(result, status)
  124. of nkRecCase:
  125. template fieldsPresentInBranch(branchIdx: int): string =
  126. let branch = recNode[branchIdx]
  127. let fields = branch[branch.len - 1]
  128. fieldsPresentInInitExpr(c, fields, initExpr)
  129. template checkMissingFields(branchNode: PNode) =
  130. let fields = branchNode[branchNode.len - 1]
  131. checkForMissingFields(c, fields, initExpr)
  132. let discriminator = recNode.sons[0]
  133. internalAssert c.config, discriminator.kind == nkSym
  134. var selectedBranch = -1
  135. for i in 1 ..< recNode.len:
  136. let innerRecords = recNode[i][^1]
  137. let status = semConstructFields(c, innerRecords, initExpr, flags)
  138. if status notin {initNone, initUnknown}:
  139. mergeInitStatus(result, status)
  140. if selectedBranch != -1:
  141. let prevFields = fieldsPresentInBranch(selectedBranch)
  142. let currentFields = fieldsPresentInBranch(i)
  143. localError(c.config, initExpr.info,
  144. ("The fields '$1' and '$2' cannot be initialized together, " &
  145. "because they are from conflicting branches in the case object.") %
  146. [prevFields, currentFields])
  147. result = initConflict
  148. else:
  149. selectedBranch = i
  150. if selectedBranch != -1:
  151. let branchNode = recNode[selectedBranch]
  152. let flags = flags*{efAllowDestructor} + {efNeedStatic, efPreferNilResult}
  153. let discriminatorVal = semConstrField(c, flags,
  154. discriminator.sym, initExpr)
  155. if discriminatorVal == nil:
  156. let fields = fieldsPresentInBranch(selectedBranch)
  157. localError(c.config, initExpr.info,
  158. ("you must provide a compile-time value for the discriminator '$1' " &
  159. "in order to prove that it's safe to initialize $2.") %
  160. [discriminator.sym.name.s, fields])
  161. mergeInitStatus(result, initNone)
  162. else:
  163. let discriminatorVal = discriminatorVal.skipHidden
  164. template wrongBranchError(i) =
  165. let fields = fieldsPresentInBranch(i)
  166. localError(c.config, initExpr.info,
  167. "a case selecting discriminator '$1' with value '$2' " &
  168. "appears in the object construction, but the field(s) $3 " &
  169. "are in conflict with this value.",
  170. [discriminator.sym.name.s, discriminatorVal.renderTree, fields])
  171. if branchNode.kind != nkElse:
  172. if not branchNode.caseBranchMatchesExpr(discriminatorVal):
  173. wrongBranchError(selectedBranch)
  174. else:
  175. # With an else clause, check that all other branches don't match:
  176. for i in 1 .. (recNode.len - 2):
  177. if recNode[i].caseBranchMatchesExpr(discriminatorVal):
  178. wrongBranchError(i)
  179. break
  180. # When a branch is selected with a partial match, some of the fields
  181. # that were not initialized may be mandatory. We must check for this:
  182. if result == initPartial:
  183. checkMissingFields branchNode
  184. else:
  185. result = initNone
  186. let discriminatorVal = semConstrField(c, flags + {efPreferStatic},
  187. discriminator.sym, initExpr)
  188. if discriminatorVal == nil:
  189. # None of the branches were explicitly selected by the user and no
  190. # value was given to the discrimator. We can assume that it will be
  191. # initialized to zero and this will select a particular branch as
  192. # a result:
  193. let matchedBranch = recNode.pickCaseBranch newIntLit(c.graph, initExpr.info, 0)
  194. checkMissingFields matchedBranch
  195. else:
  196. result = initPartial
  197. if discriminatorVal.kind == nkIntLit:
  198. # When the discriminator is a compile-time value, we also know
  199. # which brach will be selected:
  200. let matchedBranch = recNode.pickCaseBranch discriminatorVal
  201. if matchedBranch != nil: checkMissingFields matchedBranch
  202. else:
  203. # All bets are off. If any of the branches has a mandatory
  204. # fields we must produce an error:
  205. for i in 1 ..< recNode.len: checkMissingFields recNode[i]
  206. of nkSym:
  207. let field = recNode.sym
  208. let e = semConstrField(c, flags, field, initExpr)
  209. result = if e != nil: initFull else: initNone
  210. else:
  211. internalAssert c.config, false
  212. proc semConstructType(c: PContext, initExpr: PNode,
  213. t: PType, flags: TExprFlags): InitStatus =
  214. var t = t
  215. result = initUnknown
  216. while true:
  217. let status = semConstructFields(c, t.n, initExpr, flags)
  218. mergeInitStatus(result, status)
  219. if status in {initPartial, initNone, initUnknown}:
  220. checkForMissingFields c, t.n, initExpr
  221. let base = t.sons[0]
  222. if base == nil: break
  223. t = skipTypes(base, skipPtrs)
  224. proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags): PNode =
  225. var t = semTypeNode(c, n.sons[0], nil)
  226. result = newNodeIT(nkObjConstr, n.info, t)
  227. for child in n: result.add child
  228. if t == nil:
  229. localError(c.config, n.info, errGenerated, "object constructor needs an object type")
  230. return
  231. t = skipTypes(t, {tyGenericInst, tyAlias, tySink})
  232. if t.kind == tyRef: t = skipTypes(t.sons[0], {tyGenericInst, tyAlias, tySink})
  233. if t.kind != tyObject:
  234. localError(c.config, n.info, errGenerated, "object constructor needs an object type")
  235. return
  236. # Check if the object is fully initialized by recursively testing each
  237. # field (if this is a case object, initialized fields in two different
  238. # branches will be reported as an error):
  239. let initResult = semConstructType(c, result, t, flags)
  240. # It's possible that the object was not fully initialized while
  241. # specifying a .requiresInit. pragma.
  242. # XXX: Turn this into an error in the next release
  243. if tfNeedsInit in t.flags and initResult != initFull:
  244. # XXX: Disable this warning for now, because tfNeedsInit is propagated
  245. # too aggressively from fields to object types (and this is not correct
  246. # in case objects)
  247. when false: message(n.info, warnUser,
  248. "object type uses the 'requiresInit' pragma, but not all fields " &
  249. "have been initialized. future versions of Nim will treat this as " &
  250. "an error")
  251. # Since we were traversing the object fields, it's possible that
  252. # not all of the fields specified in the constructor was visited.
  253. # We'll check for such fields here:
  254. for i in 1..<result.len:
  255. let field = result[i]
  256. if nfSem notin field.flags:
  257. if field.kind != nkExprColonExpr:
  258. invalidObjConstr(c, field)
  259. continue
  260. let id = considerQuotedIdent(c, field[0])
  261. # This node was not processed. There are two possible reasons:
  262. # 1) It was shadowed by a field with the same name on the left
  263. for j in 1 ..< i:
  264. let prevId = considerQuotedIdent(c, result[j][0])
  265. if prevId.id == id.id:
  266. localError(c.config, field.info, errFieldInitTwice % id.s)
  267. return
  268. # 2) No such field exists in the constructed type
  269. localError(c.config, field.info, errUndeclaredFieldX % id.s)
  270. return