semstmts.nim 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898
  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
  569. if result:
  570. # make sure it's not a user pragma
  571. let ident = considerQuotedIdent(c, key)
  572. result = strTableGet(c.userPragmas, ident) == nil
  573. if result:
  574. # make sure it's not a custom pragma
  575. var amb = false
  576. let sym = searchInScopes(c, ident, amb)
  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 a[^1].kind != nkEmpty:
  752. def = semExprWithType(c, a[^1], {efTypeAllowed}, typ)
  753. if def.kind == nkSym and def.sym.kind in {skTemplate, skMacro}:
  754. typFlags.incl taIsTemplateOrMacro
  755. elif def.typ.kind == tyTypeDesc and c.p.owner.kind != skMacro:
  756. typFlags.incl taProcContextIsNotMacro
  757. if typ != nil:
  758. if typ.isMetaType:
  759. def = inferWithMetatype(c, typ, def)
  760. typ = def.typ
  761. else:
  762. # BUGFIX: ``fitNode`` is needed here!
  763. # check type compatibility between def.typ and typ
  764. def = fitNodeConsiderViewType(c, typ, def, def.info)
  765. #changeType(def.skipConv, typ, check=true)
  766. else:
  767. typ = def.typ.skipTypes({tyStatic, tySink}).skipIntLit(c.idgen)
  768. if typ.kind in tyUserTypeClasses and typ.isResolvedUserTypeClass:
  769. typ = typ.last
  770. if hasEmpty(typ):
  771. localError(c.config, def.info, errCannotInferTypeOfTheLiteral % typ.kind.toHumanStr)
  772. elif typ.kind == tyProc and def.kind == nkSym and isGenericRoutine(def.sym.ast):
  773. let owner = typ.owner
  774. let err =
  775. # consistent error message with evaltempl/semMacroExpr
  776. if owner != nil and owner.kind in {skTemplate, skMacro}:
  777. errMissingGenericParamsForTemplate % def.renderTree
  778. else:
  779. errProcHasNoConcreteType % def.renderTree
  780. localError(c.config, def.info, err)
  781. when false:
  782. # XXX This typing rule is neither documented nor complete enough to
  783. # justify it. Instead use the newer 'unowned x' until we figured out
  784. # a more general solution.
  785. if symkind == skVar and typ.kind == tyOwned and def.kind notin nkCallKinds:
  786. # special type inference rule: 'var it = ownedPointer' is turned
  787. # into an unowned pointer.
  788. typ = typ.lastSon
  789. # this can only happen for errornous var statements:
  790. if typ == nil: continue
  791. if c.matchedConcept != nil:
  792. typFlags.incl taConcept
  793. typeAllowedCheck(c, a.info, typ, symkind, typFlags)
  794. var tup = skipTypes(typ, {tyGenericInst, tyAlias, tySink})
  795. if a.kind == nkVarTuple:
  796. # generate new section from tuple unpacking and embed it into this one
  797. let assignments = makeVarTupleSection(c, n, a, def, tup, symkind, result)
  798. let resSection = semVarOrLet(c, assignments, symkind)
  799. for resDef in resSection:
  800. addToVarSection(c, result, n, resDef)
  801. else:
  802. if tup.kind == tyTuple and def.kind in {nkPar, nkTupleConstr} and
  803. a.len > 3:
  804. # var a, b = (1, 2)
  805. message(c.config, a.info, warnEachIdentIsTuple)
  806. for j in 0..<a.len-2:
  807. if a[j].kind == nkDotExpr:
  808. fillPartialObject(c, a[j], typ)
  809. addToVarSection(c, result, n, a)
  810. continue
  811. var v = semIdentDef(c, a[j], symkind, false)
  812. when defined(nimsuggest):
  813. v.hasUserSpecifiedType = hasUserSpecifiedType
  814. styleCheckDef(c, v)
  815. onDef(a[j].info, v)
  816. if sfGenSym notin v.flags:
  817. if not isDiscardUnderscore(v): addInterfaceDecl(c, v)
  818. else:
  819. if v.owner == nil: v.owner = c.p.owner
  820. when oKeepVariableNames:
  821. if c.inUnrolledContext > 0: v.flags.incl(sfShadowed)
  822. else:
  823. let shadowed = findShadowedVar(c, v)
  824. if shadowed != nil:
  825. shadowed.flags.incl(sfShadowed)
  826. if shadowed.kind == skResult and sfGenSym notin v.flags:
  827. message(c.config, a.info, warnResultShadowed)
  828. if def.kind != nkEmpty:
  829. if sfThread in v.flags: localError(c.config, def.info, errThreadvarCannotInit)
  830. setVarType(c, v, typ)
  831. # this is needed for the evaluation pass, guard checking
  832. # and custom pragmas:
  833. b = newNodeI(nkIdentDefs, a.info)
  834. if importantComments(c.config):
  835. # keep documentation information:
  836. b.comment = a.comment
  837. # postfix not generated here (to generate, get rid of it in transf)
  838. if a[j].kind == nkPragmaExpr:
  839. var p = newNodeI(nkPragmaExpr, a.info)
  840. p.add newSymNode(v)
  841. p.add a[j][1]
  842. b.add p
  843. else:
  844. b.add newSymNode(v)
  845. # keep type desc for doc generator
  846. b.add a[^2]
  847. b.add copyTree(def)
  848. addToVarSection(c, result, n, b)
  849. v.ast = b
  850. if def.kind == nkEmpty:
  851. let actualType = v.typ.skipTypes({tyGenericInst, tyAlias,
  852. tyUserTypeClassInst})
  853. if actualType.kind in {tyObject, tyDistinct} and
  854. actualType.requiresInit:
  855. defaultConstructionError(c, v.typ, v.info)
  856. else:
  857. checkNilable(c, v)
  858. # allow let to not be initialised if imported from C:
  859. if v.kind == skLet and sfImportc notin v.flags and (strictDefs notin c.features or not isLocalSym(v)):
  860. localError(c.config, a.info, errLetNeedsInit)
  861. if sfCompileTime in v.flags:
  862. var x = newNodeI(result.kind, v.info)
  863. x.add result[i]
  864. vm.setupCompileTimeVar(c.module, c.idgen, c.graph, x)
  865. if v.flags * {sfGlobal, sfThread} == {sfGlobal}:
  866. message(c.config, v.info, hintGlobalVar)
  867. if {sfGlobal, sfPure} <= v.flags:
  868. globalVarInitCheck(c, def)
  869. suggestSym(c.graph, v.info, v, c.graph.usageSym)
  870. proc semConst(c: PContext, n: PNode): PNode =
  871. result = copyNode(n)
  872. inc c.inStaticContext
  873. var b: PNode
  874. for i in 0..<n.len:
  875. var a = n[i]
  876. if c.config.cmd == cmdIdeTools: suggestStmt(c, a)
  877. if a.kind == nkCommentStmt: continue
  878. if a.kind notin {nkConstDef, nkVarTuple}: illFormedAst(a, c.config)
  879. checkMinSonsLen(a, 3, c.config)
  880. b = semVarMacroPragma(c, a, n)
  881. if b != nil:
  882. addToVarSection(c, result, b)
  883. continue
  884. var hasUserSpecifiedType = false
  885. var typ: PType = nil
  886. if a[^2].kind != nkEmpty:
  887. typ = semTypeNode(c, a[^2], nil)
  888. hasUserSpecifiedType = true
  889. var typFlags: TTypeAllowedFlags = {}
  890. # don't evaluate here since the type compatibility check below may add a converter
  891. var def = semExprWithType(c, a[^1], {efTypeAllowed}, typ)
  892. if def.kind == nkSym and def.sym.kind in {skTemplate, skMacro}:
  893. typFlags.incl taIsTemplateOrMacro
  894. elif def.typ.kind == tyTypeDesc and c.p.owner.kind != skMacro:
  895. typFlags.incl taProcContextIsNotMacro
  896. # check type compatibility between def.typ and typ:
  897. if typ != nil:
  898. if typ.isMetaType:
  899. def = inferWithMetatype(c, typ, def)
  900. typ = def.typ
  901. else:
  902. def = fitRemoveHiddenConv(c, typ, def)
  903. else:
  904. typ = def.typ
  905. # evaluate the node
  906. def = semConstExpr(c, def)
  907. if def == nil:
  908. localError(c.config, a[^1].info, errConstExprExpected)
  909. continue
  910. if def.kind != nkNilLit:
  911. if c.matchedConcept != nil:
  912. typFlags.incl taConcept
  913. typeAllowedCheck(c, a.info, typ, skConst, typFlags)
  914. if a.kind == nkVarTuple:
  915. # generate new section from tuple unpacking and embed it into this one
  916. let assignments = makeVarTupleSection(c, n, a, def, typ, skConst, result)
  917. let resSection = semConst(c, assignments)
  918. for resDef in resSection:
  919. addToVarSection(c, result, n, resDef)
  920. else:
  921. for j in 0..<a.len-2:
  922. var v = semIdentDef(c, a[j], skConst)
  923. when defined(nimsuggest):
  924. v.hasUserSpecifiedType = hasUserSpecifiedType
  925. if sfGenSym notin v.flags: addInterfaceDecl(c, v)
  926. elif v.owner == nil: v.owner = getCurrOwner(c)
  927. styleCheckDef(c, v)
  928. onDef(a[j].info, v)
  929. var fillSymbol = true
  930. if v.typ != nil:
  931. # symbol already has type and probably value
  932. # don't mutate
  933. fillSymbol = false
  934. else:
  935. setVarType(c, v, typ)
  936. b = newNodeI(nkConstDef, a.info)
  937. if importantComments(c.config): b.comment = a.comment
  938. # postfix not generated here (to generate, get rid of it in transf)
  939. if a[j].kind == nkPragmaExpr:
  940. var p = newNodeI(nkPragmaExpr, a.info)
  941. p.add newSymNode(v)
  942. p.add a[j][1].copyTree
  943. b.add p
  944. else:
  945. b.add newSymNode(v)
  946. b.add a[1]
  947. b.add copyTree(def)
  948. if fillSymbol:
  949. v.ast = b
  950. addToVarSection(c, result, n, b)
  951. dec c.inStaticContext
  952. include semfields
  953. proc symForVar(c: PContext, n: PNode): PSym =
  954. let m = if n.kind == nkPragmaExpr: n[0] else: n
  955. result = newSymG(skForVar, m, c)
  956. styleCheckDef(c, result)
  957. onDef(n.info, result)
  958. if n.kind == nkPragmaExpr:
  959. pragma(c, result, n[1], forVarPragmas)
  960. proc semForVars(c: PContext, n: PNode; flags: TExprFlags): PNode =
  961. result = n
  962. let iterBase = n[^2].typ
  963. var iter = skipTypes(iterBase, {tyGenericInst, tyAlias, tySink, tyOwned})
  964. var iterAfterVarLent = iter.skipTypes({tyGenericInst, tyAlias, tyLent, tyVar})
  965. # n.len == 3 means that there is one for loop variable
  966. # and thus no tuple unpacking:
  967. if iterAfterVarLent.kind == tyEmpty:
  968. localError(c.config, n[^2].info, "cannot infer element type of $1" %
  969. renderTree(n[^2], {renderNoComments}))
  970. if iterAfterVarLent.kind != tyTuple or n.len == 3:
  971. if n.len == 3:
  972. if n[0].kind == nkVarTuple:
  973. if iterAfterVarLent.kind != tyTuple:
  974. return localErrorNode(c, n, n[0].info, errTupleUnpackingTupleExpected %
  975. [typeToString(n[1].typ, preferDesc)])
  976. elif n[0].len-1 != iterAfterVarLent.len:
  977. return localErrorNode(c, n, n[0].info, errWrongNumberOfVariables)
  978. for i in 0..<n[0].len-1:
  979. var v = symForVar(c, n[0][i])
  980. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  981. case iter.kind
  982. of tyVar, tyLent:
  983. v.typ = newTypeS(iter.kind, c)
  984. v.typ.add iterAfterVarLent[i]
  985. if tfVarIsPtr in iter.flags:
  986. v.typ.flags.incl tfVarIsPtr
  987. else:
  988. v.typ = iter[i]
  989. n[0][i] = newSymNode(v)
  990. if sfGenSym notin v.flags and not isDiscardUnderscore(v): addDecl(c, v)
  991. elif v.owner == nil: v.owner = getCurrOwner(c)
  992. else:
  993. var v = symForVar(c, n[0])
  994. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  995. # BUGFIX: don't use `iter` here as that would strip away
  996. # the ``tyGenericInst``! See ``tests/compile/tgeneric.nim``
  997. # for an example:
  998. v.typ = iterBase
  999. n[0] = newSymNode(v)
  1000. if sfGenSym notin v.flags and not isDiscardUnderscore(v): addDecl(c, v)
  1001. elif v.owner == nil: v.owner = getCurrOwner(c)
  1002. else:
  1003. localError(c.config, n.info, errWrongNumberOfVariables)
  1004. elif n.len-2 != iterAfterVarLent.len:
  1005. localError(c.config, n.info, errWrongNumberOfVariables)
  1006. else:
  1007. for i in 0..<n.len - 2:
  1008. if n[i].kind == nkVarTuple:
  1009. var mutable = false
  1010. var isLent = false
  1011. case iter[i].kind
  1012. of tyVar:
  1013. mutable = true
  1014. iter[i] = iter[i].skipTypes({tyVar})
  1015. of tyLent:
  1016. isLent = true
  1017. iter[i] = iter[i].skipTypes({tyLent})
  1018. else: discard
  1019. if n[i].len-1 != iter[i].len:
  1020. localError(c.config, n[i].info, errWrongNumberOfVariables)
  1021. for j in 0..<n[i].len-1:
  1022. var v = symForVar(c, n[i][j])
  1023. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  1024. if mutable:
  1025. v.typ = newTypeS(tyVar, c)
  1026. v.typ.add iter[i][j]
  1027. elif isLent:
  1028. v.typ = newTypeS(tyLent, c)
  1029. v.typ.add iter[i][j]
  1030. else:
  1031. v.typ = iter[i][j]
  1032. n[i][j] = newSymNode(v)
  1033. if not isDiscardUnderscore(v): addDecl(c, v)
  1034. elif v.owner == nil: v.owner = getCurrOwner(c)
  1035. else:
  1036. var v = symForVar(c, n[i])
  1037. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  1038. case iter.kind
  1039. of tyVar, tyLent:
  1040. v.typ = newTypeS(iter.kind, c)
  1041. v.typ.add iterAfterVarLent[i]
  1042. if tfVarIsPtr in iter.flags:
  1043. v.typ.flags.incl tfVarIsPtr
  1044. else:
  1045. v.typ = iter[i]
  1046. n[i] = newSymNode(v)
  1047. if sfGenSym notin v.flags:
  1048. if not isDiscardUnderscore(v): addDecl(c, v)
  1049. elif v.owner == nil: v.owner = getCurrOwner(c)
  1050. inc(c.p.nestedLoopCounter)
  1051. let oldBreakInLoop = c.p.breakInLoop
  1052. c.p.breakInLoop = true
  1053. openScope(c)
  1054. n[^1] = semExprBranch(c, n[^1], flags)
  1055. if efInTypeof notin flags:
  1056. discardCheck(c, n[^1], flags)
  1057. closeScope(c)
  1058. c.p.breakInLoop = oldBreakInLoop
  1059. dec(c.p.nestedLoopCounter)
  1060. proc implicitIterator(c: PContext, it: string, arg: PNode): PNode =
  1061. result = newNodeI(nkCall, arg.info)
  1062. result.add(newIdentNode(getIdent(c.cache, it), arg.info))
  1063. if arg.typ != nil and arg.typ.kind in {tyVar, tyLent}:
  1064. result.add newDeref(arg)
  1065. else:
  1066. result.add arg
  1067. result = semExprNoDeref(c, result, {efWantIterator})
  1068. proc isTrivalStmtExpr(n: PNode): bool =
  1069. for i in 0..<n.len-1:
  1070. if n[i].kind notin {nkEmpty, nkCommentStmt}:
  1071. return false
  1072. result = true
  1073. proc handleStmtMacro(c: PContext; n, selector: PNode; magicType: string;
  1074. flags: TExprFlags): PNode =
  1075. if selector.kind in nkCallKinds:
  1076. # we transform
  1077. # n := for a, b, c in m(x, y, z): Y
  1078. # to
  1079. # m(n)
  1080. let maType = magicsys.getCompilerProc(c.graph, magicType)
  1081. if maType == nil: return
  1082. let headSymbol = selector[0]
  1083. var o: TOverloadIter = default(TOverloadIter)
  1084. var match: PSym = nil
  1085. var symx = initOverloadIter(o, c, headSymbol)
  1086. while symx != nil:
  1087. if symx.kind in {skTemplate, skMacro}:
  1088. if symx.typ.len == 2 and symx.typ.firstParamType == maType.typ:
  1089. if match == nil:
  1090. match = symx
  1091. else:
  1092. localError(c.config, n.info, errAmbiguousCallXYZ % [
  1093. getProcHeader(c.config, match),
  1094. getProcHeader(c.config, symx), $selector])
  1095. symx = nextOverloadIter(o, c, headSymbol)
  1096. if match == nil: return
  1097. var callExpr = newNodeI(nkCall, n.info)
  1098. callExpr.add newSymNode(match)
  1099. callExpr.add n
  1100. case match.kind
  1101. of skMacro: result = semMacroExpr(c, callExpr, callExpr, match, flags)
  1102. of skTemplate: result = semTemplateExpr(c, callExpr, match, flags)
  1103. else: result = nil
  1104. else:
  1105. result = nil
  1106. proc handleForLoopMacro(c: PContext; n: PNode; flags: TExprFlags): PNode =
  1107. result = handleStmtMacro(c, n, n[^2], "ForLoopStmt", flags)
  1108. proc handleCaseStmtMacro(c: PContext; n: PNode; flags: TExprFlags): PNode =
  1109. # n[0] has been sem'checked and has a type. We use this to resolve
  1110. # '`case`(n[0])' but then we pass 'n' to the `case` macro. This seems to
  1111. # be the best solution.
  1112. var toResolve = newNodeI(nkCall, n.info)
  1113. toResolve.add newIdentNode(getIdent(c.cache, "case"), n.info)
  1114. toResolve.add n[0]
  1115. var errors: CandidateErrors = @[]
  1116. var r = resolveOverloads(c, toResolve, toResolve, {skTemplate, skMacro}, {efNoDiagnostics},
  1117. errors, false)
  1118. if r.state == csMatch:
  1119. var match = r.calleeSym
  1120. markUsed(c, n[0].info, match)
  1121. onUse(n[0].info, match)
  1122. # but pass 'n' to the `case` macro, not 'n[0]':
  1123. r.call[1] = n
  1124. let toExpand = semResolvedCall(c, r, r.call, {})
  1125. case match.kind
  1126. of skMacro: result = semMacroExpr(c, toExpand, toExpand, match, flags)
  1127. of skTemplate: result = semTemplateExpr(c, toExpand, match, flags)
  1128. else: result = errorNode(c, n[0])
  1129. elif r.state == csNoMatch:
  1130. result = errorNode(c, n[0])
  1131. else:
  1132. result = errorNode(c, n[0])
  1133. if result.kind == nkEmpty:
  1134. localError(c.config, n[0].info, errSelectorMustBeOfCertainTypes)
  1135. # this would be the perfectly consistent solution with 'for loop macros',
  1136. # but it kinda sucks for pattern matching as the matcher is not attached to
  1137. # a type then:
  1138. when false:
  1139. result = handleStmtMacro(c, n, n[0], "CaseStmt")
  1140. proc semFor(c: PContext, n: PNode; flags: TExprFlags): PNode =
  1141. checkMinSonsLen(n, 3, c.config)
  1142. result = handleForLoopMacro(c, n, flags)
  1143. if result != nil: return result
  1144. openScope(c)
  1145. result = n
  1146. n[^2] = semExprNoDeref(c, n[^2], {efWantIterator})
  1147. var call = n[^2]
  1148. if call.kind == nkStmtListExpr and (isTrivalStmtExpr(call) or (call.lastSon.kind in nkCallKinds and call.lastSon[0].sym.kind == skIterator)):
  1149. call = call.lastSon
  1150. n[^2] = call
  1151. let isCallExpr = call.kind in nkCallKinds
  1152. if isCallExpr and call[0].kind == nkSym and
  1153. call[0].sym.magic in {mFields, mFieldPairs, mOmpParFor}:
  1154. if call[0].sym.magic == mOmpParFor:
  1155. result = semForVars(c, n, flags)
  1156. result.transitionSonsKind(nkParForStmt)
  1157. else:
  1158. result = semForFields(c, n, call[0].sym.magic)
  1159. elif isCallExpr and isClosureIterator(call[0].typ.skipTypes(abstractInst)):
  1160. # first class iterator:
  1161. result = semForVars(c, n, flags)
  1162. elif not isCallExpr or call[0].kind != nkSym or
  1163. call[0].sym.kind != skIterator:
  1164. if n.len == 3:
  1165. n[^2] = implicitIterator(c, "items", n[^2])
  1166. elif n.len == 4:
  1167. n[^2] = implicitIterator(c, "pairs", n[^2])
  1168. else:
  1169. localError(c.config, n[^2].info, "iterator within for loop context expected")
  1170. result = semForVars(c, n, flags)
  1171. else:
  1172. result = semForVars(c, n, flags)
  1173. # propagate any enforced VoidContext:
  1174. if n[^1].typ == c.enforceVoidContext:
  1175. result.typ = c.enforceVoidContext
  1176. elif efInTypeof in flags:
  1177. result.typ = result.lastSon.typ
  1178. closeScope(c)
  1179. proc semCase(c: PContext, n: PNode; flags: TExprFlags; expectedType: PType = nil): PNode =
  1180. result = n
  1181. checkMinSonsLen(n, 2, c.config)
  1182. openScope(c)
  1183. pushCaseContext(c, n)
  1184. n[0] = semExprWithType(c, n[0])
  1185. var covered: Int128 = toInt128(0)
  1186. var typ = commonTypeBegin
  1187. var expectedType = expectedType
  1188. var hasElse = false
  1189. let caseTyp = skipTypes(n[0].typ, abstractVar-{tyTypeDesc})
  1190. var chckCovered = caseTyp.shouldCheckCaseCovered()
  1191. case caseTyp.kind
  1192. of tyFloat..tyFloat128, tyString, tyCstring, tyError, shouldChckCovered, tyRange:
  1193. discard
  1194. else:
  1195. popCaseContext(c)
  1196. closeScope(c)
  1197. return handleCaseStmtMacro(c, n, flags)
  1198. template invalidOrderOfBranches(n: PNode) =
  1199. localError(c.config, n.info, "invalid order of case branches")
  1200. break
  1201. for i in 1..<n.len:
  1202. setCaseContextIdx(c, i)
  1203. var x = n[i]
  1204. when defined(nimsuggest):
  1205. if c.config.ideCmd == ideSug and exactEquals(c.config.m.trackPos, x.info) and caseTyp.kind == tyEnum:
  1206. suggestEnum(c, x, caseTyp)
  1207. case x.kind
  1208. of nkOfBranch:
  1209. if hasElse: invalidOrderOfBranches(x)
  1210. checkMinSonsLen(x, 2, c.config)
  1211. semCaseBranch(c, n, x, i, covered)
  1212. var last = x.len-1
  1213. x[last] = semExprBranchScope(c, x[last], expectedType)
  1214. typ = commonType(c, typ, x[last])
  1215. if not endsInNoReturn(x[last]):
  1216. expectedType = typ
  1217. of nkElifBranch:
  1218. if hasElse: invalidOrderOfBranches(x)
  1219. chckCovered = false
  1220. checkSonsLen(x, 2, c.config)
  1221. openScope(c)
  1222. x[0] = forceBool(c, semExprWithType(c, x[0], expectedType = getSysType(c.graph, n.info, tyBool)))
  1223. x[1] = semExprBranch(c, x[1], expectedType = expectedType)
  1224. typ = commonType(c, typ, x[1])
  1225. if not endsInNoReturn(x[1]):
  1226. expectedType = typ
  1227. closeScope(c)
  1228. of nkElse:
  1229. checkSonsLen(x, 1, c.config)
  1230. x[0] = semExprBranchScope(c, x[0], expectedType)
  1231. typ = commonType(c, typ, x[0])
  1232. if not endsInNoReturn(x[0]):
  1233. expectedType = typ
  1234. if (chckCovered and covered == toCover(c, n[0].typ)) or hasElse:
  1235. message(c.config, x.info, warnUnreachableElse)
  1236. hasElse = true
  1237. chckCovered = false
  1238. else:
  1239. illFormedAst(x, c.config)
  1240. if chckCovered:
  1241. if covered == toCover(c, n[0].typ):
  1242. hasElse = true
  1243. elif n[0].typ.skipTypes(abstractRange).kind in {tyEnum, tyChar}:
  1244. localError(c.config, n.info, "not all cases are covered; missing: $1" %
  1245. formatMissingEnums(c, n))
  1246. else:
  1247. localError(c.config, n.info, "not all cases are covered")
  1248. popCaseContext(c)
  1249. closeScope(c)
  1250. if isEmptyType(typ) or typ.kind in {tyNil, tyUntyped} or
  1251. (not hasElse and efInTypeof notin flags):
  1252. for i in 1..<n.len: discardCheck(c, n[i].lastSon, flags)
  1253. # propagate any enforced VoidContext:
  1254. if typ == c.enforceVoidContext:
  1255. result.typ = c.enforceVoidContext
  1256. else:
  1257. for i in 1..<n.len:
  1258. var it = n[i]
  1259. let j = it.len-1
  1260. if not endsInNoReturn(it[j]):
  1261. it[j] = fitNode(c, typ, it[j], it[j].info)
  1262. result.typ = typ
  1263. proc semRaise(c: PContext, n: PNode): PNode =
  1264. result = n
  1265. checkSonsLen(n, 1, c.config)
  1266. if n[0].kind != nkEmpty:
  1267. n[0] = semExprWithType(c, n[0])
  1268. var typ = n[0].typ
  1269. if not isImportedException(typ, c.config):
  1270. typ = typ.skipTypes({tyAlias, tyGenericInst, tyOwned})
  1271. if typ.kind != tyRef:
  1272. localError(c.config, n.info, errExprCannotBeRaised)
  1273. if typ.len > 0 and not isException(typ.elementType):
  1274. localError(c.config, n.info, "raised object of type $1 does not inherit from Exception" % typeToString(typ))
  1275. proc addGenericParamListToScope(c: PContext, n: PNode) =
  1276. if n.kind != nkGenericParams: illFormedAst(n, c.config)
  1277. for i in 0..<n.len:
  1278. var a = n[i]
  1279. if a.kind == nkSym: addDecl(c, a.sym)
  1280. else: illFormedAst(a, c.config)
  1281. proc typeSectionTypeName(c: PContext; n: PNode): PNode =
  1282. if n.kind == nkPragmaExpr:
  1283. if n.len == 0: illFormedAst(n, c.config)
  1284. result = n[0]
  1285. else:
  1286. result = n
  1287. if result.kind == nkPostfix:
  1288. if result.len != 2: illFormedAst(n, c.config)
  1289. result = result[1]
  1290. if result.kind != nkSym: illFormedAst(n, c.config)
  1291. proc typeDefLeftSidePass(c: PContext, typeSection: PNode, i: int) =
  1292. let typeDef = typeSection[i]
  1293. checkSonsLen(typeDef, 3, c.config)
  1294. var name = typeDef[0]
  1295. var s: PSym = nil
  1296. if name.kind == nkDotExpr and typeDef[2].kind == nkObjectTy:
  1297. let pkgName = considerQuotedIdent(c, name[0])
  1298. let typName = considerQuotedIdent(c, name[1])
  1299. let pkg = c.graph.packageSyms.strTableGet(pkgName)
  1300. if pkg.isNil or pkg.kind != skPackage:
  1301. localError(c.config, name.info, "unknown package name: " & pkgName.s)
  1302. else:
  1303. let typsym = c.graph.packageTypes.strTableGet(typName)
  1304. if typsym.isNil:
  1305. s = semIdentDef(c, name[1], skType)
  1306. onDef(name[1].info, s)
  1307. s.typ = newTypeS(tyObject, c)
  1308. s.typ.sym = s
  1309. s.flags.incl sfForward
  1310. c.graph.packageTypes.strTableAdd s
  1311. addInterfaceDecl(c, s)
  1312. elif typsym.kind == skType and sfForward in typsym.flags:
  1313. s = typsym
  1314. addInterfaceDecl(c, s)
  1315. # PRTEMP no onDef here?
  1316. else:
  1317. localError(c.config, name.info, typsym.name.s & " is not a type that can be forwarded")
  1318. s = typsym
  1319. else:
  1320. s = semIdentDef(c, name, skType)
  1321. onDef(name.info, s)
  1322. s.typ = newTypeS(tyForward, c)
  1323. s.typ.sym = s # process pragmas:
  1324. if name.kind == nkPragmaExpr:
  1325. let rewritten = applyTypeSectionPragmas(c, name[1], typeDef)
  1326. if rewritten != nil:
  1327. case rewritten.kind
  1328. of nkTypeDef:
  1329. typeSection[i] = rewritten
  1330. of nkTypeSection:
  1331. typeSection.sons[i .. i] = rewritten.sons
  1332. else: illFormedAst(rewritten, c.config)
  1333. typeDefLeftSidePass(c, typeSection, i)
  1334. return
  1335. pragma(c, s, name[1], typePragmas)
  1336. if sfForward in s.flags:
  1337. # check if the symbol already exists:
  1338. let pkg = c.module.owner
  1339. if not isTopLevel(c) or pkg.isNil:
  1340. localError(c.config, name.info, "only top level types in a package can be 'package'")
  1341. else:
  1342. let typsym = c.graph.packageTypes.strTableGet(s.name)
  1343. if typsym != nil:
  1344. if sfForward notin typsym.flags or sfNoForward notin typsym.flags:
  1345. typeCompleted(typsym)
  1346. typsym.info = s.info
  1347. else:
  1348. localError(c.config, name.info, "cannot complete type '" & s.name.s & "' twice; " &
  1349. "previous type completion was here: " & c.config$typsym.info)
  1350. s = typsym
  1351. # add it here, so that recursive types are possible:
  1352. if sfGenSym notin s.flags: addInterfaceDecl(c, s)
  1353. elif s.owner == nil: s.owner = getCurrOwner(c)
  1354. if name.kind == nkPragmaExpr:
  1355. if name[0].kind == nkPostfix:
  1356. typeDef[0][0][1] = newSymNode(s)
  1357. else:
  1358. typeDef[0][0] = newSymNode(s)
  1359. else:
  1360. if name.kind == nkPostfix:
  1361. typeDef[0][1] = newSymNode(s)
  1362. else:
  1363. typeDef[0] = newSymNode(s)
  1364. proc typeSectionLeftSidePass(c: PContext, n: PNode) =
  1365. # process the symbols on the left side for the whole type section, before
  1366. # we even look at the type definitions on the right
  1367. var i = 0
  1368. while i < n.len: # n may grow due to type pragma macros
  1369. var a = n[i]
  1370. when defined(nimsuggest):
  1371. if c.config.cmd == cmdIdeTools:
  1372. inc c.inTypeContext
  1373. suggestStmt(c, a)
  1374. dec c.inTypeContext
  1375. case a.kind
  1376. of nkCommentStmt: discard
  1377. of nkTypeDef: typeDefLeftSidePass(c, n, i)
  1378. else: illFormedAst(a, c.config)
  1379. inc i
  1380. proc checkCovariantParamsUsages(c: PContext; genericType: PType) =
  1381. var body = genericType.typeBodyImpl
  1382. proc traverseSubTypes(c: PContext; t: PType): bool =
  1383. template error(msg) = localError(c.config, genericType.sym.info, msg)
  1384. result = false
  1385. template subresult(r) =
  1386. let sub = r
  1387. result = result or sub
  1388. case t.kind
  1389. of tyGenericParam:
  1390. t.flags.incl tfWeakCovariant
  1391. return true
  1392. of tyObject:
  1393. for field in t.n:
  1394. subresult traverseSubTypes(c, field.typ)
  1395. of tyArray:
  1396. return traverseSubTypes(c, t.elementType)
  1397. of tyProc:
  1398. for subType in t.signature:
  1399. if subType != nil:
  1400. subresult traverseSubTypes(c, subType)
  1401. if result:
  1402. error("non-invariant type param used in a proc type: " & $t)
  1403. of tySequence:
  1404. return traverseSubTypes(c, t.elementType)
  1405. of tyGenericInvocation:
  1406. let targetBody = t.genericHead
  1407. for i in 1..<t.len:
  1408. let param = t[i]
  1409. if param.kind == tyGenericParam:
  1410. if tfCovariant in param.flags:
  1411. let formalFlags = targetBody[i-1].flags
  1412. if tfCovariant notin formalFlags:
  1413. error("covariant param '" & param.sym.name.s &
  1414. "' used in a non-covariant position")
  1415. elif tfWeakCovariant in formalFlags:
  1416. param.flags.incl tfWeakCovariant
  1417. result = true
  1418. elif tfContravariant in param.flags:
  1419. let formalParam = targetBody[i-1].sym
  1420. if tfContravariant notin formalParam.typ.flags:
  1421. error("contravariant param '" & param.sym.name.s &
  1422. "' used in a non-contravariant position")
  1423. result = true
  1424. else:
  1425. subresult traverseSubTypes(c, param)
  1426. of tyAnd, tyOr, tyNot, tyStatic, tyBuiltInTypeClass, tyCompositeTypeClass:
  1427. error("non-invariant type parameters cannot be used with types such '" & $t & "'")
  1428. of tyUserTypeClass, tyUserTypeClassInst:
  1429. error("non-invariant type parameters are not supported in concepts")
  1430. of tyTuple:
  1431. for fieldType in t.kids:
  1432. subresult traverseSubTypes(c, fieldType)
  1433. of tyPtr, tyRef, tyVar, tyLent:
  1434. if t.elementType.kind == tyGenericParam: return true
  1435. return traverseSubTypes(c, t.elementType)
  1436. of tyDistinct, tyAlias, tySink, tyOwned:
  1437. return traverseSubTypes(c, t.skipModifier)
  1438. of tyGenericInst:
  1439. internalAssert c.config, false
  1440. else:
  1441. discard
  1442. discard traverseSubTypes(c, body)
  1443. proc typeSectionRightSidePass(c: PContext, n: PNode) =
  1444. for i in 0..<n.len:
  1445. var a = n[i]
  1446. if a.kind == nkCommentStmt: continue
  1447. if a.kind != nkTypeDef: illFormedAst(a, c.config)
  1448. checkSonsLen(a, 3, c.config)
  1449. let name = typeSectionTypeName(c, a[0])
  1450. var s = name.sym
  1451. if s.magic == mNone and a[2].kind == nkEmpty:
  1452. localError(c.config, a.info, errImplOfXexpected % s.name.s)
  1453. if s.magic != mNone: processMagicType(c, s)
  1454. let oldFlags = s.typ.flags
  1455. if a[1].kind != nkEmpty:
  1456. # We have a generic type declaration here. In generic types,
  1457. # symbol lookup needs to be done here.
  1458. openScope(c)
  1459. pushOwner(c, s)
  1460. if s.magic == mNone: s.typ.kind = tyGenericBody
  1461. # XXX for generic type aliases this is not correct! We need the
  1462. # underlying Id really:
  1463. #
  1464. # type
  1465. # TGObj[T] = object
  1466. # TAlias[T] = TGObj[T]
  1467. #
  1468. s.typ.n = semGenericParamList(c, a[1], s.typ)
  1469. a[1] = s.typ.n
  1470. s.typ.size = -1 # could not be computed properly
  1471. # we fill it out later. For magic generics like 'seq', it won't be filled
  1472. # so we use tyNone instead of nil to not crash for strange conversions
  1473. # like: mydata.seq
  1474. if s.typ.kind in {tyOpenArray, tyVarargs} and s.typ.len == 1:
  1475. # XXX investigate why `tySequence` cannot be added here for now.
  1476. discard
  1477. else:
  1478. rawAddSon(s.typ, newTypeS(tyNone, c))
  1479. s.ast = a
  1480. inc c.inGenericContext
  1481. var body = semTypeNode(c, a[2], s.typ)
  1482. dec c.inGenericContext
  1483. if body != nil:
  1484. body.sym = s
  1485. body.size = -1 # could not be computed properly
  1486. if body.kind == tyObject:
  1487. # add flags applied to generic type to object (nominal) type
  1488. incl(body.flags, oldFlags)
  1489. # {.inheritable, final.} is already disallowed, but
  1490. # object might have been assumed to be final
  1491. if tfInheritable in oldFlags and tfFinal in body.flags:
  1492. excl(body.flags, tfFinal)
  1493. s.typ[^1] = body
  1494. if tfCovariant in s.typ.flags:
  1495. checkCovariantParamsUsages(c, s.typ)
  1496. # XXX: This is a temporary limitation:
  1497. # The codegen currently produces various failures with
  1498. # generic imported types that have fields, but we need
  1499. # the fields specified in order to detect weak covariance.
  1500. # The proper solution is to teach the codegen how to handle
  1501. # such types, because this would offer various interesting
  1502. # possibilities such as instantiating C++ generic types with
  1503. # garbage collected Nim types.
  1504. if sfImportc in s.flags:
  1505. var body = s.typ.last
  1506. if body.kind == tyObject:
  1507. # erases all declared fields
  1508. body.n.sons = @[]
  1509. popOwner(c)
  1510. closeScope(c)
  1511. elif a[2].kind != nkEmpty:
  1512. # process the type's body:
  1513. pushOwner(c, s)
  1514. var t = semTypeNode(c, a[2], s.typ)
  1515. if s.typ == nil:
  1516. s.typ = t
  1517. elif t != s.typ and (s.typ == nil or s.typ.kind != tyAlias):
  1518. # this can happen for e.g. tcan_alias_specialised_generic:
  1519. assignType(s.typ, t)
  1520. #debug s.typ
  1521. s.ast = a
  1522. popOwner(c)
  1523. # If the right hand side expression was a macro call we replace it with
  1524. # its evaluated result here so that we don't execute it once again in the
  1525. # final pass
  1526. if a[2].kind in nkCallKinds:
  1527. incl a[2].flags, nfSem # bug #10548
  1528. if sfExportc in s.flags:
  1529. if s.typ.kind == tyAlias:
  1530. localError(c.config, name.info, "{.exportc.} not allowed for type aliases")
  1531. elif s.typ.kind == tyGenericBody:
  1532. localError(c.config, name.info, "{.exportc.} not allowed for generic types")
  1533. if tfBorrowDot in s.typ.flags:
  1534. let body = s.typ.skipTypes({tyGenericBody})
  1535. if body.kind != tyDistinct:
  1536. # flag might be copied from alias/instantiation:
  1537. let t = body.skipTypes({tyAlias, tyGenericInst})
  1538. if not (t.kind == tyDistinct and tfBorrowDot in t.flags):
  1539. excl s.typ.flags, tfBorrowDot
  1540. localError(c.config, name.info, "only a 'distinct' type can borrow `.`")
  1541. let aa = a[2]
  1542. if aa.kind in {nkRefTy, nkPtrTy} and aa.len == 1 and
  1543. aa[0].kind == nkObjectTy:
  1544. # give anonymous object a dummy symbol:
  1545. var st = s.typ
  1546. if st.kind == tyGenericBody: st = st.typeBodyImpl
  1547. internalAssert c.config, st.kind in {tyPtr, tyRef}
  1548. internalAssert c.config, st.last.sym == nil
  1549. incl st.flags, tfRefsAnonObj
  1550. let objTy = st.last
  1551. # add flags for `ref object` etc to underlying `object`
  1552. incl(objTy.flags, oldFlags)
  1553. # {.inheritable, final.} is already disallowed, but
  1554. # object might have been assumed to be final
  1555. if tfInheritable in oldFlags and tfFinal in objTy.flags:
  1556. excl(objTy.flags, tfFinal)
  1557. let obj = newSym(skType, getIdent(c.cache, s.name.s & ":ObjectType"),
  1558. c.idgen, getCurrOwner(c), s.info)
  1559. obj.flags.incl sfGeneratedType
  1560. let symNode = newSymNode(obj)
  1561. obj.ast = a.shallowCopy
  1562. case a[0].kind
  1563. of nkSym: obj.ast[0] = symNode
  1564. of nkPragmaExpr:
  1565. obj.ast[0] = a[0].shallowCopy
  1566. if a[0][0].kind == nkPostfix:
  1567. obj.ast[0][0] = a[0][0].shallowCopy
  1568. obj.ast[0][0][1] = symNode
  1569. else:
  1570. obj.ast[0][0] = symNode
  1571. obj.ast[0][1] = a[0][1]
  1572. of nkPostfix:
  1573. obj.ast[0] = a[0].shallowCopy
  1574. obj.ast[0][1] = symNode
  1575. else: assert(false)
  1576. obj.ast[1] = a[1]
  1577. obj.ast[2] = a[2][0]
  1578. if sfPure in s.flags:
  1579. obj.flags.incl sfPure
  1580. obj.typ = objTy
  1581. objTy.sym = obj
  1582. for sk in c.skipTypes:
  1583. discard semTypeNode(c, sk, nil)
  1584. c.skipTypes = @[]
  1585. proc checkForMetaFields(c: PContext; n: PNode; hasError: var bool) =
  1586. proc checkMeta(c: PContext; n: PNode; t: PType; hasError: var bool; parent: PType) =
  1587. if t != nil and (t.isMetaType or t.kind == tyNone) and tfGenericTypeParam notin t.flags:
  1588. if t.kind == tyBuiltInTypeClass and t.len == 1 and t.elementType.kind == tyProc:
  1589. localError(c.config, n.info, ("'$1' is not a concrete type; " &
  1590. "for a callback without parameters use 'proc()'") % t.typeToString)
  1591. elif t.kind == tyNone and parent != nil:
  1592. # TODO: openarray has the `tfGenericTypeParam` flag & generics
  1593. # TODO: handle special cases (sink etc.) and views
  1594. localError(c.config, n.info, errTIsNotAConcreteType % parent.typeToString)
  1595. else:
  1596. localError(c.config, n.info, errTIsNotAConcreteType % t.typeToString)
  1597. hasError = true
  1598. if n.isNil: return
  1599. case n.kind
  1600. of nkRecList, nkRecCase:
  1601. for s in n: checkForMetaFields(c, s, hasError)
  1602. of nkOfBranch, nkElse:
  1603. checkForMetaFields(c, n.lastSon, hasError)
  1604. of nkSym:
  1605. let t = n.sym.typ
  1606. case t.kind
  1607. of tySequence, tySet, tyArray, tyOpenArray, tyVar, tyLent, tyPtr, tyRef,
  1608. tyProc, tyGenericInvocation, tyGenericInst, tyAlias, tySink, tyOwned:
  1609. let start = ord(t.kind in {tyGenericInvocation, tyGenericInst})
  1610. for i in start..<t.len:
  1611. checkMeta(c, n, t[i], hasError, t)
  1612. else:
  1613. checkMeta(c, n, t, hasError, nil)
  1614. else:
  1615. internalAssert c.config, false
  1616. proc typeSectionFinalPass(c: PContext, n: PNode) =
  1617. for i in 0..<n.len:
  1618. var a = n[i]
  1619. if a.kind == nkCommentStmt: continue
  1620. let name = typeSectionTypeName(c, a[0])
  1621. var s = name.sym
  1622. # check the style here after the pragmas have been processed:
  1623. styleCheckDef(c, s)
  1624. # compute the type's size and check for illegal recursions:
  1625. if a[1].kind == nkEmpty:
  1626. var x = a[2]
  1627. if x.kind in nkCallKinds and nfSem in x.flags:
  1628. discard "already semchecked, see line marked with bug #10548"
  1629. else:
  1630. while x.kind in {nkStmtList, nkStmtListExpr} and x.len > 0:
  1631. x = x.lastSon
  1632. # we need the 'safeSkipTypes' here because illegally recursive types
  1633. # can enter at this point, see bug #13763
  1634. if x.kind notin {nkObjectTy, nkDistinctTy, nkEnumTy, nkEmpty} and
  1635. s.typ.safeSkipTypes(abstractPtrs).kind notin {tyObject, tyEnum}:
  1636. # type aliases are hard:
  1637. var t = semTypeNode(c, x, nil)
  1638. assert t != nil
  1639. if s.typ != nil and s.typ.kind notin {tyAlias, tySink}:
  1640. if t.kind in {tyProc, tyGenericInst} and not t.isMetaType:
  1641. assignType(s.typ, t)
  1642. s.typ.itemId = t.itemId
  1643. elif t.kind in {tyObject, tyEnum, tyDistinct}:
  1644. assert s.typ != nil
  1645. assignType(s.typ, t)
  1646. s.typ.itemId = t.itemId # same id
  1647. var hasError = false
  1648. let baseType = s.typ.safeSkipTypes(abstractPtrs)
  1649. if baseType.kind in {tyObject, tyTuple} and not baseType.n.isNil and
  1650. (x.kind in {nkObjectTy, nkTupleTy} or
  1651. (x.kind in {nkRefTy, nkPtrTy} and x.len == 1 and
  1652. x[0].kind in {nkObjectTy, nkTupleTy})
  1653. ):
  1654. checkForMetaFields(c, baseType.n, hasError)
  1655. if not hasError:
  1656. checkConstructedType(c.config, s.info, s.typ)
  1657. # fix bug #5170, bug #17162, bug #15526: ensure locally scoped types get a unique name:
  1658. if s.typ.kind in {tyEnum, tyRef, tyObject} and not isTopLevel(c):
  1659. incl(s.flags, sfGenSym)
  1660. #instAllTypeBoundOp(c, n.info)
  1661. proc semAllTypeSections(c: PContext; n: PNode): PNode =
  1662. proc gatherStmts(c: PContext; n: PNode; result: PNode) {.nimcall.} =
  1663. case n.kind
  1664. of nkIncludeStmt:
  1665. for i in 0..<n.len:
  1666. var f = checkModuleName(c.config, n[i])
  1667. if f != InvalidFileIdx:
  1668. if containsOrIncl(c.includedFiles, f.int):
  1669. localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
  1670. else:
  1671. let code = c.graph.includeFileCallback(c.graph, c.module, f)
  1672. gatherStmts c, code, result
  1673. excl(c.includedFiles, f.int)
  1674. of nkStmtList:
  1675. for i in 0..<n.len:
  1676. gatherStmts(c, n[i], result)
  1677. of nkTypeSection:
  1678. incl n.flags, nfSem
  1679. typeSectionLeftSidePass(c, n)
  1680. result.add n
  1681. else:
  1682. result.add n
  1683. result = newNodeI(nkStmtList, n.info)
  1684. gatherStmts(c, n, result)
  1685. template rec(name) =
  1686. for i in 0..<result.len:
  1687. if result[i].kind == nkTypeSection:
  1688. name(c, result[i])
  1689. rec typeSectionRightSidePass
  1690. rec typeSectionFinalPass
  1691. when false:
  1692. # too beautiful to delete:
  1693. template rec(name; setbit=false) =
  1694. proc `name rec`(c: PContext; n: PNode) {.nimcall.} =
  1695. if n.kind == nkTypeSection:
  1696. when setbit: incl n.flags, nfSem
  1697. name(c, n)
  1698. elif n.kind == nkStmtList:
  1699. for i in 0..<n.len:
  1700. `name rec`(c, n[i])
  1701. `name rec`(c, n)
  1702. rec typeSectionLeftSidePass, true
  1703. rec typeSectionRightSidePass
  1704. rec typeSectionFinalPass
  1705. proc semTypeSection(c: PContext, n: PNode): PNode =
  1706. ## Processes a type section. This must be done in separate passes, in order
  1707. ## to allow the type definitions in the section to reference each other
  1708. ## without regard for the order of their definitions.
  1709. if sfNoForward notin c.module.flags or nfSem notin n.flags:
  1710. inc c.inTypeContext
  1711. typeSectionLeftSidePass(c, n)
  1712. typeSectionRightSidePass(c, n)
  1713. typeSectionFinalPass(c, n)
  1714. dec c.inTypeContext
  1715. result = n
  1716. proc semParamList(c: PContext, n, genericParams: PNode, s: PSym) =
  1717. s.typ = semProcTypeNode(c, n, genericParams, nil, s.kind)
  1718. proc addParams(c: PContext, n: PNode, kind: TSymKind) =
  1719. for i in 1..<n.len:
  1720. if n[i].kind == nkSym: addParamOrResult(c, n[i].sym, kind)
  1721. else: illFormedAst(n, c.config)
  1722. proc semBorrow(c: PContext, n: PNode, s: PSym) =
  1723. # search for the correct alias:
  1724. var (b, state) = searchForBorrowProc(c, c.currentScope.parent, s)
  1725. case state
  1726. of bsMatch:
  1727. # store the alias:
  1728. n[bodyPos] = newSymNode(b)
  1729. # Carry over the original symbol magic, this is necessary in order to ensure
  1730. # the semantic pass is correct
  1731. s.magic = b.magic
  1732. if b.typ != nil and b.typ.len > 0:
  1733. s.typ.n[0] = b.typ.n[0]
  1734. s.typ.flags = b.typ.flags
  1735. of bsNoDistinct:
  1736. localError(c.config, n.info, "borrow proc without distinct type parameter is meaningless")
  1737. of bsReturnNotMatch:
  1738. localError(c.config, n.info, "borrow from proc return type mismatch: '$1'" % typeToString(b.typ.returnType))
  1739. of bsGeneric:
  1740. localError(c.config, n.info, "borrow with generic parameter is not supported")
  1741. of bsNotSupported:
  1742. localError(c.config, n.info, "borrow from '$1' is not supported" % $b.name.s)
  1743. else:
  1744. localError(c.config, n.info, errNoSymbolToBorrowFromFound)
  1745. proc swapResult(n: PNode, sRes: PSym, dNode: PNode) =
  1746. ## Swap nodes that are (skResult) symbols to d(estination)Node.
  1747. for i in 0..<n.safeLen:
  1748. if n[i].kind == nkSym and n[i].sym == sRes:
  1749. n[i] = dNode
  1750. swapResult(n[i], sRes, dNode)
  1751. proc addResult(c: PContext, n: PNode, t: PType, owner: TSymKind) =
  1752. template genResSym(s) =
  1753. var s = newSym(skResult, getIdent(c.cache, "result"), c.idgen,
  1754. getCurrOwner(c), n.info)
  1755. s.typ = t
  1756. incl(s.flags, sfUsed)
  1757. if owner == skMacro or t != nil:
  1758. if n.len > resultPos and n[resultPos] != nil:
  1759. if n[resultPos].sym.kind != skResult:
  1760. localError(c.config, n.info, "incorrect result proc symbol")
  1761. if n[resultPos].sym.owner != getCurrOwner(c):
  1762. # re-write result with new ownership, and re-write the proc accordingly
  1763. let sResSym = n[resultPos].sym
  1764. genResSym(s)
  1765. n[resultPos] = newSymNode(s)
  1766. swapResult(n, sResSym, n[resultPos])
  1767. c.p.resultSym = n[resultPos].sym
  1768. else:
  1769. genResSym(s)
  1770. c.p.resultSym = s
  1771. n.add newSymNode(c.p.resultSym)
  1772. addParamOrResult(c, c.p.resultSym, owner)
  1773. proc semProcAnnotation(c: PContext, prc: PNode;
  1774. validPragmas: TSpecialWords): PNode =
  1775. # Mirrored with semVarMacroPragma
  1776. result = nil
  1777. var n = prc[pragmasPos]
  1778. if n == nil or n.kind == nkEmpty: return
  1779. for i in 0..<n.len:
  1780. let it = n[i]
  1781. let key = if it.kind in nkPragmaCallKinds and it.len >= 1: it[0] else: it
  1782. trySuggestPragmas(c, key)
  1783. if isPossibleMacroPragma(c, it, key):
  1784. # we transform ``proc p {.m, rest.}`` into ``m(do: proc p {.rest.})`` and
  1785. # let the semantic checker deal with it:
  1786. var x = newNodeI(nkCall, key.info)
  1787. x.add(key)
  1788. if it.kind in nkPragmaCallKinds and it.len > 1:
  1789. # pass pragma arguments to the macro too:
  1790. for i in 1..<it.len:
  1791. x.add(it[i])
  1792. # Drop the pragma from the list, this prevents getting caught in endless
  1793. # recursion when the nkCall is semanticized
  1794. prc[pragmasPos] = copyExcept(n, i)
  1795. if prc[pragmasPos].kind != nkEmpty and prc[pragmasPos].len == 0:
  1796. prc[pragmasPos] = c.graph.emptyNode
  1797. x.add(prc)
  1798. # recursion assures that this works for multiple macro annotations too:
  1799. var r = semOverloadedCall(c, x, x, {skMacro, skTemplate}, {efNoUndeclared})
  1800. if r == nil:
  1801. # Restore the old list of pragmas since we couldn't process this
  1802. prc[pragmasPos] = n
  1803. # No matching macro was found but there's always the possibility this may
  1804. # be a .pragma. template instead
  1805. continue
  1806. doAssert r[0].kind == nkSym
  1807. let m = r[0].sym
  1808. case m.kind
  1809. of skMacro: result = semMacroExpr(c, r, r, m, {})
  1810. of skTemplate: result = semTemplateExpr(c, r, m, {})
  1811. else:
  1812. prc[pragmasPos] = n
  1813. continue
  1814. doAssert result != nil
  1815. return result
  1816. proc semInferredLambda(c: PContext, pt: TypeMapping, n: PNode): PNode =
  1817. ## used for resolving 'auto' in lambdas based on their callsite
  1818. var n = n
  1819. let original = n[namePos].sym
  1820. let s = original #copySym(original, false)
  1821. #incl(s.flags, sfFromGeneric)
  1822. #s.owner = original
  1823. n = replaceTypesInBody(c, pt, n, original)
  1824. result = n
  1825. s.ast = result
  1826. n[namePos].sym = s
  1827. n[genericParamsPos] = c.graph.emptyNode
  1828. # for LL we need to avoid wrong aliasing
  1829. let params = copyTree n.typ.n
  1830. s.typ = n.typ
  1831. for i in 1..<params.len:
  1832. if params[i].typ.kind in {tyTypeDesc, tyGenericParam,
  1833. tyFromExpr}+tyTypeClasses:
  1834. localError(c.config, params[i].info, "cannot infer type of parameter: " &
  1835. params[i].sym.name.s)
  1836. #params[i].sym.owner = s
  1837. openScope(c)
  1838. pushOwner(c, s)
  1839. addParams(c, params, skProc)
  1840. pushProcCon(c, s)
  1841. addResult(c, n, n.typ.returnType, skProc)
  1842. s.ast[bodyPos] = hloBody(c, semProcBody(c, n[bodyPos], n.typ.returnType))
  1843. trackProc(c, s, s.ast[bodyPos])
  1844. popProcCon(c)
  1845. popOwner(c)
  1846. closeScope(c)
  1847. if optOwnedRefs in c.config.globalOptions and result.typ != nil:
  1848. result.typ = makeVarType(c, result.typ, tyOwned)
  1849. # alternative variant (not quite working):
  1850. # var prc = arg[0].sym
  1851. # let inferred = c.semGenerateInstance(c, prc, m.bindings, arg.info)
  1852. # result = inferred.ast
  1853. # result.kind = arg.kind
  1854. proc activate(c: PContext, n: PNode) =
  1855. # XXX: This proc is part of my plan for getting rid of
  1856. # forward declarations. stay tuned.
  1857. when false:
  1858. # well for now it breaks code ...
  1859. case n.kind
  1860. of nkLambdaKinds:
  1861. discard semLambda(c, n, {})
  1862. of nkCallKinds:
  1863. for i in 1..<n.len: activate(c, n[i])
  1864. else:
  1865. discard
  1866. proc maybeAddResult(c: PContext, s: PSym, n: PNode) =
  1867. if s.kind == skMacro:
  1868. let resultType = sysTypeFromName(c.graph, n.info, "NimNode")
  1869. addResult(c, n, resultType, s.kind)
  1870. elif s.typ.returnType != nil and not isInlineIterator(s.typ):
  1871. addResult(c, n, s.typ.returnType, s.kind)
  1872. proc canonType(c: PContext, t: PType): PType =
  1873. if t.kind == tySequence:
  1874. result = c.graph.sysTypes[tySequence]
  1875. else:
  1876. result = t
  1877. proc prevDestructor(c: PContext; prevOp: PSym; obj: PType; info: TLineInfo) =
  1878. var msg = "cannot bind another '" & prevOp.name.s & "' to: " & typeToString(obj)
  1879. if sfOverridden notin prevOp.flags:
  1880. msg.add "; previous declaration was constructed here implicitly: " & (c.config $ prevOp.info)
  1881. else:
  1882. msg.add "; previous declaration was here: " & (c.config $ prevOp.info)
  1883. localError(c.config, info, errGenerated, msg)
  1884. proc whereToBindTypeHook(c: PContext; t: PType): PType =
  1885. result = t
  1886. while true:
  1887. if result.kind in {tyGenericBody, tyGenericInst}: result = result.skipModifier
  1888. elif result.kind == tyGenericInvocation: result = result[0]
  1889. else: break
  1890. if result.kind in {tyObject, tyDistinct, tySequence, tyString}:
  1891. result = canonType(c, result)
  1892. proc bindDupHook(c: PContext; s: PSym; n: PNode; op: TTypeAttachedOp) =
  1893. let t = s.typ
  1894. var noError = false
  1895. let cond = t.len == 2 and t.returnType != nil
  1896. if cond:
  1897. var obj = t.firstParamType
  1898. while true:
  1899. incl(obj.flags, tfHasAsgn)
  1900. if obj.kind in {tyGenericBody, tyGenericInst}: obj = obj.skipModifier
  1901. elif obj.kind == tyGenericInvocation: obj = obj.genericHead
  1902. else: break
  1903. var res = t.returnType
  1904. while true:
  1905. if res.kind in {tyGenericBody, tyGenericInst}: res = res.skipModifier
  1906. elif res.kind == tyGenericInvocation: res = res.genericHead
  1907. else: break
  1908. if obj.kind in {tyObject, tyDistinct, tySequence, tyString} and sameType(obj, res):
  1909. obj = canonType(c, obj)
  1910. let ao = getAttachedOp(c.graph, obj, op)
  1911. if ao == s:
  1912. discard "forward declared destructor"
  1913. elif ao.isNil and tfCheckedForDestructor notin obj.flags:
  1914. setAttachedOp(c.graph, c.module.position, obj, op, s)
  1915. else:
  1916. prevDestructor(c, ao, obj, n.info)
  1917. noError = true
  1918. if obj.owner.getModule != s.getModule:
  1919. localError(c.config, n.info, errGenerated,
  1920. "type bound operation `" & s.name.s & "` can be defined only in the same module with its type (" & obj.typeToString() & ")")
  1921. if not noError and sfSystemModule notin s.owner.flags:
  1922. localError(c.config, n.info, errGenerated,
  1923. "signature for '=dup' must be proc[T: object](x: T): T")
  1924. incl(s.flags, sfUsed)
  1925. incl(s.flags, sfOverridden)
  1926. proc bindTypeHook(c: PContext; s: PSym; n: PNode; op: TTypeAttachedOp; suppressVarDestructorWarning = false) =
  1927. let t = s.typ
  1928. var noError = false
  1929. let cond = case op
  1930. of attachedWasMoved:
  1931. t.len == 2 and t.returnType == nil and t.firstParamType.kind == tyVar
  1932. of attachedTrace:
  1933. t.len == 3 and t.returnType == nil and t.firstParamType.kind == tyVar and t[2].kind == tyPointer
  1934. of attachedDestructor:
  1935. if c.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  1936. t.len == 2 and t.returnType == nil
  1937. else:
  1938. t.len == 2 and t.returnType == nil and t.firstParamType.kind == tyVar
  1939. else:
  1940. t.len >= 2 and t.returnType == nil
  1941. if cond:
  1942. var obj = t.firstParamType.skipTypes({tyVar})
  1943. while true:
  1944. incl(obj.flags, tfHasAsgn)
  1945. if obj.kind in {tyGenericBody, tyGenericInst}: obj = obj.skipModifier
  1946. elif obj.kind == tyGenericInvocation: obj = obj.genericHead
  1947. else: break
  1948. if obj.kind in {tyObject, tyDistinct, tySequence, tyString}:
  1949. if (not suppressVarDestructorWarning) and op == attachedDestructor and t.firstParamType.kind == tyVar and
  1950. c.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  1951. message(c.config, n.info, warnDeprecated, "A custom '=destroy' hook which takes a 'var T' parameter is deprecated; it should take a 'T' parameter")
  1952. obj = canonType(c, obj)
  1953. let ao = getAttachedOp(c.graph, obj, op)
  1954. if ao == s:
  1955. discard "forward declared destructor"
  1956. elif ao.isNil and tfCheckedForDestructor notin obj.flags:
  1957. setAttachedOp(c.graph, c.module.position, obj, op, s)
  1958. else:
  1959. prevDestructor(c, ao, obj, n.info)
  1960. noError = true
  1961. if obj.owner.getModule != s.getModule:
  1962. localError(c.config, n.info, errGenerated,
  1963. "type bound operation `" & s.name.s & "` can be defined only in the same module with its type (" & obj.typeToString() & ")")
  1964. if not noError and sfSystemModule notin s.owner.flags:
  1965. case op
  1966. of attachedTrace:
  1967. localError(c.config, n.info, errGenerated,
  1968. "signature for '=trace' must be proc[T: object](x: var T; env: pointer)")
  1969. of attachedDestructor:
  1970. if c.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  1971. localError(c.config, n.info, errGenerated,
  1972. "signature for '=destroy' must be proc[T: object](x: var T) or proc[T: object](x: T)")
  1973. else:
  1974. localError(c.config, n.info, errGenerated,
  1975. "signature for '=destroy' must be proc[T: object](x: var T)")
  1976. else:
  1977. localError(c.config, n.info, errGenerated,
  1978. "signature for '" & s.name.s & "' must be proc[T: object](x: var T)")
  1979. incl(s.flags, sfUsed)
  1980. incl(s.flags, sfOverridden)
  1981. proc semOverride(c: PContext, s: PSym, n: PNode) =
  1982. let name = s.name.s.normalize
  1983. case name
  1984. of "=destroy":
  1985. bindTypeHook(c, s, n, attachedDestructor)
  1986. if s.ast != nil:
  1987. if s.ast[pragmasPos].kind == nkEmpty:
  1988. s.ast[pragmasPos] = newNodeI(nkPragma, s.info)
  1989. s.ast[pragmasPos].add newTree(nkExprColonExpr,
  1990. newIdentNode(c.cache.getIdent("raises"), s.info), newNodeI(nkBracket, s.info))
  1991. of "deepcopy", "=deepcopy":
  1992. if s.typ.len == 2 and
  1993. s.typ.firstParamType.skipTypes(abstractInst).kind in {tyRef, tyPtr} and
  1994. sameType(s.typ.firstParamType, s.typ.returnType):
  1995. # Note: we store the deepCopy in the base of the pointer to mitigate
  1996. # the problem that pointers are structural types:
  1997. var t = s.typ.firstParamType.skipTypes(abstractInst).elementType.skipTypes(abstractInst)
  1998. while true:
  1999. if t.kind == tyGenericBody: t = t.typeBodyImpl
  2000. elif t.kind == tyGenericInvocation: t = t.genericHead
  2001. else: break
  2002. if t.kind in {tyObject, tyDistinct, tyEnum, tySequence, tyString}:
  2003. if getAttachedOp(c.graph, t, attachedDeepCopy).isNil:
  2004. setAttachedOp(c.graph, c.module.position, t, attachedDeepCopy, s)
  2005. else:
  2006. localError(c.config, n.info, errGenerated,
  2007. "cannot bind another 'deepCopy' to: " & typeToString(t))
  2008. else:
  2009. localError(c.config, n.info, errGenerated,
  2010. "cannot bind 'deepCopy' to: " & typeToString(t))
  2011. if t.owner.getModule != s.getModule:
  2012. localError(c.config, n.info, errGenerated,
  2013. "type bound operation `" & name & "` can be defined only in the same module with its type (" & t.typeToString() & ")")
  2014. else:
  2015. localError(c.config, n.info, errGenerated,
  2016. "signature for 'deepCopy' must be proc[T: ptr|ref](x: T): T")
  2017. incl(s.flags, sfUsed)
  2018. incl(s.flags, sfOverridden)
  2019. of "=", "=copy", "=sink":
  2020. if s.magic == mAsgn: return
  2021. incl(s.flags, sfUsed)
  2022. incl(s.flags, sfOverridden)
  2023. if name == "=":
  2024. message(c.config, n.info, warnDeprecated, "Overriding `=` hook is deprecated; Override `=copy` hook instead")
  2025. let t = s.typ
  2026. if t.len == 3 and t.returnType == nil and t.firstParamType.kind == tyVar:
  2027. var obj = t.firstParamType.elementType
  2028. while true:
  2029. incl(obj.flags, tfHasAsgn)
  2030. if obj.kind == tyGenericBody: obj = obj.skipModifier
  2031. elif obj.kind == tyGenericInvocation: obj = obj.genericHead
  2032. else: break
  2033. var objB = t[2]
  2034. while true:
  2035. if objB.kind == tyGenericBody: objB = objB.skipModifier
  2036. elif objB.kind in {tyGenericInvocation, tyGenericInst}:
  2037. objB = objB.genericHead
  2038. else: break
  2039. if obj.kind in {tyObject, tyDistinct, tySequence, tyString} and sameType(obj, objB):
  2040. # attach these ops to the canonical tySequence
  2041. obj = canonType(c, obj)
  2042. #echo "ATTACHING TO ", obj.id, " ", s.name.s, " ", cast[int](obj)
  2043. let k = if name == "=" or name == "=copy": attachedAsgn else: attachedSink
  2044. let ao = getAttachedOp(c.graph, obj, k)
  2045. if ao == s:
  2046. discard "forward declared op"
  2047. elif ao.isNil and tfCheckedForDestructor notin obj.flags:
  2048. setAttachedOp(c.graph, c.module.position, obj, k, s)
  2049. else:
  2050. prevDestructor(c, ao, obj, n.info)
  2051. if obj.owner.getModule != s.getModule:
  2052. localError(c.config, n.info, errGenerated,
  2053. "type bound operation `" & name & "` can be defined only in the same module with its type (" & obj.typeToString() & ")")
  2054. return
  2055. if sfSystemModule notin s.owner.flags:
  2056. localError(c.config, n.info, errGenerated,
  2057. "signature for '" & s.name.s & "' must be proc[T: object](x: var T; y: T)")
  2058. of "=trace":
  2059. if s.magic != mTrace:
  2060. bindTypeHook(c, s, n, attachedTrace)
  2061. of "=wasmoved":
  2062. if s.magic != mWasMoved:
  2063. bindTypeHook(c, s, n, attachedWasMoved)
  2064. of "=dup":
  2065. if s.magic != mDup:
  2066. bindDupHook(c, s, n, attachedDup)
  2067. else:
  2068. if sfOverridden in s.flags:
  2069. localError(c.config, n.info, errGenerated,
  2070. "'destroy' or 'deepCopy' expected for 'override'")
  2071. proc cursorInProcAux(conf: ConfigRef; n: PNode): bool =
  2072. result = false
  2073. if inCheckpoint(n.info, conf.m.trackPos) != cpNone: return true
  2074. for i in 0..<n.safeLen:
  2075. if cursorInProcAux(conf, n[i]): return true
  2076. proc cursorInProc(conf: ConfigRef; n: PNode): bool =
  2077. if n.info.fileIndex == conf.m.trackPos.fileIndex:
  2078. result = cursorInProcAux(conf, n)
  2079. else:
  2080. result = false
  2081. proc hasObjParam(s: PSym): bool =
  2082. result = false
  2083. var t = s.typ
  2084. for col in 1..<t.len:
  2085. if skipTypes(t[col], skipPtrs).kind == tyObject:
  2086. return true
  2087. proc finishMethod(c: PContext, s: PSym) =
  2088. if hasObjParam(s):
  2089. methodDef(c.graph, c.idgen, s)
  2090. proc semCppMember(c: PContext; s: PSym; n: PNode) =
  2091. if sfImportc notin s.flags:
  2092. let isVirtual = sfVirtual in s.flags
  2093. let isCtor = sfConstructor in s.flags
  2094. let pragmaName = if isVirtual: "virtual" elif isCtor: "constructor" else: "member"
  2095. if c.config.backend == backendCpp:
  2096. if s.typ.len < 2 and not isCtor:
  2097. localError(c.config, n.info, pragmaName & " must have at least one parameter")
  2098. for son in s.typ.signature:
  2099. if son!=nil and son.isMetaType:
  2100. localError(c.config, n.info, pragmaName & " unsupported for generic routine")
  2101. var typ: PType
  2102. if isCtor:
  2103. typ = s.typ.returnType
  2104. if typ == nil or typ.kind != tyObject:
  2105. localError(c.config, n.info, "constructor must return an object")
  2106. if sfImportc in typ.sym.flags:
  2107. localError(c.config, n.info, "constructor in an imported type needs importcpp pragma")
  2108. else:
  2109. typ = s.typ.firstParamType
  2110. if typ.kind == tyPtr and not isCtor:
  2111. typ = typ.elementType
  2112. if typ.kind != tyObject:
  2113. localError(c.config, n.info, pragmaName & " must be either ptr to object or object type.")
  2114. if typ.owner.id == s.owner.id and c.module.id == s.owner.id:
  2115. c.graph.memberProcsPerType.mgetOrPut(typ.itemId, @[]).add s
  2116. else:
  2117. localError(c.config, n.info,
  2118. pragmaName & " procs must be defined in the same scope as the type they are virtual for and it must be a top level scope")
  2119. else:
  2120. localError(c.config, n.info, pragmaName & " procs are only supported in C++")
  2121. else:
  2122. var typ = s.typ.returnType
  2123. if typ != nil and typ.kind == tyObject and typ.itemId notin c.graph.initializersPerType:
  2124. var initializerCall = newTree(nkCall, newSymNode(s))
  2125. var isInitializer = n[paramsPos].len > 1
  2126. for i in 1..<n[paramsPos].len:
  2127. let p = n[paramsPos][i]
  2128. let val = p[^1]
  2129. if val.kind == nkEmpty:
  2130. isInitializer = false
  2131. break
  2132. var j = 0
  2133. while p[j].sym.kind == skParam:
  2134. initializerCall.add val
  2135. inc j
  2136. if isInitializer:
  2137. c.graph.initializersPerType[typ.itemId] = initializerCall
  2138. proc semMethodPrototype(c: PContext; s: PSym; n: PNode) =
  2139. if s.isGenericRoutine:
  2140. let tt = s.typ
  2141. var foundObj = false
  2142. # we start at 1 for now so that tparsecombnum continues to compile.
  2143. # XXX Revisit this problem later.
  2144. for col in 1..<tt.len:
  2145. let t = tt[col]
  2146. if t != nil and t.kind == tyGenericInvocation:
  2147. var x = skipTypes(t.genericHead, {tyVar, tyLent, tyPtr, tyRef, tyGenericInst,
  2148. tyGenericInvocation, tyGenericBody,
  2149. tyAlias, tySink, tyOwned})
  2150. if x.kind == tyObject and t.len-1 == n[genericParamsPos].len:
  2151. foundObj = true
  2152. addMethodToGeneric(c.graph, c.module.position, x, col, s)
  2153. message(c.config, n.info, warnDeprecated, "generic methods are deprecated")
  2154. #if not foundObj:
  2155. # message(c.config, n.info, warnDeprecated, "generic method not attachable to object type is deprecated")
  2156. else:
  2157. # why check for the body? bug #2400 has none. Checking for sfForward makes
  2158. # no sense either.
  2159. # and result[bodyPos].kind != nkEmpty:
  2160. if hasObjParam(s):
  2161. methodDef(c.graph, c.idgen, s)
  2162. else:
  2163. localError(c.config, n.info, "'method' needs a parameter that has an object type")
  2164. proc semProcAux(c: PContext, n: PNode, kind: TSymKind,
  2165. validPragmas: TSpecialWords, flags: TExprFlags = {}): PNode =
  2166. result = semProcAnnotation(c, n, validPragmas)
  2167. if result != nil: return result
  2168. result = n
  2169. checkMinSonsLen(n, bodyPos + 1, c.config)
  2170. let
  2171. isAnon = n[namePos].kind == nkEmpty
  2172. isHighlight = c.config.ideCmd == ideHighlight
  2173. var s: PSym
  2174. case n[namePos].kind
  2175. of nkEmpty:
  2176. s = newSym(kind, c.cache.idAnon, c.idgen, c.getCurrOwner, n.info)
  2177. s.flags.incl sfUsed
  2178. n[namePos] = newSymNode(s)
  2179. of nkSym:
  2180. s = n[namePos].sym
  2181. s.owner = c.getCurrOwner
  2182. else:
  2183. # Highlighting needs to be done early so the position for
  2184. # name isn't changed (see taccent_highlight). We don't want to check if this is the
  2185. # defintion yet since we are missing some info (comments, side effects)
  2186. s = semIdentDef(c, n[namePos], kind, reportToNimsuggest=isHighlight)
  2187. n[namePos] = newSymNode(s)
  2188. when false:
  2189. # disable for now
  2190. if sfNoForward in c.module.flags and
  2191. sfSystemModule notin c.module.flags:
  2192. addInterfaceOverloadableSymAt(c, c.currentScope, s)
  2193. s.flags.incl sfForward
  2194. return
  2195. assert s.kind in skProcKinds
  2196. s.ast = n
  2197. s.options = c.config.options
  2198. #s.scope = c.currentScope
  2199. if s.kind in {skMacro, skTemplate}:
  2200. # push noalias flag at first to prevent unwanted recursive calls:
  2201. incl(s.flags, sfNoalias)
  2202. # before compiling the proc params & body, set as current the scope
  2203. # where the proc was declared
  2204. let declarationScope = c.currentScope
  2205. pushOwner(c, s)
  2206. openScope(c)
  2207. # process parameters:
  2208. # generic parameters, parameters, and also the implicit generic parameters
  2209. # within are analysed. This is often the entirety of their semantic analysis
  2210. # but later we will have to do a check for forward declarations, which can by
  2211. # way of pragmas, default params, and so on invalidate this parsing.
  2212. # Nonetheless, we need to carry out this analysis to perform the search for a
  2213. # potential forward declaration.
  2214. setGenericParamsMisc(c, n)
  2215. if n[paramsPos].kind != nkEmpty:
  2216. semParamList(c, n[paramsPos], n[genericParamsPos], s)
  2217. else:
  2218. s.typ = newProcType(c, n.info)
  2219. if n[genericParamsPos].safeLen == 0:
  2220. # if there exist no explicit or implicit generic parameters, then this is
  2221. # at most a nullary generic (generic with no type params). Regardless of
  2222. # whether it's a nullary generic or non-generic, we restore the original.
  2223. # In the case of `nkEmpty` it's non-generic and an empty `nkGeneircParams`
  2224. # is a nullary generic.
  2225. #
  2226. # Remarks about nullary generics vs non-generics:
  2227. # The difference between a non-generic and nullary generic is minor in
  2228. # most cases but there are subtle and significant differences as well.
  2229. # Due to instantiation that generic procs go through, a static echo in the
  2230. # body of a nullary generic will not be executed immediately, as it's
  2231. # instantiated and not immediately evaluated.
  2232. n[genericParamsPos] = n[miscPos][1]
  2233. n[miscPos] = c.graph.emptyNode
  2234. if tfTriggersCompileTime in s.typ.flags: incl(s.flags, sfCompileTime)
  2235. if n[patternPos].kind != nkEmpty:
  2236. n[patternPos] = semPattern(c, n[patternPos], s)
  2237. if s.kind == skIterator:
  2238. s.typ.flags.incl(tfIterator)
  2239. elif s.kind == skFunc:
  2240. incl(s.flags, sfNoSideEffect)
  2241. incl(s.typ.flags, tfNoSideEffect)
  2242. var (proto, comesFromShadowScope) =
  2243. if isAnon: (nil, false)
  2244. else: searchForProc(c, declarationScope, s)
  2245. if proto == nil and sfForward in s.flags and n[bodyPos].kind != nkEmpty:
  2246. ## In cases such as a macro generating a proc with a gensymmed name we
  2247. ## know `searchForProc` will not find it and sfForward will be set. In
  2248. ## such scenarios the sym is shared between forward declaration and we
  2249. ## can treat the `s` as the proto.
  2250. ## To differentiate between that happening and a macro just returning a
  2251. ## forward declaration that has been typed before we check if the body
  2252. ## is not empty. This has the sideeffect of allowing multiple forward
  2253. ## declarations if they share the same sym.
  2254. ## See the "doubly-typed forward decls" case in tmacros_issues.nim
  2255. proto = s
  2256. let hasProto = proto != nil
  2257. # set the default calling conventions
  2258. case s.kind
  2259. of skIterator:
  2260. if s.typ.callConv != ccClosure:
  2261. s.typ.callConv = if isAnon: ccClosure else: ccInline
  2262. of skMacro, skTemplate:
  2263. # we don't bother setting calling conventions for macros and templates
  2264. discard
  2265. else:
  2266. # NB: procs with a forward decl have theirs determined by the forward decl
  2267. if not hasProto:
  2268. # in this case we're either a forward declaration or we're an impl without
  2269. # a forward decl. We set the calling convention or will be set during
  2270. # pragma analysis further down.
  2271. s.typ.callConv = lastOptionEntry(c).defaultCC
  2272. if not hasProto and sfGenSym notin s.flags: #and not isAnon:
  2273. if s.kind in OverloadableSyms:
  2274. addInterfaceOverloadableSymAt(c, declarationScope, s)
  2275. else:
  2276. addInterfaceDeclAt(c, declarationScope, s)
  2277. pragmaCallable(c, s, n, validPragmas)
  2278. if not hasProto:
  2279. implicitPragmas(c, s, n.info, validPragmas)
  2280. if n[pragmasPos].kind != nkEmpty and sfBorrow notin s.flags:
  2281. setEffectsForProcType(c.graph, s.typ, n[pragmasPos], s)
  2282. s.typ.flags.incl tfEffectSystemWorkaround
  2283. # To ease macro generation that produce forwarded .async procs we now
  2284. # allow a bit redundancy in the pragma declarations. The rule is
  2285. # a prototype's pragma list must be a superset of the current pragma
  2286. # list.
  2287. # XXX This needs more checks eventually, for example that external
  2288. # linking names do agree:
  2289. if hasProto and (
  2290. # calling convention mismatch
  2291. tfExplicitCallConv in s.typ.flags and proto.typ.callConv != s.typ.callConv or
  2292. # implementation has additional pragmas
  2293. proto.typ.flags < s.typ.flags):
  2294. localError(c.config, n[pragmasPos].info, errPragmaOnlyInHeaderOfProcX %
  2295. ("'" & proto.name.s & "' from " & c.config$proto.info &
  2296. " '" & s.name.s & "' from " & c.config$s.info))
  2297. styleCheckDef(c, s)
  2298. if hasProto:
  2299. onDefResolveForward(n[namePos].info, proto)
  2300. else:
  2301. onDef(n[namePos].info, s)
  2302. if hasProto:
  2303. if sfForward notin proto.flags and proto.magic == mNone:
  2304. wrongRedefinition(c, n.info, proto.name.s, proto.info)
  2305. if not comesFromShadowScope:
  2306. excl(proto.flags, sfForward)
  2307. incl(proto.flags, sfWasForwarded)
  2308. suggestSym(c.graph, s.info, proto, c.graph.usageSym)
  2309. closeScope(c) # close scope with wrong parameter symbols
  2310. openScope(c) # open scope for old (correct) parameter symbols
  2311. if proto.ast[genericParamsPos].isGenericParams:
  2312. addGenericParamListToScope(c, proto.ast[genericParamsPos])
  2313. addParams(c, proto.typ.n, proto.kind)
  2314. proto.info = s.info # more accurate line information
  2315. proto.options = s.options
  2316. s = proto
  2317. n[genericParamsPos] = proto.ast[genericParamsPos]
  2318. n[paramsPos] = proto.ast[paramsPos]
  2319. n[pragmasPos] = proto.ast[pragmasPos]
  2320. if n[namePos].kind != nkSym: internalError(c.config, n.info, "semProcAux")
  2321. n[namePos].sym = proto
  2322. if importantComments(c.config) and proto.ast.comment.len > 0:
  2323. n.comment = proto.ast.comment
  2324. proto.ast = n # needed for code generation
  2325. popOwner(c)
  2326. pushOwner(c, s)
  2327. if not isAnon:
  2328. if sfOverridden in s.flags or s.name.s[0] == '=': semOverride(c, s, n)
  2329. elif s.name.s[0] in {'.', '('}:
  2330. if s.name.s in [".", ".()", ".="] and {Feature.destructor, dotOperators} * c.features == {}:
  2331. localError(c.config, n.info, "the overloaded " & s.name.s &
  2332. " operator has to be enabled with {.experimental: \"dotOperators\".}")
  2333. elif s.name.s == "()" and callOperator notin c.features:
  2334. localError(c.config, n.info, "the overloaded " & s.name.s &
  2335. " operator has to be enabled with {.experimental: \"callOperator\".}")
  2336. if sfBorrow in s.flags and c.config.cmd notin cmdDocLike:
  2337. result[bodyPos] = c.graph.emptyNode
  2338. if sfCppMember * s.flags != {} and sfWasForwarded notin s.flags:
  2339. semCppMember(c, s, n)
  2340. if n[bodyPos].kind != nkEmpty and sfError notin s.flags:
  2341. # for DLL generation we allow sfImportc to have a body, for use in VM
  2342. if c.config.ideCmd in {ideSug, ideCon} and s.kind notin {skMacro, skTemplate} and not
  2343. cursorInProc(c.config, n[bodyPos]):
  2344. # speed up nimsuggest
  2345. if s.kind == skMethod: semMethodPrototype(c, s, n)
  2346. elif isAnon:
  2347. let gp = n[genericParamsPos]
  2348. if gp.kind == nkEmpty or (gp.len == 1 and tfRetType in gp[0].typ.flags):
  2349. # absolutely no generics (empty) or a single generic return type are
  2350. # allowed, everything else, including a nullary generic is an error.
  2351. pushProcCon(c, s)
  2352. addResult(c, n, s.typ.returnType, skProc)
  2353. s.ast[bodyPos] = hloBody(c, semProcBody(c, n[bodyPos], s.typ.returnType))
  2354. trackProc(c, s, s.ast[bodyPos])
  2355. popProcCon(c)
  2356. elif efOperand notin flags:
  2357. localError(c.config, n.info, errGenericLambdaNotAllowed)
  2358. else:
  2359. pushProcCon(c, s)
  2360. if n[genericParamsPos].kind == nkEmpty or s.kind in {skMacro, skTemplate}:
  2361. # Macros and Templates can have generic parameters, but they are only
  2362. # used for overload resolution (there is no instantiation of the symbol)
  2363. if s.kind notin {skMacro, skTemplate} and s.magic == mNone: paramsTypeCheck(c, s.typ)
  2364. maybeAddResult(c, s, n)
  2365. let resultType =
  2366. if s.kind == skMacro:
  2367. sysTypeFromName(c.graph, n.info, "NimNode")
  2368. elif not isInlineIterator(s.typ):
  2369. s.typ.returnType
  2370. else:
  2371. nil
  2372. # semantic checking also needed with importc in case used in VM
  2373. s.ast[bodyPos] = hloBody(c, semProcBody(c, n[bodyPos], resultType))
  2374. # unfortunately we cannot skip this step when in 'system.compiles'
  2375. # context as it may even be evaluated in 'system.compiles':
  2376. trackProc(c, s, s.ast[bodyPos])
  2377. else:
  2378. if (s.typ.returnType != nil and s.kind != skIterator):
  2379. addDecl(c, newSym(skUnknown, getIdent(c.cache, "result"), c.idgen, s, n.info))
  2380. openScope(c)
  2381. n[bodyPos] = semGenericStmt(c, n[bodyPos])
  2382. closeScope(c)
  2383. if s.magic == mNone:
  2384. fixupInstantiatedSymbols(c, s)
  2385. if s.kind == skMethod: semMethodPrototype(c, s, n)
  2386. popProcCon(c)
  2387. else:
  2388. if s.kind == skMethod: semMethodPrototype(c, s, n)
  2389. if hasProto: localError(c.config, n.info, errImplOfXexpected % proto.name.s)
  2390. if {sfImportc, sfBorrow, sfError} * s.flags == {} and s.magic == mNone:
  2391. # this is a forward declaration and we're building the prototype
  2392. if s.kind in {skProc, skFunc} and s.typ.returnType != nil and s.typ.returnType.kind == tyAnything:
  2393. localError(c.config, n[paramsPos][0].info, "return type 'auto' cannot be used in forward declarations")
  2394. incl(s.flags, sfForward)
  2395. incl(s.flags, sfWasForwarded)
  2396. elif sfBorrow in s.flags: semBorrow(c, n, s)
  2397. sideEffectsCheck(c, s)
  2398. closeScope(c) # close scope for parameters
  2399. # c.currentScope = oldScope
  2400. popOwner(c)
  2401. if n[patternPos].kind != nkEmpty:
  2402. c.patterns.add(s)
  2403. if isAnon:
  2404. n.transitionSonsKind(nkLambda)
  2405. result.typ = s.typ
  2406. if optOwnedRefs in c.config.globalOptions:
  2407. result.typ = makeVarType(c, result.typ, tyOwned)
  2408. elif isTopLevel(c) and s.kind != skIterator and s.typ.callConv == ccClosure:
  2409. localError(c.config, s.info, "'.closure' calling convention for top level routines is invalid")
  2410. # Prevent double highlights. We already highlighted before.
  2411. # When not highlighting we still need to allow for suggestions though
  2412. if not isHighlight:
  2413. suggestSym(c.graph, s.info, s, c.graph.usageSym)
  2414. proc determineType(c: PContext, s: PSym) =
  2415. if s.typ != nil: return
  2416. #if s.magic != mNone: return
  2417. #if s.ast.isNil: return
  2418. discard semProcAux(c, s.ast, s.kind, {})
  2419. proc semIterator(c: PContext, n: PNode): PNode =
  2420. # gensym'ed iterator?
  2421. if n[namePos].kind == nkSym:
  2422. # gensym'ed iterators might need to become closure iterators:
  2423. n[namePos].sym.owner = getCurrOwner(c)
  2424. n[namePos].sym.transitionRoutineSymKind(skIterator)
  2425. result = semProcAux(c, n, skIterator, iteratorPragmas)
  2426. # bug #7093: if after a macro transformation we don't have an
  2427. # nkIteratorDef aynmore, return. The iterator then might have been
  2428. # sem'checked already. (Or not, if the macro skips it.)
  2429. if result.kind != n.kind: return
  2430. var s = result[namePos].sym
  2431. var t = s.typ
  2432. if t.returnType == nil and s.typ.callConv != ccClosure:
  2433. localError(c.config, n.info, "iterator needs a return type")
  2434. # iterators are either 'inline' or 'closure'; for backwards compatibility,
  2435. # we require first class iterators to be marked with 'closure' explicitly
  2436. # -- at least for 0.9.2.
  2437. if s.typ.callConv == ccClosure:
  2438. incl(s.typ.flags, tfCapturesEnv)
  2439. else:
  2440. s.typ.callConv = ccInline
  2441. if n[bodyPos].kind == nkEmpty and s.magic == mNone and c.inConceptDecl == 0:
  2442. localError(c.config, n.info, errImplOfXexpected % s.name.s)
  2443. if optOwnedRefs in c.config.globalOptions and result.typ != nil:
  2444. result.typ = makeVarType(c, result.typ, tyOwned)
  2445. result.typ.callConv = ccClosure
  2446. proc semProc(c: PContext, n: PNode): PNode =
  2447. result = semProcAux(c, n, skProc, procPragmas)
  2448. proc semFunc(c: PContext, n: PNode): PNode =
  2449. let validPragmas = if n[namePos].kind != nkEmpty: procPragmas
  2450. else: lambdaPragmas
  2451. result = semProcAux(c, n, skFunc, validPragmas)
  2452. proc semMethod(c: PContext, n: PNode): PNode =
  2453. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "method")
  2454. result = semProcAux(c, n, skMethod, methodPragmas)
  2455. # macros can transform converters to nothing:
  2456. if namePos >= result.safeLen: return result
  2457. # bug #7093: if after a macro transformation we don't have an
  2458. # nkIteratorDef aynmore, return. The iterator then might have been
  2459. # sem'checked already. (Or not, if the macro skips it.)
  2460. if result.kind != nkMethodDef: return
  2461. var s = result[namePos].sym
  2462. # we need to fix the 'auto' return type for the dispatcher here (see tautonotgeneric
  2463. # test case):
  2464. let disp = getDispatcher(s)
  2465. # auto return type?
  2466. if disp != nil and disp.typ.returnType != nil and disp.typ.returnType.kind == tyUntyped:
  2467. let ret = s.typ.returnType
  2468. disp.typ.setReturnType ret
  2469. if disp.ast[resultPos].kind == nkSym:
  2470. if isEmptyType(ret): disp.ast[resultPos] = c.graph.emptyNode
  2471. else: disp.ast[resultPos].sym.typ = ret
  2472. proc semConverterDef(c: PContext, n: PNode): PNode =
  2473. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "converter")
  2474. result = semProcAux(c, n, skConverter, converterPragmas)
  2475. # macros can transform converters to nothing:
  2476. if namePos >= result.safeLen: return result
  2477. # bug #7093: if after a macro transformation we don't have an
  2478. # nkIteratorDef aynmore, return. The iterator then might have been
  2479. # sem'checked already. (Or not, if the macro skips it.)
  2480. if result.kind != nkConverterDef: return
  2481. var s = result[namePos].sym
  2482. var t = s.typ
  2483. if t.returnType == nil: localError(c.config, n.info, errXNeedsReturnType % "converter")
  2484. if t.len != 2: localError(c.config, n.info, "a converter takes exactly one argument")
  2485. addConverterDef(c, LazySym(sym: s))
  2486. proc semMacroDef(c: PContext, n: PNode): PNode =
  2487. result = semProcAux(c, n, skMacro, macroPragmas)
  2488. # macros can transform macros to nothing:
  2489. if namePos >= result.safeLen: return result
  2490. # bug #7093: if after a macro transformation we don't have an
  2491. # nkIteratorDef aynmore, return. The iterator then might have been
  2492. # sem'checked already. (Or not, if the macro skips it.)
  2493. if result.kind != nkMacroDef: return
  2494. var s = result[namePos].sym
  2495. var t = s.typ
  2496. var allUntyped = true
  2497. var nullary = true
  2498. for i in 1..<t.n.len:
  2499. let param = t.n[i].sym
  2500. if param.typ.kind != tyUntyped: allUntyped = false
  2501. # no default value, parameters required in call
  2502. if param.ast == nil: nullary = false
  2503. if allUntyped: incl(s.flags, sfAllUntyped)
  2504. if nullary and n[genericParamsPos].kind == nkEmpty:
  2505. # macro can be called with alias syntax, remove pushed noalias flag
  2506. excl(s.flags, sfNoalias)
  2507. if n[bodyPos].kind == nkEmpty:
  2508. localError(c.config, n.info, errImplOfXexpected % s.name.s)
  2509. proc incMod(c: PContext, n: PNode, it: PNode, includeStmtResult: PNode) =
  2510. var f = checkModuleName(c.config, it)
  2511. if f != InvalidFileIdx:
  2512. addIncludeFileDep(c, f)
  2513. onProcessing(c.graph, f, "include", c.module)
  2514. if containsOrIncl(c.includedFiles, f.int):
  2515. localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
  2516. else:
  2517. includeStmtResult.add semStmt(c, c.graph.includeFileCallback(c.graph, c.module, f), {})
  2518. excl(c.includedFiles, f.int)
  2519. proc evalInclude(c: PContext, n: PNode): PNode =
  2520. result = newNodeI(nkStmtList, n.info)
  2521. result.add n
  2522. for i in 0..<n.len:
  2523. var imp: PNode
  2524. let it = n[i]
  2525. if it.kind == nkInfix and it.len == 3 and it[0].ident.s != "/":
  2526. localError(c.config, it.info, "Cannot use '" & it[0].ident.s & "' in 'include'.")
  2527. if it.kind == nkInfix and it.len == 3 and it[2].kind == nkBracket:
  2528. let sep = it[0]
  2529. let dir = it[1]
  2530. imp = newNodeI(nkInfix, it.info)
  2531. imp.add sep
  2532. imp.add dir
  2533. imp.add sep # dummy entry, replaced in the loop
  2534. for x in it[2]:
  2535. imp[2] = x
  2536. incMod(c, n, imp, result)
  2537. else:
  2538. incMod(c, n, it, result)
  2539. proc recursiveSetFlag(n: PNode, flag: TNodeFlag) =
  2540. if n != nil:
  2541. for i in 0..<n.safeLen: recursiveSetFlag(n[i], flag)
  2542. incl(n.flags, flag)
  2543. proc semPragmaBlock(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  2544. checkSonsLen(n, 2, c.config)
  2545. let pragmaList = n[0]
  2546. pragma(c, nil, pragmaList, exprPragmas, isStatement = true)
  2547. var inUncheckedAssignSection = 0
  2548. for p in pragmaList:
  2549. if whichPragma(p) == wCast:
  2550. case whichPragma(p[1])
  2551. of wGcSafe, wNoSideEffect, wTags, wForbids, wRaises:
  2552. discard "handled in sempass2"
  2553. of wUncheckedAssign:
  2554. inUncheckedAssignSection = 1
  2555. else:
  2556. localError(c.config, p.info, "invalid pragma block: " & $p)
  2557. inc c.inUncheckedAssignSection, inUncheckedAssignSection
  2558. n[1] = semExpr(c, n[1], expectedType = expectedType)
  2559. dec c.inUncheckedAssignSection, inUncheckedAssignSection
  2560. result = n
  2561. result.typ = n[1].typ
  2562. for i in 0..<pragmaList.len:
  2563. case whichPragma(pragmaList[i])
  2564. of wLine: setInfoRecursive(result, pragmaList[i].info)
  2565. of wNoRewrite: recursiveSetFlag(result, nfNoRewrite)
  2566. else: discard
  2567. proc semStaticStmt(c: PContext, n: PNode): PNode =
  2568. #echo "semStaticStmt"
  2569. #writeStackTrace()
  2570. inc c.inStaticContext
  2571. openScope(c)
  2572. let a = semStmt(c, n[0], {})
  2573. closeScope(c)
  2574. dec c.inStaticContext
  2575. n[0] = a
  2576. evalStaticStmt(c.module, c.idgen, c.graph, a, c.p.owner)
  2577. when false:
  2578. # for incremental replays, keep the AST as required for replays:
  2579. result = n
  2580. else:
  2581. result = newNodeI(nkDiscardStmt, n.info, 1)
  2582. result[0] = c.graph.emptyNode
  2583. proc usesResult(n: PNode): bool =
  2584. # nkStmtList(expr) properly propagates the void context,
  2585. # so we don't need to process that all over again:
  2586. if n.kind notin {nkStmtList, nkStmtListExpr,
  2587. nkMacroDef, nkTemplateDef} + procDefs:
  2588. if isAtom(n):
  2589. result = n.kind == nkSym and n.sym.kind == skResult
  2590. elif n.kind == nkReturnStmt:
  2591. result = true
  2592. else:
  2593. result = false
  2594. for c in n:
  2595. if usesResult(c): return true
  2596. else:
  2597. result = false
  2598. proc inferConceptStaticParam(c: PContext, inferred, n: PNode) =
  2599. var typ = inferred.typ
  2600. let res = semConstExpr(c, n)
  2601. if not sameType(res.typ, typ.base):
  2602. localError(c.config, n.info,
  2603. "cannot infer the concept parameter '%s', due to a type mismatch. " &
  2604. "attempt to equate '%s' and '%s'." % [inferred.renderTree, $res.typ, $typ.base])
  2605. typ.n = res
  2606. proc semStmtList(c: PContext, n: PNode, flags: TExprFlags, expectedType: PType = nil): PNode =
  2607. result = n
  2608. result.transitionSonsKind(nkStmtList)
  2609. var voidContext = false
  2610. var last = n.len-1
  2611. # by not allowing for nkCommentStmt etc. we ensure nkStmtListExpr actually
  2612. # really *ends* in the expression that produces the type: The compiler now
  2613. # relies on this fact and it's too much effort to change that. And arguably
  2614. # 'R(); #comment' shouldn't produce R's type anyway.
  2615. #while last > 0 and n[last].kind in {nkPragma, nkCommentStmt,
  2616. # nkNilLit, nkEmpty}:
  2617. # dec last
  2618. for i in 0..<n.len:
  2619. var x = semExpr(c, n[i], flags, if i == n.len - 1: expectedType else: nil)
  2620. n[i] = x
  2621. if c.matchedConcept != nil and x.typ != nil and
  2622. (nfFromTemplate notin n.flags or i != last):
  2623. case x.typ.kind
  2624. of tyBool:
  2625. if x.kind == nkInfix and
  2626. x[0].kind == nkSym and
  2627. x[0].sym.name.s == "==":
  2628. if x[1].typ.isUnresolvedStatic:
  2629. inferConceptStaticParam(c, x[1], x[2])
  2630. continue
  2631. elif x[2].typ.isUnresolvedStatic:
  2632. inferConceptStaticParam(c, x[2], x[1])
  2633. continue
  2634. let verdict = semConstExpr(c, n[i])
  2635. if verdict == nil or verdict.kind != nkIntLit or verdict.intVal == 0:
  2636. localError(c.config, result.info, "concept predicate failed")
  2637. of tyUnknown: continue
  2638. else: discard
  2639. if n[i].typ == c.enforceVoidContext: #or usesResult(n[i]):
  2640. voidContext = true
  2641. n.typ = c.enforceVoidContext
  2642. if i == last and (n.len == 1 or ({efWantValue, efInTypeof} * flags != {})):
  2643. n.typ = n[i].typ
  2644. if not isEmptyType(n.typ): n.transitionSonsKind(nkStmtListExpr)
  2645. elif i != last or voidContext:
  2646. discardCheck(c, n[i], flags)
  2647. else:
  2648. n.typ = n[i].typ
  2649. if not isEmptyType(n.typ): n.transitionSonsKind(nkStmtListExpr)
  2650. var m = n[i]
  2651. while m.kind in {nkStmtListExpr, nkStmtList} and m.len > 0: # from templates
  2652. m = m.lastSon
  2653. if endsInNoReturn(m):
  2654. for j in i + 1..<n.len:
  2655. case n[j].kind
  2656. of nkPragma, nkCommentStmt, nkNilLit, nkEmpty, nkState: discard
  2657. else: message(c.config, n[j].info, warnUnreachableCode)
  2658. else: discard
  2659. if result.len == 1 and
  2660. # concept bodies should be preserved as a stmt list:
  2661. c.matchedConcept == nil and
  2662. # also, don't make life complicated for macros.
  2663. # they will always expect a proper stmtlist:
  2664. nfBlockArg notin n.flags and
  2665. result[0].kind != nkDefer:
  2666. result = result[0]
  2667. proc semStmt(c: PContext, n: PNode; flags: TExprFlags): PNode =
  2668. if efInTypeof notin flags:
  2669. result = semExprNoType(c, n)
  2670. else:
  2671. result = semExpr(c, n, flags)