semstmts.nim 101 KB

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