semstmts.nim 83 KB

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