semstmts.nim 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## this module does the semantic checking of statements
  10. # included from sem.nim
  11. const
  12. errNoSymbolToBorrowFromFound = "no symbol to borrow from found"
  13. errDiscardValueX = "value of type '$1' has to be used (or discarded)"
  14. errInvalidDiscard = "statement returns no value that can be discarded"
  15. errInvalidControlFlowX = "invalid control flow: $1"
  16. errSelectorMustBeOfCertainTypes = "selector must be of an ordinal type, float or string"
  17. errExprCannotBeRaised = "only a 'ref object' can be raised"
  18. errBreakOnlyInLoop = "'break' only allowed in loop construct"
  19. errExceptionAlreadyHandled = "exception already handled"
  20. errYieldNotAllowedHere = "'yield' only allowed in an iterator"
  21. errYieldNotAllowedInTryStmt = "'yield' cannot be used within 'try' in a non-inlined iterator"
  22. errInvalidNumberOfYieldExpr = "invalid number of 'yield' expressions"
  23. errCannotReturnExpr = "current routine cannot return an expression"
  24. errGenericLambdaNotAllowed = "A nested proc can have generic parameters only when " &
  25. "it is used as an operand to another routine and the types " &
  26. "of the generic paramers can be inferred from the expected signature."
  27. errCannotInferTypeOfTheLiteral = "cannot infer the type of the $1"
  28. errCannotInferReturnType = "cannot infer the return type of '$1'"
  29. errCannotInferStaticParam = "cannot infer the value of the static param '$1'"
  30. errProcHasNoConcreteType = "'$1' doesn't have a concrete type, due to unspecified generic parameters."
  31. errLetNeedsInit = "'let' symbol requires an initialization"
  32. errThreadvarCannotInit = "a thread var cannot be initialized explicitly; this would only run for the main thread"
  33. errImplOfXexpected = "implementation of '$1' expected"
  34. errRecursiveDependencyX = "recursive dependency: '$1'"
  35. errRecursiveDependencyIteratorX = "recursion is not supported in iterators: '$1'"
  36. errPragmaOnlyInHeaderOfProcX = "pragmas are only allowed in the header of a proc; redefinition of $1"
  37. errCannotAssignToGlobal = "cannot assign local to global variable"
  38. proc implicitlyDiscardable(n: PNode): bool
  39. proc hasEmpty(typ: PType): bool =
  40. if typ.kind in {tySequence, tyArray, tySet}:
  41. result = typ.lastSon.kind == tyEmpty
  42. elif typ.kind == tyTuple:
  43. for s in typ.sons:
  44. result = result or hasEmpty(s)
  45. proc semDiscard(c: PContext, n: PNode): PNode =
  46. result = n
  47. checkSonsLen(n, 1, c.config)
  48. if n[0].kind != nkEmpty:
  49. n[0] = semExprWithType(c, n[0])
  50. let sonType = n[0].typ
  51. let sonKind = n[0].kind
  52. if isEmptyType(sonType) or hasEmpty(sonType) or
  53. sonType.kind in {tyNone, tyTypeDesc} or
  54. sonKind == nkTypeOfExpr:
  55. localError(c.config, n.info, errInvalidDiscard)
  56. if sonType.kind == tyProc and sonKind notin nkCallKinds:
  57. # tyProc is disallowed to prevent ``discard foo`` to be valid, when ``discard foo()`` is meant.
  58. localError(c.config, n.info, "illegal discard proc, did you mean: " & $n[0] & "()")
  59. proc semBreakOrContinue(c: PContext, n: PNode): PNode =
  60. result = n
  61. checkSonsLen(n, 1, c.config)
  62. if n[0].kind != nkEmpty:
  63. if n.kind != nkContinueStmt:
  64. var s: PSym
  65. case n[0].kind
  66. of nkIdent: s = lookUp(c, n[0])
  67. of nkSym: s = n[0].sym
  68. else: illFormedAst(n, c.config)
  69. s = getGenSym(c, s)
  70. if s.kind == skLabel and s.owner.id == c.p.owner.id:
  71. var x = newSymNode(s)
  72. x.info = n.info
  73. incl(s.flags, sfUsed)
  74. n[0] = x
  75. suggestSym(c.graph, x.info, s, c.graph.usageSym)
  76. onUse(x.info, s)
  77. else:
  78. localError(c.config, n.info, errInvalidControlFlowX % s.name.s)
  79. else:
  80. localError(c.config, n.info, errGenerated, "'continue' cannot have a label")
  81. elif c.p.nestedBlockCounter > 0 and n.kind == nkBreakStmt and not c.p.breakInLoop:
  82. localError(c.config, n.info, warnUnnamedBreak)
  83. elif (c.p.nestedLoopCounter <= 0) and ((c.p.nestedBlockCounter <= 0) or n.kind == nkContinueStmt):
  84. localError(c.config, n.info, errInvalidControlFlowX %
  85. renderTree(n, {renderNoComments}))
  86. proc semAsm(c: PContext, n: PNode): PNode =
  87. checkSonsLen(n, 2, c.config)
  88. var marker = pragmaAsm(c, n[0])
  89. if marker == '\0': marker = '`' # default marker
  90. result = semAsmOrEmit(c, n, marker)
  91. proc semWhile(c: PContext, n: PNode; flags: TExprFlags): PNode =
  92. result = n
  93. checkSonsLen(n, 2, c.config)
  94. openScope(c)
  95. n[0] = forceBool(c, semExprWithType(c, n[0], expectedType = getSysType(c.graph, n.info, tyBool)))
  96. inc(c.p.nestedLoopCounter)
  97. let oldBreakInLoop = c.p.breakInLoop
  98. c.p.breakInLoop = true
  99. n[1] = semStmt(c, n[1], flags)
  100. c.p.breakInLoop = oldBreakInLoop
  101. dec(c.p.nestedLoopCounter)
  102. closeScope(c)
  103. if n[1].typ == c.enforceVoidContext:
  104. result.typ = c.enforceVoidContext
  105. elif efInTypeof in flags:
  106. result.typ = n[1].typ
  107. elif implicitlyDiscardable(n[1]):
  108. result[1].typ = c.enforceVoidContext
  109. proc semProc(c: PContext, n: PNode): PNode
  110. proc semExprBranch(c: PContext, n: PNode; flags: TExprFlags = {}; expectedType: PType = nil): PNode =
  111. result = semExpr(c, n, flags, expectedType)
  112. if result.typ != nil:
  113. # XXX tyGenericInst here?
  114. if result.typ.kind in {tyVar, tyLent}: result = newDeref(result)
  115. proc semExprBranchScope(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  116. openScope(c)
  117. result = semExprBranch(c, n, expectedType = expectedType)
  118. closeScope(c)
  119. const
  120. skipForDiscardable = {nkIfStmt, nkIfExpr, nkCaseStmt, nkOfBranch,
  121. nkElse, nkStmtListExpr, nkTryStmt, nkFinally, nkExceptBranch,
  122. nkElifBranch, nkElifExpr, nkElseExpr, nkBlockStmt, nkBlockExpr,
  123. nkHiddenStdConv, nkHiddenDeref}
  124. proc implicitlyDiscardable(n: PNode): bool =
  125. var n = n
  126. while n.kind in skipForDiscardable: n = n.lastSon
  127. result = n.kind in nkLastBlockStmts or
  128. (isCallExpr(n) and n[0].kind == nkSym and
  129. sfDiscardable in n[0].sym.flags)
  130. proc fixNilType(c: PContext; n: PNode) =
  131. if isAtom(n):
  132. if n.kind != nkNilLit and n.typ != nil:
  133. localError(c.config, n.info, errDiscardValueX % n.typ.typeToString)
  134. elif n.kind in {nkStmtList, nkStmtListExpr}:
  135. n.transitionSonsKind(nkStmtList)
  136. for it in n: fixNilType(c, it)
  137. n.typ = nil
  138. proc discardCheck(c: PContext, result: PNode, flags: TExprFlags) =
  139. if c.matchedConcept != nil or efInTypeof in flags: return
  140. if result.typ != nil and result.typ.kind notin {tyTyped, tyVoid}:
  141. if implicitlyDiscardable(result):
  142. var n = newNodeI(nkDiscardStmt, result.info, 1)
  143. n[0] = result
  144. elif result.typ.kind != tyError and c.config.cmd != cmdInteractive:
  145. if result.typ.kind == tyNone:
  146. localError(c.config, result.info, "expression has no type: " &
  147. renderTree(result, {renderNoComments}))
  148. else:
  149. var n = result
  150. while n.kind in skipForDiscardable:
  151. if n.kind == nkTryStmt: n = n[0]
  152. else: n = n.lastSon
  153. var s = "expression '" & $n & "' is of type '" &
  154. result.typ.typeToString & "' and has to be used (or discarded)"
  155. if result.info.line != n.info.line or
  156. result.info.fileIndex != n.info.fileIndex:
  157. s.add "; start of expression here: " & c.config$result.info
  158. if result.typ.kind == tyProc:
  159. s.add "; for a function call use ()"
  160. localError(c.config, n.info, s)
  161. proc semIf(c: PContext, n: PNode; flags: TExprFlags; expectedType: PType = nil): PNode =
  162. result = n
  163. var typ = commonTypeBegin
  164. var expectedType = expectedType
  165. var hasElse = false
  166. for i in 0..<n.len:
  167. var it = n[i]
  168. if it.len == 2:
  169. openScope(c)
  170. it[0] = forceBool(c, semExprWithType(c, it[0], expectedType = getSysType(c.graph, n.info, tyBool)))
  171. it[1] = semExprBranch(c, it[1], flags, expectedType)
  172. typ = commonType(c, typ, it[1])
  173. expectedType = typ
  174. closeScope(c)
  175. elif it.len == 1:
  176. hasElse = true
  177. it[0] = semExprBranchScope(c, it[0], expectedType)
  178. typ = commonType(c, typ, it[0])
  179. expectedType = typ
  180. else: illFormedAst(it, c.config)
  181. if isEmptyType(typ) or typ.kind in {tyNil, tyUntyped} or
  182. (not hasElse and efInTypeof notin flags):
  183. for it in n: discardCheck(c, it.lastSon, flags)
  184. result.transitionSonsKind(nkIfStmt)
  185. # propagate any enforced VoidContext:
  186. if typ == c.enforceVoidContext: result.typ = c.enforceVoidContext
  187. else:
  188. for it in n:
  189. let j = it.len-1
  190. if not endsInNoReturn(it[j]):
  191. it[j] = fitNode(c, typ, it[j], it[j].info)
  192. result.transitionSonsKind(nkIfExpr)
  193. result.typ = typ
  194. proc semTry(c: PContext, n: PNode; flags: TExprFlags; expectedType: PType = nil): PNode =
  195. var check = initIntSet()
  196. template semExceptBranchType(typeNode: PNode): bool =
  197. # returns true if exception type is imported type
  198. let typ = semTypeNode(c, typeNode, nil).toObject()
  199. var isImported = false
  200. if isImportedException(typ, c.config):
  201. isImported = true
  202. elif not isException(typ):
  203. localError(c.config, typeNode.info, errExprCannotBeRaised)
  204. elif not isDefectOrCatchableError(typ):
  205. message(c.config, a.info, warnBareExcept, "catch a more precise Exception deriving from CatchableError or Defect.")
  206. if containsOrIncl(check, typ.id):
  207. localError(c.config, typeNode.info, errExceptionAlreadyHandled)
  208. typeNode = newNodeIT(nkType, typeNode.info, typ)
  209. isImported
  210. result = n
  211. checkMinSonsLen(n, 2, c.config)
  212. var typ = commonTypeBegin
  213. var expectedType = expectedType
  214. n[0] = semExprBranchScope(c, n[0], expectedType)
  215. typ = commonType(c, typ, n[0].typ)
  216. expectedType = typ
  217. var last = n.len - 1
  218. var catchAllExcepts = 0
  219. for i in 1..last:
  220. let a = n[i]
  221. checkMinSonsLen(a, 1, c.config)
  222. openScope(c)
  223. if a.kind == nkExceptBranch:
  224. if a.len == 2 and a[0].kind == nkBracket:
  225. # rewrite ``except [a, b, c]: body`` -> ```except a, b, c: body```
  226. a.sons[0..0] = move a[0].sons
  227. if a.len == 2 and a[0].isInfixAs():
  228. # support ``except Exception as ex: body``
  229. let isImported = semExceptBranchType(a[0][1])
  230. let symbol = newSymG(skLet, a[0][2], c)
  231. symbol.typ = if isImported: a[0][1].typ
  232. else: a[0][1].typ.toRef(c.idgen)
  233. addDecl(c, symbol)
  234. # Overwrite symbol in AST with the symbol in the symbol table.
  235. a[0][2] = newSymNode(symbol, a[0][2].info)
  236. elif a.len == 1:
  237. # count number of ``except: body`` blocks
  238. inc catchAllExcepts
  239. message(c.config, a.info, warnBareExcept,
  240. "The bare except clause is deprecated; use `except CatchableError:` instead")
  241. else:
  242. # support ``except KeyError, ValueError, ... : body``
  243. if catchAllExcepts > 0:
  244. # if ``except: body`` already encountered,
  245. # cannot be followed by a ``except KeyError, ... : body`` block
  246. inc catchAllExcepts
  247. var isNative, isImported: bool
  248. for j in 0..<a.len-1:
  249. let tmp = semExceptBranchType(a[j])
  250. if tmp: isImported = true
  251. else: isNative = true
  252. if isNative and isImported:
  253. localError(c.config, a[0].info, "Mix of imported and native exception types is not allowed in one except branch")
  254. elif a.kind == nkFinally:
  255. if i != n.len-1:
  256. localError(c.config, a.info, "Only one finally is allowed after all other branches")
  257. else:
  258. illFormedAst(n, c.config)
  259. if catchAllExcepts > 1:
  260. # if number of ``except: body`` blocks is greater than 1
  261. # or more specific exception follows a general except block, it is invalid
  262. localError(c.config, a.info, "Only one general except clause is allowed after more specific exceptions")
  263. # last child of an nkExcept/nkFinally branch is a statement:
  264. if a.kind != nkFinally:
  265. a[^1] = semExprBranchScope(c, a[^1], expectedType)
  266. typ = commonType(c, typ, a[^1])
  267. expectedType = typ
  268. else:
  269. a[^1] = semExprBranchScope(c, a[^1])
  270. dec last
  271. closeScope(c)
  272. if isEmptyType(typ) or typ.kind in {tyNil, tyUntyped}:
  273. discardCheck(c, n[0], flags)
  274. for i in 1..<n.len: discardCheck(c, n[i].lastSon, flags)
  275. if typ == c.enforceVoidContext:
  276. result.typ = c.enforceVoidContext
  277. else:
  278. if n.lastSon.kind == nkFinally: discardCheck(c, n.lastSon.lastSon, flags)
  279. n[0] = fitNode(c, typ, n[0], n[0].info)
  280. for i in 1..last:
  281. var it = n[i]
  282. let j = it.len-1
  283. if not endsInNoReturn(it[j]):
  284. it[j] = fitNode(c, typ, it[j], it[j].info)
  285. result.typ = typ
  286. proc fitRemoveHiddenConv(c: PContext, typ: PType, n: PNode): PNode =
  287. result = fitNode(c, typ, n, n.info)
  288. if result.kind in {nkHiddenStdConv, nkHiddenSubConv}:
  289. let r1 = result[1]
  290. if r1.kind in {nkCharLit..nkUInt64Lit} and typ.skipTypes(abstractRange).kind in {tyFloat..tyFloat128}:
  291. result = newFloatNode(nkFloatLit, BiggestFloat r1.intVal)
  292. result.info = n.info
  293. result.typ = typ
  294. if not floatRangeCheck(result.floatVal, typ):
  295. localError(c.config, n.info, errFloatToString % [$result.floatVal, typeToString(typ)])
  296. else:
  297. changeType(c, r1, typ, check=true)
  298. result = r1
  299. elif not sameType(result.typ, typ):
  300. changeType(c, result, typ, check=false)
  301. proc findShadowedVar(c: PContext, v: PSym): PSym =
  302. for scope in localScopesFrom(c, c.currentScope.parent):
  303. let shadowed = strTableGet(scope.symbols, v.name)
  304. if shadowed != nil and shadowed.kind in skLocalVars:
  305. return shadowed
  306. proc identWithin(n: PNode, s: PIdent): bool =
  307. for i in 0..n.safeLen-1:
  308. if identWithin(n[i], s): return true
  309. result = n.kind == nkSym and n.sym.name.id == s.id
  310. proc semIdentDef(c: PContext, n: PNode, kind: TSymKind, reportToNimsuggest = true): PSym =
  311. if isTopLevel(c):
  312. result = semIdentWithPragma(c, kind, n, {sfExported})
  313. incl(result.flags, sfGlobal)
  314. #if kind in {skVar, skLet}:
  315. # echo "global variable here ", n.info, " ", result.name.s
  316. else:
  317. result = semIdentWithPragma(c, kind, n, {})
  318. if result.owner.kind == skModule:
  319. incl(result.flags, sfGlobal)
  320. result.options = c.config.options
  321. proc getLineInfo(n: PNode): TLineInfo =
  322. case n.kind
  323. of nkPostfix:
  324. if len(n) > 1:
  325. return getLineInfo(n[1])
  326. of nkAccQuoted, nkPragmaExpr:
  327. if len(n) > 0:
  328. return getLineInfo(n[0])
  329. else:
  330. discard
  331. result = n.info
  332. let info = getLineInfo(n)
  333. if reportToNimsuggest:
  334. suggestSym(c.graph, info, result, c.graph.usageSym)
  335. proc checkNilable(c: PContext; v: PSym) =
  336. if {sfGlobal, sfImportc} * v.flags == {sfGlobal} and v.typ.requiresInit:
  337. if v.astdef.isNil:
  338. message(c.config, v.info, warnProveInit, v.name.s)
  339. elif tfNotNil in v.typ.flags and not v.astdef.typ.isNil and tfNotNil notin v.astdef.typ.flags:
  340. message(c.config, v.info, warnProveInit, v.name.s)
  341. #include liftdestructors
  342. proc addToVarSection(c: PContext; result: var PNode; n: PNode) =
  343. if result.kind != nkStmtList:
  344. result = makeStmtList(result)
  345. result.add n
  346. proc addToVarSection(c: PContext; result: var PNode; orig, identDefs: PNode) =
  347. if result.kind == nkStmtList:
  348. let o = copyNode(orig)
  349. o.add identDefs
  350. result.add o
  351. else:
  352. result.add identDefs
  353. proc isDiscardUnderscore(v: PSym): bool =
  354. if v.name.s == "_":
  355. v.flags.incl(sfGenSym)
  356. result = true
  357. proc semUsing(c: PContext; n: PNode): PNode =
  358. result = c.graph.emptyNode
  359. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "using")
  360. for i in 0..<n.len:
  361. var a = n[i]
  362. if c.config.cmd == cmdIdeTools: suggestStmt(c, a)
  363. if a.kind == nkCommentStmt: continue
  364. if a.kind notin {nkIdentDefs, nkVarTuple, nkConstDef}: illFormedAst(a, c.config)
  365. checkMinSonsLen(a, 3, c.config)
  366. if a[^2].kind != nkEmpty:
  367. let typ = semTypeNode(c, a[^2], nil)
  368. for j in 0..<a.len-2:
  369. let v = semIdentDef(c, a[j], skParam)
  370. styleCheckDef(c, v)
  371. onDef(a[j].info, v)
  372. v.typ = typ
  373. strTableIncl(c.signatures, v)
  374. else:
  375. localError(c.config, a.info, "'using' section must have a type")
  376. var def: PNode
  377. if a[^1].kind != nkEmpty:
  378. localError(c.config, a.info, "'using' sections cannot contain assignments")
  379. proc hasUnresolvedParams(n: PNode; flags: TExprFlags): bool =
  380. result = tfUnresolved in n.typ.flags
  381. when false:
  382. case n.kind
  383. of nkSym:
  384. result = isGenericRoutineStrict(n.sym)
  385. of nkSymChoices:
  386. for ch in n:
  387. if hasUnresolvedParams(ch, flags):
  388. return true
  389. result = false
  390. else:
  391. result = false
  392. if efOperand in flags:
  393. if tfUnresolved notin n.typ.flags:
  394. result = false
  395. proc makeDeref(n: PNode): PNode =
  396. var t = n.typ
  397. if t.kind in tyUserTypeClasses and t.isResolvedUserTypeClass:
  398. t = t.lastSon
  399. t = skipTypes(t, {tyGenericInst, tyAlias, tySink, tyOwned})
  400. result = n
  401. if t.kind in {tyVar, tyLent}:
  402. result = newNodeIT(nkHiddenDeref, n.info, t[0])
  403. result.add n
  404. t = skipTypes(t[0], {tyGenericInst, tyAlias, tySink, tyOwned})
  405. while t.kind in {tyPtr, tyRef}:
  406. var a = result
  407. let baseTyp = t.lastSon
  408. result = newNodeIT(nkHiddenDeref, n.info, baseTyp)
  409. result.add a
  410. t = skipTypes(baseTyp, {tyGenericInst, tyAlias, tySink, tyOwned})
  411. proc fillPartialObject(c: PContext; n: PNode; typ: PType) =
  412. if n.len == 2:
  413. let x = semExprWithType(c, n[0])
  414. let y = considerQuotedIdent(c, n[1])
  415. let obj = x.typ.skipTypes(abstractPtrs)
  416. if obj.kind == tyObject and tfPartial in obj.flags:
  417. let field = newSym(skField, getIdent(c.cache, y.s), nextSymId c.idgen, obj.sym, n[1].info)
  418. field.typ = skipIntLit(typ, c.idgen)
  419. field.position = obj.n.len
  420. obj.n.add newSymNode(field)
  421. n[0] = makeDeref x
  422. n[1] = newSymNode(field)
  423. n.typ = field.typ
  424. else:
  425. localError(c.config, n.info, "implicit object field construction " &
  426. "requires a .partial object, but got " & typeToString(obj))
  427. else:
  428. localError(c.config, n.info, "nkDotNode requires 2 children")
  429. proc setVarType(c: PContext; v: PSym, typ: PType) =
  430. if v.typ != nil and not sameTypeOrNil(v.typ, typ):
  431. localError(c.config, v.info, "inconsistent typing for reintroduced symbol '" &
  432. v.name.s & "': previous type was: " & typeToString(v.typ, preferDesc) &
  433. "; new type is: " & typeToString(typ, preferDesc))
  434. v.typ = typ
  435. proc isPossibleMacroPragma(c: PContext, it: PNode, key: PNode): bool =
  436. # make sure it's not a normal pragma, and calls an identifier
  437. # considerQuotedIdent below will fail on non-identifiers
  438. result = whichPragma(it) == wInvalid and key.kind in nkIdentKinds
  439. if result:
  440. # make sure it's not a user pragma
  441. let ident = considerQuotedIdent(c, key)
  442. result = strTableGet(c.userPragmas, ident) == nil
  443. if result:
  444. # make sure it's not a custom pragma
  445. var amb = false
  446. let sym = searchInScopes(c, ident, amb)
  447. result = sym == nil or sfCustomPragma notin sym.flags
  448. proc copyExcept(n: PNode, i: int): PNode =
  449. result = copyNode(n)
  450. for j in 0..<n.len:
  451. if j != i: result.add(n[j])
  452. proc semVarMacroPragma(c: PContext, a: PNode, n: PNode): PNode =
  453. # Mirrored with semProcAnnotation
  454. result = nil
  455. # a, b {.prag.}: int = 3 not allowed
  456. const lhsPos = 0
  457. if a.len == 3 and a[lhsPos].kind == nkPragmaExpr:
  458. var b = a[lhsPos]
  459. const
  460. namePos = 0
  461. pragmaPos = 1
  462. let pragmas = b[pragmaPos]
  463. for i in 0 ..< pragmas.len:
  464. let it = pragmas[i]
  465. let key = if it.kind in nkPragmaCallKinds and it.len >= 1: it[0] else: it
  466. if isPossibleMacroPragma(c, it, key):
  467. # we transform ``var p {.m, rest.}`` into ``m(do: var p {.rest.})`` and
  468. # let the semantic checker deal with it:
  469. var x = newNodeI(nkCall, key.info)
  470. x.add(key)
  471. if it.kind in nkPragmaCallKinds and it.len > 1:
  472. # pass pragma arguments to the macro too:
  473. for i in 1..<it.len:
  474. x.add(it[i])
  475. # Drop the pragma from the list, this prevents getting caught in endless
  476. # recursion when the nkCall is semanticized
  477. let oldExpr = a[lhsPos]
  478. let newPragmas = copyExcept(pragmas, i)
  479. if newPragmas.kind != nkEmpty and newPragmas.len == 0:
  480. a[lhsPos] = oldExpr[namePos]
  481. else:
  482. a[lhsPos] = copyNode(oldExpr)
  483. a[lhsPos].add(oldExpr[namePos])
  484. a[lhsPos].add(newPragmas)
  485. var unarySection = newNodeI(n.kind, a.info)
  486. unarySection.add(a)
  487. x.add(unarySection)
  488. # recursion assures that this works for multiple macro annotations too:
  489. var r = semOverloadedCall(c, x, x, {skMacro, skTemplate}, {efNoUndeclared})
  490. if r == nil:
  491. # Restore the old list of pragmas since we couldn't process this
  492. a[lhsPos] = oldExpr
  493. # No matching macro was found but there's always the possibility this may
  494. # be a .pragma. template instead
  495. continue
  496. doAssert r[0].kind == nkSym
  497. let m = r[0].sym
  498. case m.kind
  499. of skMacro: result = semMacroExpr(c, r, r, m, {})
  500. of skTemplate: result = semTemplateExpr(c, r, m, {})
  501. else:
  502. a[lhsPos] = oldExpr
  503. continue
  504. doAssert result != nil
  505. return result
  506. template isLocalSym(sym: PSym): bool =
  507. sym.kind in {skVar, skLet} and not
  508. ({sfGlobal, sfPure} * sym.flags != {} or
  509. sfCompileTime in sym.flags) or
  510. sym.kind in {skProc, skFunc, skIterator} and
  511. sfGlobal notin sym.flags
  512. template isLocalVarSym(n: PNode): bool =
  513. n.kind == nkSym and isLocalSym(n.sym)
  514. proc usesLocalVar(n: PNode): bool =
  515. for z in 1 ..< n.len:
  516. if n[z].isLocalVarSym:
  517. return true
  518. elif n[z].kind in nkCallKinds:
  519. if usesLocalVar(n[z]):
  520. return true
  521. proc globalVarInitCheck(c: PContext, n: PNode) =
  522. if n.isLocalVarSym or n.kind in nkCallKinds and usesLocalVar(n):
  523. localError(c.config, n.info, errCannotAssignToGlobal)
  524. proc makeVarTupleSection(c: PContext, n, a, def: PNode, typ: PType, symkind: TSymKind, origResult: var PNode): PNode =
  525. ## expand tuple unpacking assignments into new var/let/const section
  526. if typ.kind != tyTuple:
  527. localError(c.config, a.info, errXExpected, "tuple")
  528. elif a.len-2 != typ.len:
  529. localError(c.config, a.info, errWrongNumberOfVariables)
  530. var
  531. tmpTuple: PSym
  532. lastDef: PNode
  533. let defkind = if symkind == skConst: nkConstDef else: nkIdentDefs
  534. # temporary not needed if not const and RHS is tuple literal
  535. # const breaks with seqs without temporary
  536. let useTemp = def.kind notin {nkPar, nkTupleConstr} or symkind == skConst
  537. if useTemp:
  538. # use same symkind for compatibility with original section
  539. tmpTuple = newSym(symkind, getIdent(c.cache, "tmpTuple"), nextSymId c.idgen, getCurrOwner(c), n.info)
  540. tmpTuple.typ = typ
  541. tmpTuple.flags.incl(sfGenSym)
  542. lastDef = newNodeI(defkind, a.info)
  543. newSons(lastDef, 3)
  544. lastDef[0] = newSymNode(tmpTuple)
  545. # NOTE: at the moment this is always ast.emptyNode, see parser.nim
  546. lastDef[1] = a[^2]
  547. lastDef[2] = def
  548. tmpTuple.ast = lastDef
  549. addToVarSection(c, origResult, n, lastDef)
  550. result = newNodeI(n.kind, a.info)
  551. for j in 0..<a.len-2:
  552. let name = a[j]
  553. if useTemp and name.kind == nkIdent and name.ident.s == "_":
  554. # skip _ assignments if we are using a temp as they are already evaluated
  555. continue
  556. if name.kind == nkVarTuple:
  557. # nested tuple
  558. lastDef = newNodeI(nkVarTuple, name.info)
  559. newSons(lastDef, name.len)
  560. for k in 0..<name.len-2:
  561. lastDef[k] = name[k]
  562. else:
  563. lastDef = newNodeI(defkind, name.info)
  564. newSons(lastDef, 3)
  565. lastDef[0] = name
  566. lastDef[^2] = c.graph.emptyNode
  567. if useTemp:
  568. lastDef[^1] = newTreeIT(nkBracketExpr, name.info, typ[j], newSymNode(tmpTuple), newIntNode(nkIntLit, j))
  569. else:
  570. var val = def[j]
  571. if val.kind == nkExprColonExpr: val = val[1]
  572. lastDef[^1] = val
  573. result.add(lastDef)
  574. proc semVarOrLet(c: PContext, n: PNode, symkind: TSymKind): PNode =
  575. var b: PNode
  576. result = copyNode(n)
  577. for i in 0..<n.len:
  578. var a = n[i]
  579. if c.config.cmd == cmdIdeTools: suggestStmt(c, a)
  580. if a.kind == nkCommentStmt: continue
  581. if a.kind notin {nkIdentDefs, nkVarTuple}: illFormedAst(a, c.config)
  582. checkMinSonsLen(a, 3, c.config)
  583. b = semVarMacroPragma(c, a, n)
  584. if b != nil:
  585. addToVarSection(c, result, b)
  586. continue
  587. var typ: PType = nil
  588. if a[^2].kind != nkEmpty:
  589. typ = semTypeNode(c, a[^2], nil)
  590. var typFlags: TTypeAllowedFlags
  591. var def: PNode = c.graph.emptyNode
  592. if a[^1].kind != nkEmpty:
  593. def = semExprWithType(c, a[^1], {efTypeAllowed}, typ)
  594. if def.kind == nkSym and def.sym.kind in {skTemplate, skMacro}:
  595. typFlags.incl taIsTemplateOrMacro
  596. elif def.typ.kind == tyTypeDesc and c.p.owner.kind != skMacro:
  597. typFlags.incl taProcContextIsNotMacro
  598. if typ != nil:
  599. if typ.isMetaType:
  600. def = inferWithMetatype(c, typ, def)
  601. typ = def.typ
  602. else:
  603. # BUGFIX: ``fitNode`` is needed here!
  604. # check type compatibility between def.typ and typ
  605. def = fitNodeConsiderViewType(c, typ, def, def.info)
  606. #changeType(def.skipConv, typ, check=true)
  607. else:
  608. typ = def.typ.skipTypes({tyStatic, tySink}).skipIntLit(c.idgen)
  609. if typ.kind in tyUserTypeClasses and typ.isResolvedUserTypeClass:
  610. typ = typ.lastSon
  611. if hasEmpty(typ):
  612. localError(c.config, def.info, errCannotInferTypeOfTheLiteral % typ.kind.toHumanStr)
  613. elif typ.kind == tyProc and def.kind == nkSym and isGenericRoutine(def.sym.ast):
  614. # tfUnresolved in typ.flags:
  615. localError(c.config, def.info, errProcHasNoConcreteType % def.renderTree)
  616. when false:
  617. # XXX This typing rule is neither documented nor complete enough to
  618. # justify it. Instead use the newer 'unowned x' until we figured out
  619. # a more general solution.
  620. if symkind == skVar and typ.kind == tyOwned and def.kind notin nkCallKinds:
  621. # special type inference rule: 'var it = ownedPointer' is turned
  622. # into an unowned pointer.
  623. typ = typ.lastSon
  624. # this can only happen for errornous var statements:
  625. if typ == nil: continue
  626. if c.matchedConcept != nil:
  627. typFlags.incl taConcept
  628. typeAllowedCheck(c, a.info, typ, symkind, typFlags)
  629. var tup = skipTypes(typ, {tyGenericInst, tyAlias, tySink})
  630. if a.kind == nkVarTuple:
  631. # generate new section from tuple unpacking and embed it into this one
  632. let assignments = makeVarTupleSection(c, n, a, def, tup, symkind, result)
  633. let resSection = semVarOrLet(c, assignments, symkind)
  634. for resDef in resSection:
  635. addToVarSection(c, result, n, resDef)
  636. else:
  637. if tup.kind == tyTuple and def.kind in {nkPar, nkTupleConstr} and
  638. a.len > 3:
  639. # var a, b = (1, 2)
  640. message(c.config, a.info, warnEachIdentIsTuple)
  641. for j in 0..<a.len-2:
  642. if a[j].kind == nkDotExpr:
  643. fillPartialObject(c, a[j], typ)
  644. addToVarSection(c, result, n, a)
  645. continue
  646. var v = semIdentDef(c, a[j], symkind, false)
  647. styleCheckDef(c, v)
  648. onDef(a[j].info, v)
  649. if sfGenSym notin v.flags:
  650. if not isDiscardUnderscore(v): addInterfaceDecl(c, v)
  651. else:
  652. if v.owner == nil: v.owner = c.p.owner
  653. when oKeepVariableNames:
  654. if c.inUnrolledContext > 0: v.flags.incl(sfShadowed)
  655. else:
  656. let shadowed = findShadowedVar(c, v)
  657. if shadowed != nil:
  658. shadowed.flags.incl(sfShadowed)
  659. if shadowed.kind == skResult and sfGenSym notin v.flags:
  660. message(c.config, a.info, warnResultShadowed)
  661. if def.kind != nkEmpty:
  662. if sfThread in v.flags: localError(c.config, def.info, errThreadvarCannotInit)
  663. setVarType(c, v, typ)
  664. # this is needed for the evaluation pass, guard checking
  665. # and custom pragmas:
  666. b = newNodeI(nkIdentDefs, a.info)
  667. if importantComments(c.config):
  668. # keep documentation information:
  669. b.comment = a.comment
  670. # postfix not generated here (to generate, get rid of it in transf)
  671. if a[j].kind == nkPragmaExpr:
  672. var p = newNodeI(nkPragmaExpr, a.info)
  673. p.add newSymNode(v)
  674. p.add a[j][1]
  675. b.add p
  676. else:
  677. b.add newSymNode(v)
  678. # keep type desc for doc generator
  679. b.add a[^2]
  680. b.add copyTree(def)
  681. addToVarSection(c, result, n, b)
  682. v.ast = b
  683. if def.kind == nkEmpty:
  684. let actualType = v.typ.skipTypes({tyGenericInst, tyAlias,
  685. tyUserTypeClassInst})
  686. if actualType.kind in {tyObject, tyDistinct} and
  687. actualType.requiresInit:
  688. defaultConstructionError(c, v.typ, v.info)
  689. else:
  690. checkNilable(c, v)
  691. # allow let to not be initialised if imported from C:
  692. if v.kind == skLet and sfImportc notin v.flags and (strictDefs notin c.features or not isLocalSym(v)):
  693. localError(c.config, a.info, errLetNeedsInit)
  694. if sfCompileTime in v.flags:
  695. var x = newNodeI(result.kind, v.info)
  696. x.add result[i]
  697. vm.setupCompileTimeVar(c.module, c.idgen, c.graph, x)
  698. if v.flags * {sfGlobal, sfThread} == {sfGlobal}:
  699. message(c.config, v.info, hintGlobalVar)
  700. if {sfGlobal, sfPure} <= v.flags:
  701. globalVarInitCheck(c, def)
  702. suggestSym(c.graph, v.info, v, c.graph.usageSym)
  703. proc semConst(c: PContext, n: PNode): PNode =
  704. result = copyNode(n)
  705. inc c.inStaticContext
  706. var b: PNode
  707. for i in 0..<n.len:
  708. var a = n[i]
  709. if c.config.cmd == cmdIdeTools: suggestStmt(c, a)
  710. if a.kind == nkCommentStmt: continue
  711. if a.kind notin {nkConstDef, nkVarTuple}: illFormedAst(a, c.config)
  712. checkMinSonsLen(a, 3, c.config)
  713. b = semVarMacroPragma(c, a, n)
  714. if b != nil:
  715. addToVarSection(c, result, b)
  716. continue
  717. var typ: PType = nil
  718. if a[^2].kind != nkEmpty:
  719. typ = semTypeNode(c, a[^2], nil)
  720. var typFlags: TTypeAllowedFlags
  721. # don't evaluate here since the type compatibility check below may add a converter
  722. var def = semExprWithType(c, a[^1], {efTypeAllowed}, typ)
  723. if def.kind == nkSym and def.sym.kind in {skTemplate, skMacro}:
  724. typFlags.incl taIsTemplateOrMacro
  725. elif def.typ.kind == tyTypeDesc and c.p.owner.kind != skMacro:
  726. typFlags.incl taProcContextIsNotMacro
  727. # check type compatibility between def.typ and typ:
  728. if typ != nil:
  729. if typ.isMetaType:
  730. def = inferWithMetatype(c, typ, def)
  731. typ = def.typ
  732. else:
  733. def = fitRemoveHiddenConv(c, typ, def)
  734. else:
  735. typ = def.typ
  736. # evaluate the node
  737. def = semConstExpr(c, def)
  738. if def == nil:
  739. localError(c.config, a[^1].info, errConstExprExpected)
  740. continue
  741. if def.kind != nkNilLit:
  742. if c.matchedConcept != nil:
  743. typFlags.incl taConcept
  744. typeAllowedCheck(c, a.info, typ, skConst, typFlags)
  745. if a.kind == nkVarTuple:
  746. # generate new section from tuple unpacking and embed it into this one
  747. let assignments = makeVarTupleSection(c, n, a, def, typ, skConst, result)
  748. let resSection = semConst(c, assignments)
  749. for resDef in resSection:
  750. addToVarSection(c, result, n, resDef)
  751. else:
  752. for j in 0..<a.len-2:
  753. var v = semIdentDef(c, a[j], skConst)
  754. if sfGenSym notin v.flags: addInterfaceDecl(c, v)
  755. elif v.owner == nil: v.owner = getCurrOwner(c)
  756. styleCheckDef(c, v)
  757. onDef(a[j].info, v)
  758. setVarType(c, v, typ)
  759. when false:
  760. v.ast = def # no need to copy
  761. b = newNodeI(nkConstDef, a.info)
  762. if importantComments(c.config): b.comment = a.comment
  763. # postfix not generated here (to generate, get rid of it in transf)
  764. if a[j].kind == nkPragmaExpr:
  765. var p = newNodeI(nkPragmaExpr, a.info)
  766. p.add newSymNode(v)
  767. p.add a[j][1].copyTree
  768. b.add p
  769. else:
  770. b.add newSymNode(v)
  771. b.add a[1]
  772. b.add copyTree(def)
  773. v.ast = b
  774. addToVarSection(c, result, n, b)
  775. dec c.inStaticContext
  776. include semfields
  777. proc symForVar(c: PContext, n: PNode): PSym =
  778. let m = if n.kind == nkPragmaExpr: n[0] else: n
  779. result = newSymG(skForVar, m, c)
  780. styleCheckDef(c, result)
  781. onDef(n.info, result)
  782. if n.kind == nkPragmaExpr:
  783. pragma(c, result, n[1], forVarPragmas)
  784. proc semForVars(c: PContext, n: PNode; flags: TExprFlags): PNode =
  785. result = n
  786. let iterBase = n[^2].typ
  787. var iter = skipTypes(iterBase, {tyGenericInst, tyAlias, tySink, tyOwned})
  788. var iterAfterVarLent = iter.skipTypes({tyGenericInst, tyAlias, tyLent, tyVar})
  789. # n.len == 3 means that there is one for loop variable
  790. # and thus no tuple unpacking:
  791. if iterAfterVarLent.kind == tyEmpty:
  792. localError(c.config, n[^2].info, "cannot infer element type of $1" %
  793. renderTree(n[^2], {renderNoComments}))
  794. if iterAfterVarLent.kind != tyTuple or n.len == 3:
  795. if n.len == 3:
  796. if n[0].kind == nkVarTuple:
  797. if n[0].len-1 != iterAfterVarLent.len:
  798. return localErrorNode(c, n, n[0].info, errWrongNumberOfVariables)
  799. for i in 0..<n[0].len-1:
  800. var v = symForVar(c, n[0][i])
  801. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  802. case iter.kind
  803. of tyVar, tyLent:
  804. v.typ = newTypeS(iter.kind, c)
  805. v.typ.add iterAfterVarLent[i]
  806. if tfVarIsPtr in iter.flags:
  807. v.typ.flags.incl tfVarIsPtr
  808. else:
  809. v.typ = iter[i]
  810. n[0][i] = newSymNode(v)
  811. if sfGenSym notin v.flags and not isDiscardUnderscore(v): addDecl(c, v)
  812. elif v.owner == nil: v.owner = getCurrOwner(c)
  813. else:
  814. var v = symForVar(c, n[0])
  815. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  816. # BUGFIX: don't use `iter` here as that would strip away
  817. # the ``tyGenericInst``! See ``tests/compile/tgeneric.nim``
  818. # for an example:
  819. v.typ = iterBase
  820. n[0] = newSymNode(v)
  821. if sfGenSym notin v.flags and not isDiscardUnderscore(v): addDecl(c, v)
  822. elif v.owner == nil: v.owner = getCurrOwner(c)
  823. else:
  824. localError(c.config, n.info, errWrongNumberOfVariables)
  825. elif n.len-2 != iterAfterVarLent.len:
  826. localError(c.config, n.info, errWrongNumberOfVariables)
  827. else:
  828. for i in 0..<n.len - 2:
  829. if n[i].kind == nkVarTuple:
  830. var mutable = false
  831. var isLent = false
  832. case iter[i].kind
  833. of tyVar:
  834. mutable = true
  835. iter[i] = iter[i].skipTypes({tyVar})
  836. of tyLent:
  837. isLent = true
  838. iter[i] = iter[i].skipTypes({tyLent})
  839. else: discard
  840. if n[i].len-1 != iter[i].len:
  841. localError(c.config, n[i].info, errWrongNumberOfVariables)
  842. for j in 0..<n[i].len-1:
  843. var v = symForVar(c, n[i][j])
  844. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  845. if mutable:
  846. v.typ = newTypeS(tyVar, c)
  847. v.typ.add iter[i][j]
  848. elif isLent:
  849. v.typ = newTypeS(tyLent, c)
  850. v.typ.add iter[i][j]
  851. else:
  852. v.typ = iter[i][j]
  853. n[i][j] = newSymNode(v)
  854. if not isDiscardUnderscore(v): addDecl(c, v)
  855. elif v.owner == nil: v.owner = getCurrOwner(c)
  856. else:
  857. var v = symForVar(c, n[i])
  858. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  859. case iter.kind
  860. of tyVar, tyLent:
  861. v.typ = newTypeS(iter.kind, c)
  862. v.typ.add iterAfterVarLent[i]
  863. if tfVarIsPtr in iter.flags:
  864. v.typ.flags.incl tfVarIsPtr
  865. else:
  866. v.typ = iter[i]
  867. n[i] = newSymNode(v)
  868. if sfGenSym notin v.flags:
  869. if not isDiscardUnderscore(v): addDecl(c, v)
  870. elif v.owner == nil: v.owner = getCurrOwner(c)
  871. inc(c.p.nestedLoopCounter)
  872. let oldBreakInLoop = c.p.breakInLoop
  873. c.p.breakInLoop = true
  874. openScope(c)
  875. n[^1] = semExprBranch(c, n[^1], flags)
  876. if efInTypeof notin flags:
  877. discardCheck(c, n[^1], flags)
  878. closeScope(c)
  879. c.p.breakInLoop = oldBreakInLoop
  880. dec(c.p.nestedLoopCounter)
  881. proc implicitIterator(c: PContext, it: string, arg: PNode): PNode =
  882. result = newNodeI(nkCall, arg.info)
  883. result.add(newIdentNode(getIdent(c.cache, it), arg.info))
  884. if arg.typ != nil and arg.typ.kind in {tyVar, tyLent}:
  885. result.add newDeref(arg)
  886. else:
  887. result.add arg
  888. result = semExprNoDeref(c, result, {efWantIterator})
  889. proc isTrivalStmtExpr(n: PNode): bool =
  890. for i in 0..<n.len-1:
  891. if n[i].kind notin {nkEmpty, nkCommentStmt}:
  892. return false
  893. result = true
  894. proc handleStmtMacro(c: PContext; n, selector: PNode; magicType: string;
  895. flags: TExprFlags): PNode =
  896. if selector.kind in nkCallKinds:
  897. # we transform
  898. # n := for a, b, c in m(x, y, z): Y
  899. # to
  900. # m(n)
  901. let maType = magicsys.getCompilerProc(c.graph, magicType)
  902. if maType == nil: return
  903. let headSymbol = selector[0]
  904. var o: TOverloadIter
  905. var match: PSym = nil
  906. var symx = initOverloadIter(o, c, headSymbol)
  907. while symx != nil:
  908. if symx.kind in {skTemplate, skMacro}:
  909. if symx.typ.len == 2 and symx.typ[1] == maType.typ:
  910. if match == nil:
  911. match = symx
  912. else:
  913. localError(c.config, n.info, errAmbiguousCallXYZ % [
  914. getProcHeader(c.config, match),
  915. getProcHeader(c.config, symx), $selector])
  916. symx = nextOverloadIter(o, c, headSymbol)
  917. if match == nil: return
  918. var callExpr = newNodeI(nkCall, n.info)
  919. callExpr.add newSymNode(match)
  920. callExpr.add n
  921. case match.kind
  922. of skMacro: result = semMacroExpr(c, callExpr, callExpr, match, flags)
  923. of skTemplate: result = semTemplateExpr(c, callExpr, match, flags)
  924. else: result = nil
  925. proc handleForLoopMacro(c: PContext; n: PNode; flags: TExprFlags): PNode =
  926. result = handleStmtMacro(c, n, n[^2], "ForLoopStmt", flags)
  927. proc handleCaseStmtMacro(c: PContext; n: PNode; flags: TExprFlags): PNode =
  928. # n[0] has been sem'checked and has a type. We use this to resolve
  929. # '`case`(n[0])' but then we pass 'n' to the `case` macro. This seems to
  930. # be the best solution.
  931. var toResolve = newNodeI(nkCall, n.info)
  932. toResolve.add newIdentNode(getIdent(c.cache, "case"), n.info)
  933. toResolve.add n[0]
  934. var errors: CandidateErrors
  935. var r = resolveOverloads(c, toResolve, toResolve, {skTemplate, skMacro}, {efNoDiagnostics},
  936. errors, false)
  937. if r.state == csMatch:
  938. var match = r.calleeSym
  939. markUsed(c, n[0].info, match)
  940. onUse(n[0].info, match)
  941. # but pass 'n' to the `case` macro, not 'n[0]':
  942. r.call[1] = n
  943. let toExpand = semResolvedCall(c, r, r.call, {})
  944. case match.kind
  945. of skMacro: result = semMacroExpr(c, toExpand, toExpand, match, flags)
  946. of skTemplate: result = semTemplateExpr(c, toExpand, match, flags)
  947. else: result = errorNode(c, n[0])
  948. elif r.state == csNoMatch:
  949. result = errorNode(c, n[0])
  950. if result.kind == nkEmpty:
  951. localError(c.config, n[0].info, errSelectorMustBeOfCertainTypes)
  952. # this would be the perfectly consistent solution with 'for loop macros',
  953. # but it kinda sucks for pattern matching as the matcher is not attached to
  954. # a type then:
  955. when false:
  956. result = handleStmtMacro(c, n, n[0], "CaseStmt")
  957. proc semFor(c: PContext, n: PNode; flags: TExprFlags): PNode =
  958. checkMinSonsLen(n, 3, c.config)
  959. result = handleForLoopMacro(c, n, flags)
  960. if result != nil: return result
  961. openScope(c)
  962. result = n
  963. n[^2] = semExprNoDeref(c, n[^2], {efWantIterator})
  964. var call = n[^2]
  965. if call.kind == nkStmtListExpr and (isTrivalStmtExpr(call) or (call.lastSon.kind in nkCallKinds and call.lastSon[0].sym.kind == skIterator)):
  966. call = call.lastSon
  967. n[^2] = call
  968. let isCallExpr = call.kind in nkCallKinds
  969. if isCallExpr and call[0].kind == nkSym and
  970. call[0].sym.magic in {mFields, mFieldPairs, mOmpParFor}:
  971. if call[0].sym.magic == mOmpParFor:
  972. result = semForVars(c, n, flags)
  973. result.transitionSonsKind(nkParForStmt)
  974. else:
  975. result = semForFields(c, n, call[0].sym.magic)
  976. elif isCallExpr and isClosureIterator(call[0].typ.skipTypes(abstractInst)):
  977. # first class iterator:
  978. result = semForVars(c, n, flags)
  979. elif not isCallExpr or call[0].kind != nkSym or
  980. call[0].sym.kind != skIterator:
  981. if n.len == 3:
  982. n[^2] = implicitIterator(c, "items", n[^2])
  983. elif n.len == 4:
  984. n[^2] = implicitIterator(c, "pairs", n[^2])
  985. else:
  986. localError(c.config, n[^2].info, "iterator within for loop context expected")
  987. result = semForVars(c, n, flags)
  988. else:
  989. result = semForVars(c, n, flags)
  990. # propagate any enforced VoidContext:
  991. if n[^1].typ == c.enforceVoidContext:
  992. result.typ = c.enforceVoidContext
  993. elif efInTypeof in flags:
  994. result.typ = result.lastSon.typ
  995. closeScope(c)
  996. proc semCase(c: PContext, n: PNode; flags: TExprFlags; expectedType: PType = nil): PNode =
  997. result = n
  998. checkMinSonsLen(n, 2, c.config)
  999. openScope(c)
  1000. pushCaseContext(c, n)
  1001. n[0] = semExprWithType(c, n[0])
  1002. var chckCovered = false
  1003. var covered: Int128 = toInt128(0)
  1004. var typ = commonTypeBegin
  1005. var expectedType = expectedType
  1006. var hasElse = false
  1007. let caseTyp = skipTypes(n[0].typ, abstractVar-{tyTypeDesc})
  1008. const shouldChckCovered = {tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt64, tyBool}
  1009. case caseTyp.kind
  1010. of shouldChckCovered:
  1011. chckCovered = true
  1012. of tyRange:
  1013. if skipTypes(caseTyp[0], abstractInst).kind in shouldChckCovered:
  1014. chckCovered = true
  1015. of tyFloat..tyFloat128, tyString, tyCstring, tyError:
  1016. discard
  1017. else:
  1018. popCaseContext(c)
  1019. closeScope(c)
  1020. return handleCaseStmtMacro(c, n, flags)
  1021. template invalidOrderOfBranches(n: PNode) =
  1022. localError(c.config, n.info, "invalid order of case branches")
  1023. break
  1024. for i in 1..<n.len:
  1025. setCaseContextIdx(c, i)
  1026. var x = n[i]
  1027. when defined(nimsuggest):
  1028. if c.config.ideCmd == ideSug and exactEquals(c.config.m.trackPos, x.info) and caseTyp.kind == tyEnum:
  1029. suggestEnum(c, x, caseTyp)
  1030. case x.kind
  1031. of nkOfBranch:
  1032. if hasElse: invalidOrderOfBranches(x)
  1033. checkMinSonsLen(x, 2, c.config)
  1034. semCaseBranch(c, n, x, i, covered)
  1035. var last = x.len-1
  1036. x[last] = semExprBranchScope(c, x[last], expectedType)
  1037. typ = commonType(c, typ, x[last])
  1038. expectedType = typ
  1039. of nkElifBranch:
  1040. if hasElse: invalidOrderOfBranches(x)
  1041. chckCovered = false
  1042. checkSonsLen(x, 2, c.config)
  1043. openScope(c)
  1044. x[0] = forceBool(c, semExprWithType(c, x[0], expectedType = getSysType(c.graph, n.info, tyBool)))
  1045. x[1] = semExprBranch(c, x[1], expectedType = expectedType)
  1046. typ = commonType(c, typ, x[1])
  1047. expectedType = typ
  1048. closeScope(c)
  1049. of nkElse:
  1050. checkSonsLen(x, 1, c.config)
  1051. x[0] = semExprBranchScope(c, x[0], expectedType)
  1052. typ = commonType(c, typ, x[0])
  1053. expectedType = typ
  1054. if (chckCovered and covered == toCover(c, n[0].typ)) or hasElse:
  1055. message(c.config, x.info, warnUnreachableElse)
  1056. hasElse = true
  1057. chckCovered = false
  1058. else:
  1059. illFormedAst(x, c.config)
  1060. if chckCovered:
  1061. if covered == toCover(c, n[0].typ):
  1062. hasElse = true
  1063. elif n[0].typ.skipTypes(abstractRange).kind in {tyEnum, tyChar}:
  1064. localError(c.config, n.info, "not all cases are covered; missing: $1" %
  1065. formatMissingEnums(c, n))
  1066. else:
  1067. localError(c.config, n.info, "not all cases are covered")
  1068. popCaseContext(c)
  1069. closeScope(c)
  1070. if isEmptyType(typ) or typ.kind in {tyNil, tyUntyped} or
  1071. (not hasElse and efInTypeof notin flags):
  1072. for i in 1..<n.len: discardCheck(c, n[i].lastSon, flags)
  1073. # propagate any enforced VoidContext:
  1074. if typ == c.enforceVoidContext:
  1075. result.typ = c.enforceVoidContext
  1076. else:
  1077. for i in 1..<n.len:
  1078. var it = n[i]
  1079. let j = it.len-1
  1080. if not endsInNoReturn(it[j]):
  1081. it[j] = fitNode(c, typ, it[j], it[j].info)
  1082. result.typ = typ
  1083. proc semRaise(c: PContext, n: PNode): PNode =
  1084. result = n
  1085. checkSonsLen(n, 1, c.config)
  1086. if n[0].kind != nkEmpty:
  1087. n[0] = semExprWithType(c, n[0])
  1088. var typ = n[0].typ
  1089. if not isImportedException(typ, c.config):
  1090. typ = typ.skipTypes({tyAlias, tyGenericInst, tyOwned})
  1091. if typ.kind != tyRef:
  1092. localError(c.config, n.info, errExprCannotBeRaised)
  1093. if typ.len > 0 and not isException(typ.lastSon):
  1094. localError(c.config, n.info, "raised object of type $1 does not inherit from Exception" % typeToString(typ))
  1095. proc addGenericParamListToScope(c: PContext, n: PNode) =
  1096. if n.kind != nkGenericParams: illFormedAst(n, c.config)
  1097. for i in 0..<n.len:
  1098. var a = n[i]
  1099. if a.kind == nkSym: addDecl(c, a.sym)
  1100. else: illFormedAst(a, c.config)
  1101. proc typeSectionTypeName(c: PContext; n: PNode): PNode =
  1102. if n.kind == nkPragmaExpr:
  1103. if n.len == 0: illFormedAst(n, c.config)
  1104. result = n[0]
  1105. else:
  1106. result = n
  1107. if result.kind != nkSym: illFormedAst(n, c.config)
  1108. proc typeDefLeftSidePass(c: PContext, typeSection: PNode, i: int) =
  1109. let typeDef = typeSection[i]
  1110. checkSonsLen(typeDef, 3, c.config)
  1111. var name = typeDef[0]
  1112. var s: PSym
  1113. if name.kind == nkDotExpr and typeDef[2].kind == nkObjectTy:
  1114. let pkgName = considerQuotedIdent(c, name[0])
  1115. let typName = considerQuotedIdent(c, name[1])
  1116. let pkg = c.graph.packageSyms.strTableGet(pkgName)
  1117. if pkg.isNil or pkg.kind != skPackage:
  1118. localError(c.config, name.info, "unknown package name: " & pkgName.s)
  1119. else:
  1120. let typsym = c.graph.packageTypes.strTableGet(typName)
  1121. if typsym.isNil:
  1122. s = semIdentDef(c, name[1], skType)
  1123. onDef(name[1].info, s)
  1124. s.typ = newTypeS(tyObject, c)
  1125. s.typ.sym = s
  1126. s.flags.incl sfForward
  1127. c.graph.packageTypes.strTableAdd s
  1128. addInterfaceDecl(c, s)
  1129. elif typsym.kind == skType and sfForward in typsym.flags:
  1130. s = typsym
  1131. addInterfaceDecl(c, s)
  1132. # PRTEMP no onDef here?
  1133. else:
  1134. localError(c.config, name.info, typsym.name.s & " is not a type that can be forwarded")
  1135. s = typsym
  1136. else:
  1137. s = semIdentDef(c, name, skType)
  1138. onDef(name.info, s)
  1139. s.typ = newTypeS(tyForward, c)
  1140. s.typ.sym = s # process pragmas:
  1141. if name.kind == nkPragmaExpr:
  1142. let rewritten = applyTypeSectionPragmas(c, name[1], typeDef)
  1143. if rewritten != nil:
  1144. case rewritten.kind
  1145. of nkTypeDef:
  1146. typeSection[i] = rewritten
  1147. of nkTypeSection:
  1148. typeSection.sons[i .. i] = rewritten.sons
  1149. else: illFormedAst(rewritten, c.config)
  1150. typeDefLeftSidePass(c, typeSection, i)
  1151. return
  1152. pragma(c, s, name[1], typePragmas)
  1153. if sfForward in s.flags:
  1154. # check if the symbol already exists:
  1155. let pkg = c.module.owner
  1156. if not isTopLevel(c) or pkg.isNil:
  1157. localError(c.config, name.info, "only top level types in a package can be 'package'")
  1158. else:
  1159. let typsym = c.graph.packageTypes.strTableGet(s.name)
  1160. if typsym != nil:
  1161. if sfForward notin typsym.flags or sfNoForward notin typsym.flags:
  1162. typeCompleted(typsym)
  1163. typsym.info = s.info
  1164. else:
  1165. localError(c.config, name.info, "cannot complete type '" & s.name.s & "' twice; " &
  1166. "previous type completion was here: " & c.config$typsym.info)
  1167. s = typsym
  1168. # add it here, so that recursive types are possible:
  1169. if sfGenSym notin s.flags: addInterfaceDecl(c, s)
  1170. elif s.owner == nil: s.owner = getCurrOwner(c)
  1171. if name.kind == nkPragmaExpr:
  1172. typeDef[0][0] = newSymNode(s)
  1173. else:
  1174. typeDef[0] = newSymNode(s)
  1175. proc typeSectionLeftSidePass(c: PContext, n: PNode) =
  1176. # process the symbols on the left side for the whole type section, before
  1177. # we even look at the type definitions on the right
  1178. var i = 0
  1179. while i < n.len: # n may grow due to type pragma macros
  1180. var a = n[i]
  1181. when defined(nimsuggest):
  1182. if c.config.cmd == cmdIdeTools:
  1183. inc c.inTypeContext
  1184. suggestStmt(c, a)
  1185. dec c.inTypeContext
  1186. case a.kind
  1187. of nkCommentStmt: discard
  1188. of nkTypeDef: typeDefLeftSidePass(c, n, i)
  1189. else: illFormedAst(a, c.config)
  1190. inc i
  1191. proc checkCovariantParamsUsages(c: PContext; genericType: PType) =
  1192. var body = genericType[^1]
  1193. proc traverseSubTypes(c: PContext; t: PType): bool =
  1194. template error(msg) = localError(c.config, genericType.sym.info, msg)
  1195. result = false
  1196. template subresult(r) =
  1197. let sub = r
  1198. result = result or sub
  1199. case t.kind
  1200. of tyGenericParam:
  1201. t.flags.incl tfWeakCovariant
  1202. return true
  1203. of tyObject:
  1204. for field in t.n:
  1205. subresult traverseSubTypes(c, field.typ)
  1206. of tyArray:
  1207. return traverseSubTypes(c, t[1])
  1208. of tyProc:
  1209. for subType in t.sons:
  1210. if subType != nil:
  1211. subresult traverseSubTypes(c, subType)
  1212. if result:
  1213. error("non-invariant type param used in a proc type: " & $t)
  1214. of tySequence:
  1215. return traverseSubTypes(c, t[0])
  1216. of tyGenericInvocation:
  1217. let targetBody = t[0]
  1218. for i in 1..<t.len:
  1219. let param = t[i]
  1220. if param.kind == tyGenericParam:
  1221. if tfCovariant in param.flags:
  1222. let formalFlags = targetBody[i-1].flags
  1223. if tfCovariant notin formalFlags:
  1224. error("covariant param '" & param.sym.name.s &
  1225. "' used in a non-covariant position")
  1226. elif tfWeakCovariant in formalFlags:
  1227. param.flags.incl tfWeakCovariant
  1228. result = true
  1229. elif tfContravariant in param.flags:
  1230. let formalParam = targetBody[i-1].sym
  1231. if tfContravariant notin formalParam.typ.flags:
  1232. error("contravariant param '" & param.sym.name.s &
  1233. "' used in a non-contravariant position")
  1234. result = true
  1235. else:
  1236. subresult traverseSubTypes(c, param)
  1237. of tyAnd, tyOr, tyNot, tyStatic, tyBuiltInTypeClass, tyCompositeTypeClass:
  1238. error("non-invariant type parameters cannot be used with types such '" & $t & "'")
  1239. of tyUserTypeClass, tyUserTypeClassInst:
  1240. error("non-invariant type parameters are not supported in concepts")
  1241. of tyTuple:
  1242. for fieldType in t.sons:
  1243. subresult traverseSubTypes(c, fieldType)
  1244. of tyPtr, tyRef, tyVar, tyLent:
  1245. if t.base.kind == tyGenericParam: return true
  1246. return traverseSubTypes(c, t.base)
  1247. of tyDistinct, tyAlias, tySink, tyOwned:
  1248. return traverseSubTypes(c, t.lastSon)
  1249. of tyGenericInst:
  1250. internalAssert c.config, false
  1251. else:
  1252. discard
  1253. discard traverseSubTypes(c, body)
  1254. proc typeSectionRightSidePass(c: PContext, n: PNode) =
  1255. for i in 0..<n.len:
  1256. var a = n[i]
  1257. if a.kind == nkCommentStmt: continue
  1258. if a.kind != nkTypeDef: illFormedAst(a, c.config)
  1259. checkSonsLen(a, 3, c.config)
  1260. let name = typeSectionTypeName(c, a[0])
  1261. var s = name.sym
  1262. if s.magic == mNone and a[2].kind == nkEmpty:
  1263. localError(c.config, a.info, errImplOfXexpected % s.name.s)
  1264. if s.magic != mNone: processMagicType(c, s)
  1265. let oldFlags = s.typ.flags
  1266. if a[1].kind != nkEmpty:
  1267. # We have a generic type declaration here. In generic types,
  1268. # symbol lookup needs to be done here.
  1269. openScope(c)
  1270. pushOwner(c, s)
  1271. if s.magic == mNone: s.typ.kind = tyGenericBody
  1272. # XXX for generic type aliases this is not correct! We need the
  1273. # underlying Id really:
  1274. #
  1275. # type
  1276. # TGObj[T] = object
  1277. # TAlias[T] = TGObj[T]
  1278. #
  1279. s.typ.n = semGenericParamList(c, a[1], s.typ)
  1280. a[1] = s.typ.n
  1281. s.typ.size = -1 # could not be computed properly
  1282. # we fill it out later. For magic generics like 'seq', it won't be filled
  1283. # so we use tyNone instead of nil to not crash for strange conversions
  1284. # like: mydata.seq
  1285. rawAddSon(s.typ, newTypeS(tyNone, c))
  1286. s.ast = a
  1287. inc c.inGenericContext
  1288. var body = semTypeNode(c, a[2], s.typ)
  1289. dec c.inGenericContext
  1290. if body != nil:
  1291. body.sym = s
  1292. body.size = -1 # could not be computed properly
  1293. if body.kind == tyObject:
  1294. # add flags applied to generic type to object (nominal) type
  1295. incl(body.flags, oldFlags)
  1296. # {.inheritable, final.} is already disallowed, but
  1297. # object might have been assumed to be final
  1298. if tfInheritable in oldFlags and tfFinal in body.flags:
  1299. excl(body.flags, tfFinal)
  1300. s.typ[^1] = body
  1301. if tfCovariant in s.typ.flags:
  1302. checkCovariantParamsUsages(c, s.typ)
  1303. # XXX: This is a temporary limitation:
  1304. # The codegen currently produces various failures with
  1305. # generic imported types that have fields, but we need
  1306. # the fields specified in order to detect weak covariance.
  1307. # The proper solution is to teach the codegen how to handle
  1308. # such types, because this would offer various interesting
  1309. # possibilities such as instantiating C++ generic types with
  1310. # garbage collected Nim types.
  1311. if sfImportc in s.flags:
  1312. var body = s.typ.lastSon
  1313. if body.kind == tyObject:
  1314. # erases all declared fields
  1315. body.n.sons = @[]
  1316. popOwner(c)
  1317. closeScope(c)
  1318. elif a[2].kind != nkEmpty:
  1319. # process the type's body:
  1320. pushOwner(c, s)
  1321. var t = semTypeNode(c, a[2], s.typ)
  1322. if s.typ == nil:
  1323. s.typ = t
  1324. elif t != s.typ and (s.typ == nil or s.typ.kind != tyAlias):
  1325. # this can happen for e.g. tcan_alias_specialised_generic:
  1326. assignType(s.typ, t)
  1327. #debug s.typ
  1328. s.ast = a
  1329. popOwner(c)
  1330. # If the right hand side expression was a macro call we replace it with
  1331. # its evaluated result here so that we don't execute it once again in the
  1332. # final pass
  1333. if a[2].kind in nkCallKinds:
  1334. incl a[2].flags, nfSem # bug #10548
  1335. if sfExportc in s.flags and s.typ.kind == tyAlias:
  1336. localError(c.config, name.info, "{.exportc.} not allowed for type aliases")
  1337. if tfBorrowDot in s.typ.flags and s.typ.skipTypes({tyGenericBody}).kind != tyDistinct:
  1338. excl s.typ.flags, tfBorrowDot
  1339. localError(c.config, name.info, "only a 'distinct' type can borrow `.`")
  1340. let aa = a[2]
  1341. if aa.kind in {nkRefTy, nkPtrTy} and aa.len == 1 and
  1342. aa[0].kind == nkObjectTy:
  1343. # give anonymous object a dummy symbol:
  1344. var st = s.typ
  1345. if st.kind == tyGenericBody: st = st.lastSon
  1346. internalAssert c.config, st.kind in {tyPtr, tyRef}
  1347. internalAssert c.config, st.lastSon.sym == nil
  1348. incl st.flags, tfRefsAnonObj
  1349. let objTy = st.lastSon
  1350. # add flags for `ref object` etc to underlying `object`
  1351. incl(objTy.flags, oldFlags)
  1352. # {.inheritable, final.} is already disallowed, but
  1353. # object might have been assumed to be final
  1354. if tfInheritable in oldFlags and tfFinal in objTy.flags:
  1355. excl(objTy.flags, tfFinal)
  1356. let obj = newSym(skType, getIdent(c.cache, s.name.s & ":ObjectType"),
  1357. nextSymId c.idgen, getCurrOwner(c), s.info)
  1358. obj.flags.incl sfGeneratedType
  1359. let symNode = newSymNode(obj)
  1360. obj.ast = a.shallowCopy
  1361. case a[0].kind
  1362. of nkSym: obj.ast[0] = symNode
  1363. of nkPragmaExpr:
  1364. obj.ast[0] = a[0].shallowCopy
  1365. obj.ast[0][0] = symNode
  1366. obj.ast[0][1] = a[0][1]
  1367. else: assert(false)
  1368. obj.ast[1] = a[1]
  1369. obj.ast[2] = a[2][0]
  1370. if sfPure in s.flags:
  1371. obj.flags.incl sfPure
  1372. obj.typ = objTy
  1373. objTy.sym = obj
  1374. proc checkForMetaFields(c: PContext; n: PNode) =
  1375. proc checkMeta(c: PContext; n: PNode; t: PType) =
  1376. if t != nil and t.isMetaType and tfGenericTypeParam notin t.flags:
  1377. if t.kind == tyBuiltInTypeClass and t.len == 1 and t[0].kind == tyProc:
  1378. localError(c.config, n.info, ("'$1' is not a concrete type; " &
  1379. "for a callback without parameters use 'proc()'") % t.typeToString)
  1380. else:
  1381. localError(c.config, n.info, errTIsNotAConcreteType % t.typeToString)
  1382. if n.isNil: return
  1383. case n.kind
  1384. of nkRecList, nkRecCase:
  1385. for s in n: checkForMetaFields(c, s)
  1386. of nkOfBranch, nkElse:
  1387. checkForMetaFields(c, n.lastSon)
  1388. of nkSym:
  1389. let t = n.sym.typ
  1390. case t.kind
  1391. of tySequence, tySet, tyArray, tyOpenArray, tyVar, tyLent, tyPtr, tyRef,
  1392. tyProc, tyGenericInvocation, tyGenericInst, tyAlias, tySink, tyOwned:
  1393. let start = ord(t.kind in {tyGenericInvocation, tyGenericInst})
  1394. for i in start..<t.len:
  1395. checkMeta(c, n, t[i])
  1396. else:
  1397. checkMeta(c, n, t)
  1398. else:
  1399. internalAssert c.config, false
  1400. proc typeSectionFinalPass(c: PContext, n: PNode) =
  1401. for i in 0..<n.len:
  1402. var a = n[i]
  1403. if a.kind == nkCommentStmt: continue
  1404. let name = typeSectionTypeName(c, a[0])
  1405. var s = name.sym
  1406. # check the style here after the pragmas have been processed:
  1407. styleCheckDef(c, s)
  1408. # compute the type's size and check for illegal recursions:
  1409. if a[1].kind == nkEmpty:
  1410. var x = a[2]
  1411. if x.kind in nkCallKinds and nfSem in x.flags:
  1412. discard "already semchecked, see line marked with bug #10548"
  1413. else:
  1414. while x.kind in {nkStmtList, nkStmtListExpr} and x.len > 0:
  1415. x = x.lastSon
  1416. # we need the 'safeSkipTypes' here because illegally recursive types
  1417. # can enter at this point, see bug #13763
  1418. if x.kind notin {nkObjectTy, nkDistinctTy, nkEnumTy, nkEmpty} and
  1419. s.typ.safeSkipTypes(abstractPtrs).kind notin {tyObject, tyEnum}:
  1420. # type aliases are hard:
  1421. var t = semTypeNode(c, x, nil)
  1422. assert t != nil
  1423. if s.typ != nil and s.typ.kind notin {tyAlias, tySink}:
  1424. if t.kind in {tyProc, tyGenericInst} and not t.isMetaType:
  1425. assignType(s.typ, t)
  1426. s.typ.itemId = t.itemId
  1427. elif t.kind in {tyObject, tyEnum, tyDistinct}:
  1428. assert s.typ != nil
  1429. assignType(s.typ, t)
  1430. s.typ.itemId = t.itemId # same id
  1431. checkConstructedType(c.config, s.info, s.typ)
  1432. if s.typ.kind in {tyObject, tyTuple} and not s.typ.n.isNil:
  1433. checkForMetaFields(c, s.typ.n)
  1434. # fix bug #5170, bug #17162, bug #15526: ensure locally scoped types get a unique name:
  1435. if s.typ.kind in {tyEnum, tyRef, tyObject} and not isTopLevel(c):
  1436. incl(s.flags, sfGenSym)
  1437. #instAllTypeBoundOp(c, n.info)
  1438. proc semAllTypeSections(c: PContext; n: PNode): PNode =
  1439. proc gatherStmts(c: PContext; n: PNode; result: PNode) {.nimcall.} =
  1440. case n.kind
  1441. of nkIncludeStmt:
  1442. for i in 0..<n.len:
  1443. var f = checkModuleName(c.config, n[i])
  1444. if f != InvalidFileIdx:
  1445. if containsOrIncl(c.includedFiles, f.int):
  1446. localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
  1447. else:
  1448. let code = c.graph.includeFileCallback(c.graph, c.module, f)
  1449. gatherStmts c, code, result
  1450. excl(c.includedFiles, f.int)
  1451. of nkStmtList:
  1452. for i in 0..<n.len:
  1453. gatherStmts(c, n[i], result)
  1454. of nkTypeSection:
  1455. incl n.flags, nfSem
  1456. typeSectionLeftSidePass(c, n)
  1457. result.add n
  1458. else:
  1459. result.add n
  1460. result = newNodeI(nkStmtList, n.info)
  1461. gatherStmts(c, n, result)
  1462. template rec(name) =
  1463. for i in 0..<result.len:
  1464. if result[i].kind == nkTypeSection:
  1465. name(c, result[i])
  1466. rec typeSectionRightSidePass
  1467. rec typeSectionFinalPass
  1468. when false:
  1469. # too beautiful to delete:
  1470. template rec(name; setbit=false) =
  1471. proc `name rec`(c: PContext; n: PNode) {.nimcall.} =
  1472. if n.kind == nkTypeSection:
  1473. when setbit: incl n.flags, nfSem
  1474. name(c, n)
  1475. elif n.kind == nkStmtList:
  1476. for i in 0..<n.len:
  1477. `name rec`(c, n[i])
  1478. `name rec`(c, n)
  1479. rec typeSectionLeftSidePass, true
  1480. rec typeSectionRightSidePass
  1481. rec typeSectionFinalPass
  1482. proc semTypeSection(c: PContext, n: PNode): PNode =
  1483. ## Processes a type section. This must be done in separate passes, in order
  1484. ## to allow the type definitions in the section to reference each other
  1485. ## without regard for the order of their definitions.
  1486. if sfNoForward notin c.module.flags or nfSem notin n.flags:
  1487. inc c.inTypeContext
  1488. typeSectionLeftSidePass(c, n)
  1489. typeSectionRightSidePass(c, n)
  1490. typeSectionFinalPass(c, n)
  1491. dec c.inTypeContext
  1492. result = n
  1493. proc semParamList(c: PContext, n, genericParams: PNode, s: PSym) =
  1494. s.typ = semProcTypeNode(c, n, genericParams, nil, s.kind)
  1495. proc addParams(c: PContext, n: PNode, kind: TSymKind) =
  1496. for i in 1..<n.len:
  1497. if n[i].kind == nkSym: addParamOrResult(c, n[i].sym, kind)
  1498. else: illFormedAst(n, c.config)
  1499. proc semBorrow(c: PContext, n: PNode, s: PSym) =
  1500. # search for the correct alias:
  1501. var b = searchForBorrowProc(c, c.currentScope.parent, s)
  1502. if b != nil:
  1503. # store the alias:
  1504. n[bodyPos] = newSymNode(b)
  1505. # Carry over the original symbol magic, this is necessary in order to ensure
  1506. # the semantic pass is correct
  1507. s.magic = b.magic
  1508. if b.typ != nil and b.typ.len > 0:
  1509. s.typ.n[0] = b.typ.n[0]
  1510. s.typ.flags = b.typ.flags
  1511. else:
  1512. localError(c.config, n.info, errNoSymbolToBorrowFromFound)
  1513. proc swapResult(n: PNode, sRes: PSym, dNode: PNode) =
  1514. ## Swap nodes that are (skResult) symbols to d(estination)Node.
  1515. for i in 0..<n.safeLen:
  1516. if n[i].kind == nkSym and n[i].sym == sRes:
  1517. n[i] = dNode
  1518. swapResult(n[i], sRes, dNode)
  1519. proc addResult(c: PContext, n: PNode, t: PType, owner: TSymKind) =
  1520. template genResSym(s) =
  1521. var s = newSym(skResult, getIdent(c.cache, "result"), nextSymId c.idgen,
  1522. getCurrOwner(c), n.info)
  1523. s.typ = t
  1524. incl(s.flags, sfUsed)
  1525. if owner == skMacro or t != nil:
  1526. if n.len > resultPos and n[resultPos] != nil:
  1527. if n[resultPos].sym.kind != skResult:
  1528. localError(c.config, n.info, "incorrect result proc symbol")
  1529. if n[resultPos].sym.owner != getCurrOwner(c):
  1530. # re-write result with new ownership, and re-write the proc accordingly
  1531. let sResSym = n[resultPos].sym
  1532. genResSym(s)
  1533. n[resultPos] = newSymNode(s)
  1534. swapResult(n, sResSym, n[resultPos])
  1535. c.p.resultSym = n[resultPos].sym
  1536. else:
  1537. genResSym(s)
  1538. c.p.resultSym = s
  1539. n.add newSymNode(c.p.resultSym)
  1540. addParamOrResult(c, c.p.resultSym, owner)
  1541. proc semProcAnnotation(c: PContext, prc: PNode;
  1542. validPragmas: TSpecialWords): PNode =
  1543. # Mirrored with semVarMacroPragma
  1544. var n = prc[pragmasPos]
  1545. if n == nil or n.kind == nkEmpty: return
  1546. for i in 0..<n.len:
  1547. let it = n[i]
  1548. let key = if it.kind in nkPragmaCallKinds and it.len >= 1: it[0] else: it
  1549. if isPossibleMacroPragma(c, it, key):
  1550. # we transform ``proc p {.m, rest.}`` into ``m(do: proc p {.rest.})`` and
  1551. # let the semantic checker deal with it:
  1552. var x = newNodeI(nkCall, key.info)
  1553. x.add(key)
  1554. if it.kind in nkPragmaCallKinds and it.len > 1:
  1555. # pass pragma arguments to the macro too:
  1556. for i in 1..<it.len:
  1557. x.add(it[i])
  1558. # Drop the pragma from the list, this prevents getting caught in endless
  1559. # recursion when the nkCall is semanticized
  1560. prc[pragmasPos] = copyExcept(n, i)
  1561. if prc[pragmasPos].kind != nkEmpty and prc[pragmasPos].len == 0:
  1562. prc[pragmasPos] = c.graph.emptyNode
  1563. x.add(prc)
  1564. # recursion assures that this works for multiple macro annotations too:
  1565. var r = semOverloadedCall(c, x, x, {skMacro, skTemplate}, {efNoUndeclared})
  1566. if r == nil:
  1567. # Restore the old list of pragmas since we couldn't process this
  1568. prc[pragmasPos] = n
  1569. # No matching macro was found but there's always the possibility this may
  1570. # be a .pragma. template instead
  1571. continue
  1572. doAssert r[0].kind == nkSym
  1573. let m = r[0].sym
  1574. case m.kind
  1575. of skMacro: result = semMacroExpr(c, r, r, m, {})
  1576. of skTemplate: result = semTemplateExpr(c, r, m, {})
  1577. else:
  1578. prc[pragmasPos] = n
  1579. continue
  1580. doAssert result != nil
  1581. return result
  1582. proc semInferredLambda(c: PContext, pt: TIdTable, n: PNode): PNode =
  1583. ## used for resolving 'auto' in lambdas based on their callsite
  1584. var n = n
  1585. let original = n[namePos].sym
  1586. let s = original #copySym(original, false)
  1587. #incl(s.flags, sfFromGeneric)
  1588. #s.owner = original
  1589. n = replaceTypesInBody(c, pt, n, original)
  1590. result = n
  1591. s.ast = result
  1592. n[namePos].sym = s
  1593. n[genericParamsPos] = c.graph.emptyNode
  1594. # for LL we need to avoid wrong aliasing
  1595. let params = copyTree n.typ.n
  1596. n[paramsPos] = params
  1597. s.typ = n.typ
  1598. for i in 1..<params.len:
  1599. if params[i].typ.kind in {tyTypeDesc, tyGenericParam,
  1600. tyFromExpr}+tyTypeClasses:
  1601. localError(c.config, params[i].info, "cannot infer type of parameter: " &
  1602. params[i].sym.name.s)
  1603. #params[i].sym.owner = s
  1604. openScope(c)
  1605. pushOwner(c, s)
  1606. addParams(c, params, skProc)
  1607. pushProcCon(c, s)
  1608. addResult(c, n, n.typ[0], skProc)
  1609. s.ast[bodyPos] = hloBody(c, semProcBody(c, n[bodyPos], n.typ[0]))
  1610. trackProc(c, s, s.ast[bodyPos])
  1611. popProcCon(c)
  1612. popOwner(c)
  1613. closeScope(c)
  1614. if optOwnedRefs in c.config.globalOptions and result.typ != nil:
  1615. result.typ = makeVarType(c, result.typ, tyOwned)
  1616. # alternative variant (not quite working):
  1617. # var prc = arg[0].sym
  1618. # let inferred = c.semGenerateInstance(c, prc, m.bindings, arg.info)
  1619. # result = inferred.ast
  1620. # result.kind = arg.kind
  1621. proc activate(c: PContext, n: PNode) =
  1622. # XXX: This proc is part of my plan for getting rid of
  1623. # forward declarations. stay tuned.
  1624. when false:
  1625. # well for now it breaks code ...
  1626. case n.kind
  1627. of nkLambdaKinds:
  1628. discard semLambda(c, n, {})
  1629. of nkCallKinds:
  1630. for i in 1..<n.len: activate(c, n[i])
  1631. else:
  1632. discard
  1633. proc maybeAddResult(c: PContext, s: PSym, n: PNode) =
  1634. if s.kind == skMacro:
  1635. let resultType = sysTypeFromName(c.graph, n.info, "NimNode")
  1636. addResult(c, n, resultType, s.kind)
  1637. elif s.typ[0] != nil and not isInlineIterator(s.typ):
  1638. addResult(c, n, s.typ[0], s.kind)
  1639. proc canonType(c: PContext, t: PType): PType =
  1640. if t.kind == tySequence:
  1641. result = c.graph.sysTypes[tySequence]
  1642. else:
  1643. result = t
  1644. proc prevDestructor(c: PContext; prevOp: PSym; obj: PType; info: TLineInfo) =
  1645. var msg = "cannot bind another '" & prevOp.name.s & "' to: " & typeToString(obj)
  1646. if sfOverriden notin prevOp.flags:
  1647. msg.add "; previous declaration was constructed here implicitly: " & (c.config $ prevOp.info)
  1648. else:
  1649. msg.add "; previous declaration was here: " & (c.config $ prevOp.info)
  1650. localError(c.config, info, errGenerated, msg)
  1651. proc whereToBindTypeHook(c: PContext; t: PType): PType =
  1652. result = t
  1653. while true:
  1654. if result.kind in {tyGenericBody, tyGenericInst}: result = result.lastSon
  1655. elif result.kind == tyGenericInvocation: result = result[0]
  1656. else: break
  1657. if result.kind in {tyObject, tyDistinct, tySequence, tyString}:
  1658. result = canonType(c, result)
  1659. proc bindTypeHook(c: PContext; s: PSym; n: PNode; op: TTypeAttachedOp) =
  1660. let t = s.typ
  1661. var noError = false
  1662. let cond = if op in {attachedDestructor, attachedWasMoved}:
  1663. t.len == 2 and t[0] == nil and t[1].kind == tyVar
  1664. elif op == attachedTrace:
  1665. t.len == 3 and t[0] == nil and t[1].kind == tyVar and t[2].kind == tyPointer
  1666. else:
  1667. t.len >= 2 and t[0] == nil
  1668. if cond:
  1669. var obj = t[1].skipTypes({tyVar})
  1670. while true:
  1671. incl(obj.flags, tfHasAsgn)
  1672. if obj.kind in {tyGenericBody, tyGenericInst}: obj = obj.lastSon
  1673. elif obj.kind == tyGenericInvocation: obj = obj[0]
  1674. else: break
  1675. if obj.kind in {tyObject, tyDistinct, tySequence, tyString}:
  1676. obj = canonType(c, obj)
  1677. let ao = getAttachedOp(c.graph, obj, op)
  1678. if ao == s:
  1679. discard "forward declared destructor"
  1680. elif ao.isNil and tfCheckedForDestructor notin obj.flags:
  1681. setAttachedOp(c.graph, c.module.position, obj, op, s)
  1682. else:
  1683. prevDestructor(c, ao, obj, n.info)
  1684. noError = true
  1685. if obj.owner.getModule != s.getModule:
  1686. localError(c.config, n.info, errGenerated,
  1687. "type bound operation `" & s.name.s & "` can be defined only in the same module with its type (" & obj.typeToString() & ")")
  1688. if not noError and sfSystemModule notin s.owner.flags:
  1689. if op == attachedTrace:
  1690. localError(c.config, n.info, errGenerated,
  1691. "signature for '=trace' must be proc[T: object](x: var T; env: pointer)")
  1692. else:
  1693. localError(c.config, n.info, errGenerated,
  1694. "signature for '" & s.name.s & "' must be proc[T: object](x: var T)")
  1695. incl(s.flags, sfUsed)
  1696. incl(s.flags, sfOverriden)
  1697. proc semOverride(c: PContext, s: PSym, n: PNode) =
  1698. let name = s.name.s.normalize
  1699. case name
  1700. of "=destroy":
  1701. bindTypeHook(c, s, n, attachedDestructor)
  1702. of "deepcopy", "=deepcopy":
  1703. if s.typ.len == 2 and
  1704. s.typ[1].skipTypes(abstractInst).kind in {tyRef, tyPtr} and
  1705. sameType(s.typ[1], s.typ[0]):
  1706. # Note: we store the deepCopy in the base of the pointer to mitigate
  1707. # the problem that pointers are structural types:
  1708. var t = s.typ[1].skipTypes(abstractInst).lastSon.skipTypes(abstractInst)
  1709. while true:
  1710. if t.kind == tyGenericBody: t = t.lastSon
  1711. elif t.kind == tyGenericInvocation: t = t[0]
  1712. else: break
  1713. if t.kind in {tyObject, tyDistinct, tyEnum, tySequence, tyString}:
  1714. if getAttachedOp(c.graph, t, attachedDeepCopy).isNil:
  1715. setAttachedOp(c.graph, c.module.position, t, attachedDeepCopy, s)
  1716. else:
  1717. localError(c.config, n.info, errGenerated,
  1718. "cannot bind another 'deepCopy' to: " & typeToString(t))
  1719. else:
  1720. localError(c.config, n.info, errGenerated,
  1721. "cannot bind 'deepCopy' to: " & typeToString(t))
  1722. if t.owner.getModule != s.getModule:
  1723. localError(c.config, n.info, errGenerated,
  1724. "type bound operation `" & name & "` can be defined only in the same module with its type (" & t.typeToString() & ")")
  1725. else:
  1726. localError(c.config, n.info, errGenerated,
  1727. "signature for 'deepCopy' must be proc[T: ptr|ref](x: T): T")
  1728. incl(s.flags, sfUsed)
  1729. incl(s.flags, sfOverriden)
  1730. of "=", "=copy", "=sink":
  1731. if s.magic == mAsgn: return
  1732. incl(s.flags, sfUsed)
  1733. incl(s.flags, sfOverriden)
  1734. if name == "=":
  1735. message(c.config, n.info, warnDeprecated, "Overriding `=` hook is deprecated; Override `=copy` hook instead")
  1736. let t = s.typ
  1737. if t.len == 3 and t[0] == nil and t[1].kind == tyVar:
  1738. var obj = t[1][0]
  1739. while true:
  1740. incl(obj.flags, tfHasAsgn)
  1741. if obj.kind == tyGenericBody: obj = obj.lastSon
  1742. elif obj.kind == tyGenericInvocation: obj = obj[0]
  1743. else: break
  1744. var objB = t[2]
  1745. while true:
  1746. if objB.kind == tyGenericBody: objB = objB.lastSon
  1747. elif objB.kind in {tyGenericInvocation, tyGenericInst}:
  1748. objB = objB[0]
  1749. else: break
  1750. if obj.kind in {tyObject, tyDistinct, tySequence, tyString} and sameType(obj, objB):
  1751. # attach these ops to the canonical tySequence
  1752. obj = canonType(c, obj)
  1753. #echo "ATTACHING TO ", obj.id, " ", s.name.s, " ", cast[int](obj)
  1754. let k = if name == "=" or name == "=copy": attachedAsgn else: attachedSink
  1755. let ao = getAttachedOp(c.graph, obj, k)
  1756. if ao == s:
  1757. discard "forward declared op"
  1758. elif ao.isNil and tfCheckedForDestructor notin obj.flags:
  1759. setAttachedOp(c.graph, c.module.position, obj, k, s)
  1760. else:
  1761. prevDestructor(c, ao, obj, n.info)
  1762. if obj.owner.getModule != s.getModule:
  1763. localError(c.config, n.info, errGenerated,
  1764. "type bound operation `" & name & "` can be defined only in the same module with its type (" & obj.typeToString() & ")")
  1765. return
  1766. if sfSystemModule notin s.owner.flags:
  1767. localError(c.config, n.info, errGenerated,
  1768. "signature for '" & s.name.s & "' must be proc[T: object](x: var T; y: T)")
  1769. of "=trace":
  1770. if s.magic != mTrace:
  1771. bindTypeHook(c, s, n, attachedTrace)
  1772. of "=wasmoved":
  1773. if s.magic != mWasMoved:
  1774. bindTypeHook(c, s, n, attachedWasMoved)
  1775. else:
  1776. if sfOverriden in s.flags:
  1777. localError(c.config, n.info, errGenerated,
  1778. "'destroy' or 'deepCopy' expected for 'override'")
  1779. proc cursorInProcAux(conf: ConfigRef; n: PNode): bool =
  1780. if inCheckpoint(n.info, conf.m.trackPos) != cpNone: return true
  1781. for i in 0..<n.safeLen:
  1782. if cursorInProcAux(conf, n[i]): return true
  1783. proc cursorInProc(conf: ConfigRef; n: PNode): bool =
  1784. if n.info.fileIndex == conf.m.trackPos.fileIndex:
  1785. result = cursorInProcAux(conf, n)
  1786. proc hasObjParam(s: PSym): bool =
  1787. var t = s.typ
  1788. for col in 1..<t.len:
  1789. if skipTypes(t[col], skipPtrs).kind == tyObject:
  1790. return true
  1791. proc finishMethod(c: PContext, s: PSym) =
  1792. if hasObjParam(s):
  1793. methodDef(c.graph, c.idgen, s)
  1794. proc semMethodPrototype(c: PContext; s: PSym; n: PNode) =
  1795. if s.isGenericRoutine:
  1796. let tt = s.typ
  1797. var foundObj = false
  1798. # we start at 1 for now so that tparsecombnum continues to compile.
  1799. # XXX Revisit this problem later.
  1800. for col in 1..<tt.len:
  1801. let t = tt[col]
  1802. if t != nil and t.kind == tyGenericInvocation:
  1803. var x = skipTypes(t[0], {tyVar, tyLent, tyPtr, tyRef, tyGenericInst,
  1804. tyGenericInvocation, tyGenericBody,
  1805. tyAlias, tySink, tyOwned})
  1806. if x.kind == tyObject and t.len-1 == n[genericParamsPos].len:
  1807. foundObj = true
  1808. addMethodToGeneric(c.graph, c.module.position, x, col, s)
  1809. message(c.config, n.info, warnDeprecated, "generic methods are deprecated")
  1810. #if not foundObj:
  1811. # message(c.config, n.info, warnDeprecated, "generic method not attachable to object type is deprecated")
  1812. else:
  1813. # why check for the body? bug #2400 has none. Checking for sfForward makes
  1814. # no sense either.
  1815. # and result[bodyPos].kind != nkEmpty:
  1816. if hasObjParam(s):
  1817. methodDef(c.graph, c.idgen, s)
  1818. else:
  1819. localError(c.config, n.info, "'method' needs a parameter that has an object type")
  1820. proc semProcAux(c: PContext, n: PNode, kind: TSymKind,
  1821. validPragmas: TSpecialWords, flags: TExprFlags = {}): PNode =
  1822. result = semProcAnnotation(c, n, validPragmas)
  1823. if result != nil: return result
  1824. result = n
  1825. checkMinSonsLen(n, bodyPos + 1, c.config)
  1826. let isAnon = n[namePos].kind == nkEmpty
  1827. var s: PSym
  1828. case n[namePos].kind
  1829. of nkEmpty:
  1830. s = newSym(kind, c.cache.idAnon, nextSymId c.idgen, c.getCurrOwner, n.info)
  1831. s.flags.incl sfUsed
  1832. n[namePos] = newSymNode(s)
  1833. of nkSym:
  1834. s = n[namePos].sym
  1835. s.owner = c.getCurrOwner
  1836. else:
  1837. s = semIdentDef(c, n[namePos], kind)
  1838. n[namePos] = newSymNode(s)
  1839. when false:
  1840. # disable for now
  1841. if sfNoForward in c.module.flags and
  1842. sfSystemModule notin c.module.flags:
  1843. addInterfaceOverloadableSymAt(c, c.currentScope, s)
  1844. s.flags.incl sfForward
  1845. return
  1846. assert s.kind in skProcKinds
  1847. s.ast = n
  1848. s.options = c.config.options
  1849. #s.scope = c.currentScope
  1850. # before compiling the proc params & body, set as current the scope
  1851. # where the proc was declared
  1852. let declarationScope = c.currentScope
  1853. pushOwner(c, s)
  1854. openScope(c)
  1855. # process parameters:
  1856. # generic parameters, parameters, and also the implicit generic parameters
  1857. # within are analysed. This is often the entirety of their semantic analysis
  1858. # but later we will have to do a check for forward declarations, which can by
  1859. # way of pragmas, default params, and so on invalidate this parsing.
  1860. # Nonetheless, we need to carry out this analysis to perform the search for a
  1861. # potential forward declaration.
  1862. setGenericParamsMisc(c, n)
  1863. if n[paramsPos].kind != nkEmpty:
  1864. semParamList(c, n[paramsPos], n[genericParamsPos], s)
  1865. else:
  1866. s.typ = newProcType(c, n.info)
  1867. if n[genericParamsPos].safeLen == 0:
  1868. # if there exist no explicit or implicit generic parameters, then this is
  1869. # at most a nullary generic (generic with no type params). Regardless of
  1870. # whether it's a nullary generic or non-generic, we restore the original.
  1871. # In the case of `nkEmpty` it's non-generic and an empty `nkGeneircParams`
  1872. # is a nullary generic.
  1873. #
  1874. # Remarks about nullary generics vs non-generics:
  1875. # The difference between a non-generic and nullary generic is minor in
  1876. # most cases but there are subtle and significant differences as well.
  1877. # Due to instantiation that generic procs go through, a static echo in the
  1878. # body of a nullary generic will not be executed immediately, as it's
  1879. # instantiated and not immediately evaluated.
  1880. n[genericParamsPos] = n[miscPos][1]
  1881. n[miscPos] = c.graph.emptyNode
  1882. if tfTriggersCompileTime in s.typ.flags: incl(s.flags, sfCompileTime)
  1883. if n[patternPos].kind != nkEmpty:
  1884. n[patternPos] = semPattern(c, n[patternPos], s)
  1885. if s.kind == skIterator:
  1886. s.typ.flags.incl(tfIterator)
  1887. elif s.kind == skFunc:
  1888. incl(s.flags, sfNoSideEffect)
  1889. incl(s.typ.flags, tfNoSideEffect)
  1890. var (proto, comesFromShadowScope) =
  1891. if isAnon: (nil, false)
  1892. else: searchForProc(c, declarationScope, s)
  1893. if proto == nil and sfForward in s.flags and n[bodyPos].kind != nkEmpty:
  1894. ## In cases such as a macro generating a proc with a gensymmed name we
  1895. ## know `searchForProc` will not find it and sfForward will be set. In
  1896. ## such scenarios the sym is shared between forward declaration and we
  1897. ## can treat the `s` as the proto.
  1898. ## To differentiate between that happening and a macro just returning a
  1899. ## forward declaration that has been typed before we check if the body
  1900. ## is not empty. This has the sideeffect of allowing multiple forward
  1901. ## declarations if they share the same sym.
  1902. ## See the "doubly-typed forward decls" case in tmacros_issues.nim
  1903. proto = s
  1904. let hasProto = proto != nil
  1905. # set the default calling conventions
  1906. case s.kind
  1907. of skIterator:
  1908. if s.typ.callConv != ccClosure:
  1909. s.typ.callConv = if isAnon: ccClosure else: ccInline
  1910. of skMacro, skTemplate:
  1911. # we don't bother setting calling conventions for macros and templates
  1912. discard
  1913. else:
  1914. # NB: procs with a forward decl have theirs determined by the forward decl
  1915. if not hasProto:
  1916. # in this case we're either a forward declaration or we're an impl without
  1917. # a forward decl. We set the calling convention or will be set during
  1918. # pragma analysis further down.
  1919. s.typ.callConv = lastOptionEntry(c).defaultCC
  1920. if not hasProto and sfGenSym notin s.flags: #and not isAnon:
  1921. if s.kind in OverloadableSyms:
  1922. addInterfaceOverloadableSymAt(c, declarationScope, s)
  1923. else:
  1924. addInterfaceDeclAt(c, declarationScope, s)
  1925. pragmaCallable(c, s, n, validPragmas)
  1926. if not hasProto:
  1927. implicitPragmas(c, s, n.info, validPragmas)
  1928. if n[pragmasPos].kind != nkEmpty and sfBorrow notin s.flags:
  1929. setEffectsForProcType(c.graph, s.typ, n[pragmasPos], s)
  1930. s.typ.flags.incl tfEffectSystemWorkaround
  1931. # To ease macro generation that produce forwarded .async procs we now
  1932. # allow a bit redundancy in the pragma declarations. The rule is
  1933. # a prototype's pragma list must be a superset of the current pragma
  1934. # list.
  1935. # XXX This needs more checks eventually, for example that external
  1936. # linking names do agree:
  1937. if hasProto and (
  1938. # calling convention mismatch
  1939. tfExplicitCallConv in s.typ.flags and proto.typ.callConv != s.typ.callConv or
  1940. # implementation has additional pragmas
  1941. proto.typ.flags < s.typ.flags):
  1942. localError(c.config, n[pragmasPos].info, errPragmaOnlyInHeaderOfProcX %
  1943. ("'" & proto.name.s & "' from " & c.config$proto.info &
  1944. " '" & s.name.s & "' from " & c.config$s.info))
  1945. styleCheckDef(c, s)
  1946. if hasProto:
  1947. onDefResolveForward(n[namePos].info, proto)
  1948. else:
  1949. onDef(n[namePos].info, s)
  1950. if hasProto:
  1951. if sfForward notin proto.flags and proto.magic == mNone:
  1952. wrongRedefinition(c, n.info, proto.name.s, proto.info)
  1953. if not comesFromShadowScope:
  1954. excl(proto.flags, sfForward)
  1955. incl(proto.flags, sfWasForwarded)
  1956. suggestSym(c.graph, s.info, proto, c.graph.usageSym)
  1957. closeScope(c) # close scope with wrong parameter symbols
  1958. openScope(c) # open scope for old (correct) parameter symbols
  1959. if proto.ast[genericParamsPos].isGenericParams:
  1960. addGenericParamListToScope(c, proto.ast[genericParamsPos])
  1961. addParams(c, proto.typ.n, proto.kind)
  1962. proto.info = s.info # more accurate line information
  1963. proto.options = s.options
  1964. s = proto
  1965. n[genericParamsPos] = proto.ast[genericParamsPos]
  1966. n[paramsPos] = proto.ast[paramsPos]
  1967. n[pragmasPos] = proto.ast[pragmasPos]
  1968. if n[namePos].kind != nkSym: internalError(c.config, n.info, "semProcAux")
  1969. n[namePos].sym = proto
  1970. if importantComments(c.config) and proto.ast.comment.len > 0:
  1971. n.comment = proto.ast.comment
  1972. proto.ast = n # needed for code generation
  1973. popOwner(c)
  1974. pushOwner(c, s)
  1975. if not isAnon:
  1976. if sfOverriden in s.flags or s.name.s[0] == '=': semOverride(c, s, n)
  1977. elif s.name.s[0] in {'.', '('}:
  1978. if s.name.s in [".", ".()", ".="] and {Feature.destructor, dotOperators} * c.features == {}:
  1979. localError(c.config, n.info, "the overloaded " & s.name.s &
  1980. " operator has to be enabled with {.experimental: \"dotOperators\".}")
  1981. elif s.name.s == "()" and callOperator notin c.features:
  1982. localError(c.config, n.info, "the overloaded " & s.name.s &
  1983. " operator has to be enabled with {.experimental: \"callOperator\".}")
  1984. if sfBorrow in s.flags and c.config.cmd notin cmdDocLike:
  1985. result[bodyPos] = c.graph.emptyNode
  1986. if n[bodyPos].kind != nkEmpty and sfError notin s.flags:
  1987. # for DLL generation we allow sfImportc to have a body, for use in VM
  1988. if c.config.ideCmd in {ideSug, ideCon} and s.kind notin {skMacro, skTemplate} and not
  1989. cursorInProc(c.config, n[bodyPos]):
  1990. # speed up nimsuggest
  1991. if s.kind == skMethod: semMethodPrototype(c, s, n)
  1992. elif isAnon:
  1993. let gp = n[genericParamsPos]
  1994. if gp.kind == nkEmpty or (gp.len == 1 and tfRetType in gp[0].typ.flags):
  1995. # absolutely no generics (empty) or a single generic return type are
  1996. # allowed, everything else, including a nullary generic is an error.
  1997. pushProcCon(c, s)
  1998. addResult(c, n, s.typ[0], skProc)
  1999. s.ast[bodyPos] = hloBody(c, semProcBody(c, n[bodyPos], s.typ[0]))
  2000. trackProc(c, s, s.ast[bodyPos])
  2001. popProcCon(c)
  2002. elif efOperand notin flags:
  2003. localError(c.config, n.info, errGenericLambdaNotAllowed)
  2004. else:
  2005. pushProcCon(c, s)
  2006. if n[genericParamsPos].kind == nkEmpty or s.kind in {skMacro, skTemplate}:
  2007. # Macros and Templates can have generic parameters, but they are only
  2008. # used for overload resolution (there is no instantiation of the symbol)
  2009. if s.kind notin {skMacro, skTemplate} and s.magic == mNone: paramsTypeCheck(c, s.typ)
  2010. maybeAddResult(c, s, n)
  2011. let resultType =
  2012. if s.kind == skMacro:
  2013. sysTypeFromName(c.graph, n.info, "NimNode")
  2014. elif not isInlineIterator(s.typ):
  2015. s.typ[0]
  2016. else:
  2017. nil
  2018. # semantic checking also needed with importc in case used in VM
  2019. s.ast[bodyPos] = hloBody(c, semProcBody(c, n[bodyPos], resultType))
  2020. # unfortunately we cannot skip this step when in 'system.compiles'
  2021. # context as it may even be evaluated in 'system.compiles':
  2022. trackProc(c, s, s.ast[bodyPos])
  2023. else:
  2024. if (s.typ[0] != nil and s.kind != skIterator):
  2025. addDecl(c, newSym(skUnknown, getIdent(c.cache, "result"), nextSymId c.idgen, s, n.info))
  2026. openScope(c)
  2027. n[bodyPos] = semGenericStmt(c, n[bodyPos])
  2028. closeScope(c)
  2029. if s.magic == mNone:
  2030. fixupInstantiatedSymbols(c, s)
  2031. if s.kind == skMethod: semMethodPrototype(c, s, n)
  2032. popProcCon(c)
  2033. else:
  2034. if s.kind == skMethod: semMethodPrototype(c, s, n)
  2035. if hasProto: localError(c.config, n.info, errImplOfXexpected % proto.name.s)
  2036. if {sfImportc, sfBorrow, sfError} * s.flags == {} and s.magic == mNone:
  2037. # this is a forward declaration and we're building the prototype
  2038. if s.kind in {skProc, skFunc} and s.typ[0] != nil and s.typ[0].kind == tyAnything:
  2039. localError(c.config, n[paramsPos][0].info, "return type 'auto' cannot be used in forward declarations")
  2040. incl(s.flags, sfForward)
  2041. incl(s.flags, sfWasForwarded)
  2042. elif sfBorrow in s.flags: semBorrow(c, n, s)
  2043. sideEffectsCheck(c, s)
  2044. closeScope(c) # close scope for parameters
  2045. # c.currentScope = oldScope
  2046. popOwner(c)
  2047. if n[patternPos].kind != nkEmpty:
  2048. c.patterns.add(s)
  2049. if isAnon:
  2050. n.transitionSonsKind(nkLambda)
  2051. result.typ = s.typ
  2052. if optOwnedRefs in c.config.globalOptions:
  2053. result.typ = makeVarType(c, result.typ, tyOwned)
  2054. elif isTopLevel(c) and s.kind != skIterator and s.typ.callConv == ccClosure:
  2055. localError(c.config, s.info, "'.closure' calling convention for top level routines is invalid")
  2056. proc determineType(c: PContext, s: PSym) =
  2057. if s.typ != nil: return
  2058. #if s.magic != mNone: return
  2059. #if s.ast.isNil: return
  2060. discard semProcAux(c, s.ast, s.kind, {})
  2061. proc semIterator(c: PContext, n: PNode): PNode =
  2062. # gensym'ed iterator?
  2063. if n[namePos].kind == nkSym:
  2064. # gensym'ed iterators might need to become closure iterators:
  2065. n[namePos].sym.owner = getCurrOwner(c)
  2066. n[namePos].sym.transitionRoutineSymKind(skIterator)
  2067. result = semProcAux(c, n, skIterator, iteratorPragmas)
  2068. # bug #7093: if after a macro transformation we don't have an
  2069. # nkIteratorDef aynmore, return. The iterator then might have been
  2070. # sem'checked already. (Or not, if the macro skips it.)
  2071. if result.kind != n.kind: return
  2072. var s = result[namePos].sym
  2073. var t = s.typ
  2074. if t[0] == nil and s.typ.callConv != ccClosure:
  2075. localError(c.config, n.info, "iterator needs a return type")
  2076. # iterators are either 'inline' or 'closure'; for backwards compatibility,
  2077. # we require first class iterators to be marked with 'closure' explicitly
  2078. # -- at least for 0.9.2.
  2079. if s.typ.callConv == ccClosure:
  2080. incl(s.typ.flags, tfCapturesEnv)
  2081. else:
  2082. s.typ.callConv = ccInline
  2083. if n[bodyPos].kind == nkEmpty and s.magic == mNone and c.inConceptDecl == 0:
  2084. localError(c.config, n.info, errImplOfXexpected % s.name.s)
  2085. if optOwnedRefs in c.config.globalOptions and result.typ != nil:
  2086. result.typ = makeVarType(c, result.typ, tyOwned)
  2087. result.typ.callConv = ccClosure
  2088. proc semProc(c: PContext, n: PNode): PNode =
  2089. result = semProcAux(c, n, skProc, procPragmas)
  2090. proc semFunc(c: PContext, n: PNode): PNode =
  2091. let validPragmas = if n[namePos].kind != nkEmpty: procPragmas
  2092. else: lambdaPragmas
  2093. result = semProcAux(c, n, skFunc, validPragmas)
  2094. proc semMethod(c: PContext, n: PNode): PNode =
  2095. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "method")
  2096. result = semProcAux(c, n, skMethod, methodPragmas)
  2097. # macros can transform converters to nothing:
  2098. if namePos >= result.safeLen: return result
  2099. # bug #7093: if after a macro transformation we don't have an
  2100. # nkIteratorDef aynmore, return. The iterator then might have been
  2101. # sem'checked already. (Or not, if the macro skips it.)
  2102. if result.kind != nkMethodDef: return
  2103. var s = result[namePos].sym
  2104. # we need to fix the 'auto' return type for the dispatcher here (see tautonotgeneric
  2105. # test case):
  2106. let disp = getDispatcher(s)
  2107. # auto return type?
  2108. if disp != nil and disp.typ[0] != nil and disp.typ[0].kind == tyUntyped:
  2109. let ret = s.typ[0]
  2110. disp.typ[0] = ret
  2111. if disp.ast[resultPos].kind == nkSym:
  2112. if isEmptyType(ret): disp.ast[resultPos] = c.graph.emptyNode
  2113. else: disp.ast[resultPos].sym.typ = ret
  2114. proc semConverterDef(c: PContext, n: PNode): PNode =
  2115. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "converter")
  2116. result = semProcAux(c, n, skConverter, converterPragmas)
  2117. # macros can transform converters to nothing:
  2118. if namePos >= result.safeLen: return result
  2119. # bug #7093: if after a macro transformation we don't have an
  2120. # nkIteratorDef aynmore, return. The iterator then might have been
  2121. # sem'checked already. (Or not, if the macro skips it.)
  2122. if result.kind != nkConverterDef: return
  2123. var s = result[namePos].sym
  2124. var t = s.typ
  2125. if t[0] == nil: localError(c.config, n.info, errXNeedsReturnType % "converter")
  2126. if t.len != 2: localError(c.config, n.info, "a converter takes exactly one argument")
  2127. addConverterDef(c, LazySym(sym: s))
  2128. proc semMacroDef(c: PContext, n: PNode): PNode =
  2129. result = semProcAux(c, n, skMacro, macroPragmas)
  2130. # macros can transform macros to nothing:
  2131. if namePos >= result.safeLen: return result
  2132. # bug #7093: if after a macro transformation we don't have an
  2133. # nkIteratorDef aynmore, return. The iterator then might have been
  2134. # sem'checked already. (Or not, if the macro skips it.)
  2135. if result.kind != nkMacroDef: return
  2136. var s = result[namePos].sym
  2137. var t = s.typ
  2138. var allUntyped = true
  2139. for i in 1..<t.n.len:
  2140. let param = t.n[i].sym
  2141. if param.typ.kind != tyUntyped: allUntyped = false
  2142. if allUntyped: incl(s.flags, sfAllUntyped)
  2143. if n[bodyPos].kind == nkEmpty:
  2144. localError(c.config, n.info, errImplOfXexpected % s.name.s)
  2145. proc incMod(c: PContext, n: PNode, it: PNode, includeStmtResult: PNode) =
  2146. var f = checkModuleName(c.config, it)
  2147. if f != InvalidFileIdx:
  2148. addIncludeFileDep(c, f)
  2149. onProcessing(c.graph, f, "include", c.module)
  2150. if containsOrIncl(c.includedFiles, f.int):
  2151. localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
  2152. else:
  2153. includeStmtResult.add semStmt(c, c.graph.includeFileCallback(c.graph, c.module, f), {})
  2154. excl(c.includedFiles, f.int)
  2155. proc evalInclude(c: PContext, n: PNode): PNode =
  2156. result = newNodeI(nkStmtList, n.info)
  2157. result.add n
  2158. for i in 0..<n.len:
  2159. var imp: PNode
  2160. let it = n[i]
  2161. if it.kind == nkInfix and it.len == 3 and it[0].ident.s != "/":
  2162. localError(c.config, it.info, "Cannot use '" & it[0].ident.s & "' in 'include'.")
  2163. if it.kind == nkInfix and it.len == 3 and it[2].kind == nkBracket:
  2164. let sep = it[0]
  2165. let dir = it[1]
  2166. imp = newNodeI(nkInfix, it.info)
  2167. imp.add sep
  2168. imp.add dir
  2169. imp.add sep # dummy entry, replaced in the loop
  2170. for x in it[2]:
  2171. imp[2] = x
  2172. incMod(c, n, imp, result)
  2173. else:
  2174. incMod(c, n, it, result)
  2175. proc recursiveSetFlag(n: PNode, flag: TNodeFlag) =
  2176. if n != nil:
  2177. for i in 0..<n.safeLen: recursiveSetFlag(n[i], flag)
  2178. incl(n.flags, flag)
  2179. proc semPragmaBlock(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  2180. checkSonsLen(n, 2, c.config)
  2181. let pragmaList = n[0]
  2182. pragma(c, nil, pragmaList, exprPragmas, isStatement = true)
  2183. var inUncheckedAssignSection = 0
  2184. for p in pragmaList:
  2185. if whichPragma(p) == wCast:
  2186. case whichPragma(p[1])
  2187. of wGcSafe, wNoSideEffect, wTags, wForbids, wRaises:
  2188. discard "handled in sempass2"
  2189. of wUncheckedAssign:
  2190. inUncheckedAssignSection = 1
  2191. else:
  2192. localError(c.config, p.info, "invalid pragma block: " & $p)
  2193. inc c.inUncheckedAssignSection, inUncheckedAssignSection
  2194. n[1] = semExpr(c, n[1], expectedType = expectedType)
  2195. dec c.inUncheckedAssignSection, inUncheckedAssignSection
  2196. result = n
  2197. result.typ = n[1].typ
  2198. for i in 0..<pragmaList.len:
  2199. case whichPragma(pragmaList[i])
  2200. of wLine: setInfoRecursive(result, pragmaList[i].info)
  2201. of wNoRewrite: recursiveSetFlag(result, nfNoRewrite)
  2202. else: discard
  2203. proc semStaticStmt(c: PContext, n: PNode): PNode =
  2204. #echo "semStaticStmt"
  2205. #writeStackTrace()
  2206. inc c.inStaticContext
  2207. openScope(c)
  2208. let a = semStmt(c, n[0], {})
  2209. closeScope(c)
  2210. dec c.inStaticContext
  2211. n[0] = a
  2212. evalStaticStmt(c.module, c.idgen, c.graph, a, c.p.owner)
  2213. when false:
  2214. # for incremental replays, keep the AST as required for replays:
  2215. result = n
  2216. else:
  2217. result = newNodeI(nkDiscardStmt, n.info, 1)
  2218. result[0] = c.graph.emptyNode
  2219. proc usesResult(n: PNode): bool =
  2220. # nkStmtList(expr) properly propagates the void context,
  2221. # so we don't need to process that all over again:
  2222. if n.kind notin {nkStmtList, nkStmtListExpr,
  2223. nkMacroDef, nkTemplateDef} + procDefs:
  2224. if isAtom(n):
  2225. result = n.kind == nkSym and n.sym.kind == skResult
  2226. elif n.kind == nkReturnStmt:
  2227. result = true
  2228. else:
  2229. for c in n:
  2230. if usesResult(c): return true
  2231. proc inferConceptStaticParam(c: PContext, inferred, n: PNode) =
  2232. var typ = inferred.typ
  2233. let res = semConstExpr(c, n)
  2234. if not sameType(res.typ, typ.base):
  2235. localError(c.config, n.info,
  2236. "cannot infer the concept parameter '%s', due to a type mismatch. " &
  2237. "attempt to equate '%s' and '%s'." % [inferred.renderTree, $res.typ, $typ.base])
  2238. typ.n = res
  2239. proc semStmtList(c: PContext, n: PNode, flags: TExprFlags, expectedType: PType = nil): PNode =
  2240. result = n
  2241. result.transitionSonsKind(nkStmtList)
  2242. var voidContext = false
  2243. var last = n.len-1
  2244. # by not allowing for nkCommentStmt etc. we ensure nkStmtListExpr actually
  2245. # really *ends* in the expression that produces the type: The compiler now
  2246. # relies on this fact and it's too much effort to change that. And arguably
  2247. # 'R(); #comment' shouldn't produce R's type anyway.
  2248. #while last > 0 and n[last].kind in {nkPragma, nkCommentStmt,
  2249. # nkNilLit, nkEmpty}:
  2250. # dec last
  2251. for i in 0..<n.len:
  2252. var x = semExpr(c, n[i], flags, if i == n.len - 1: expectedType else: nil)
  2253. n[i] = x
  2254. if c.matchedConcept != nil and x.typ != nil and
  2255. (nfFromTemplate notin n.flags or i != last):
  2256. case x.typ.kind
  2257. of tyBool:
  2258. if x.kind == nkInfix and
  2259. x[0].kind == nkSym and
  2260. x[0].sym.name.s == "==":
  2261. if x[1].typ.isUnresolvedStatic:
  2262. inferConceptStaticParam(c, x[1], x[2])
  2263. continue
  2264. elif x[2].typ.isUnresolvedStatic:
  2265. inferConceptStaticParam(c, x[2], x[1])
  2266. continue
  2267. let verdict = semConstExpr(c, n[i])
  2268. if verdict == nil or verdict.kind != nkIntLit or verdict.intVal == 0:
  2269. localError(c.config, result.info, "concept predicate failed")
  2270. of tyUnknown: continue
  2271. else: discard
  2272. if n[i].typ == c.enforceVoidContext: #or usesResult(n[i]):
  2273. voidContext = true
  2274. n.typ = c.enforceVoidContext
  2275. if i == last and (n.len == 1 or ({efWantValue, efInTypeof} * flags != {})):
  2276. n.typ = n[i].typ
  2277. if not isEmptyType(n.typ): n.transitionSonsKind(nkStmtListExpr)
  2278. elif i != last or voidContext:
  2279. discardCheck(c, n[i], flags)
  2280. else:
  2281. n.typ = n[i].typ
  2282. if not isEmptyType(n.typ): n.transitionSonsKind(nkStmtListExpr)
  2283. var m = n[i]
  2284. while m.kind in {nkStmtListExpr, nkStmtList} and m.len > 0: # from templates
  2285. m = m.lastSon
  2286. if m.kind in nkLastBlockStmts or
  2287. m.kind in nkCallKinds and m[0].kind == nkSym and
  2288. sfNoReturn in m[0].sym.flags:
  2289. for j in i + 1..<n.len:
  2290. case n[j].kind
  2291. of nkPragma, nkCommentStmt, nkNilLit, nkEmpty, nkState: discard
  2292. else: message(c.config, n[j].info, warnUnreachableCode)
  2293. else: discard
  2294. if result.len == 1 and
  2295. # concept bodies should be preserved as a stmt list:
  2296. c.matchedConcept == nil and
  2297. # also, don't make life complicated for macros.
  2298. # they will always expect a proper stmtlist:
  2299. nfBlockArg notin n.flags and
  2300. result[0].kind != nkDefer:
  2301. result = result[0]
  2302. when defined(nimfix):
  2303. if result.kind == nkCommentStmt and not result.comment.isNil and
  2304. not (result.comment[0] == '#' and result.comment[1] == '#'):
  2305. # it is an old-style comment statement: we replace it with 'discard ""':
  2306. prettybase.replaceComment(result.info)
  2307. proc semStmt(c: PContext, n: PNode; flags: TExprFlags): PNode =
  2308. if efInTypeof notin flags:
  2309. result = semExprNoType(c, n)
  2310. else:
  2311. result = semExpr(c, n, flags)