semstmts.nim 73 KB

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