semstmts.nim 85 KB

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