semstmts.nim 101 KB

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