semstmts.nim 93 KB

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