semstmts.nim 88 KB

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