semstmts.nim 85 KB

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