semstmts.nim 93 KB

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