semstmts.nim 105 KB

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