semstmts.nim 95 KB

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