semstmts.nim 85 KB

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