semstmts.nim 110 KB

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