sem.nim 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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 implements the semantic checking pass.
  10. import tables
  11. import
  12. ast, strutils, options, astalgo, trees,
  13. wordrecg, ropes, msgs, idents, renderer, types, platform, math,
  14. magicsys, nversion, nimsets, semfold, modulepaths, importer,
  15. procfind, lookups, pragmas, semdata, semtypinst, sigmatch,
  16. intsets, transf, vmdef, vm, aliases, cgmeth, lambdalifting,
  17. evaltempl, patterns, parampatterns, sempass2, linter, semmacrosanity,
  18. lowerings, plugins/active, lineinfos, strtabs, int128,
  19. isolation_check, typeallowed, modulegraphs, enumtostr, concepts, astmsgs
  20. when not defined(leanCompiler):
  21. import spawn
  22. when defined(nimPreviewSlimSystem):
  23. import std/formatfloat
  24. # implementation
  25. proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}, expectedType: PType = nil): PNode
  26. proc semExprWithType(c: PContext, n: PNode, flags: TExprFlags = {}, expectedType: PType = nil): PNode
  27. proc semExprNoType(c: PContext, n: PNode): PNode
  28. proc semExprNoDeref(c: PContext, n: PNode, flags: TExprFlags = {}): PNode
  29. proc semProcBody(c: PContext, n: PNode; expectedType: PType = nil): PNode
  30. proc fitNode(c: PContext, formal: PType, arg: PNode; info: TLineInfo): PNode
  31. proc changeType(c: PContext; n: PNode, newType: PType, check: bool)
  32. proc semTypeNode(c: PContext, n: PNode, prev: PType): PType
  33. proc semStmt(c: PContext, n: PNode; flags: TExprFlags): PNode
  34. proc semOpAux(c: PContext, n: PNode)
  35. proc semParamList(c: PContext, n, genericParams: PNode, s: PSym)
  36. proc addParams(c: PContext, n: PNode, kind: TSymKind)
  37. proc maybeAddResult(c: PContext, s: PSym, n: PNode)
  38. proc tryExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode
  39. proc activate(c: PContext, n: PNode)
  40. proc semQuoteAst(c: PContext, n: PNode): PNode
  41. proc finishMethod(c: PContext, s: PSym)
  42. proc evalAtCompileTime(c: PContext, n: PNode): PNode
  43. proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode
  44. proc semStaticExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode
  45. proc semStaticType(c: PContext, childNode: PNode, prev: PType): PType
  46. proc semTypeOf(c: PContext; n: PNode): PNode
  47. proc computeRequiresInit(c: PContext, t: PType): bool
  48. proc defaultConstructionError(c: PContext, t: PType, info: TLineInfo)
  49. proc hasUnresolvedArgs(c: PContext, n: PNode): bool
  50. proc isArrayConstr(n: PNode): bool {.inline.} =
  51. result = n.kind == nkBracket and
  52. n.typ.skipTypes(abstractInst).kind == tyArray
  53. template semIdeForTemplateOrGenericCheck(conf, n, requiresCheck) =
  54. # we check quickly if the node is where the cursor is
  55. when defined(nimsuggest):
  56. if n.info.fileIndex == conf.m.trackPos.fileIndex and n.info.line == conf.m.trackPos.line:
  57. requiresCheck = true
  58. template semIdeForTemplateOrGeneric(c: PContext; n: PNode;
  59. requiresCheck: bool) =
  60. # use only for idetools support; this is pretty slow so generics and
  61. # templates perform some quick check whether the cursor is actually in
  62. # the generic or template.
  63. when defined(nimsuggest):
  64. if c.config.cmd == cmdIdeTools and requiresCheck:
  65. #if optIdeDebug in gGlobalOptions:
  66. # echo "passing to safeSemExpr: ", renderTree(n)
  67. discard safeSemExpr(c, n)
  68. proc fitNodePostMatch(c: PContext, formal: PType, arg: PNode): PNode =
  69. let x = arg.skipConv
  70. if (x.kind == nkCurly and formal.kind == tySet and formal.base.kind != tyGenericParam) or
  71. (x.kind in {nkPar, nkTupleConstr}) and formal.kind notin {tyUntyped, tyBuiltInTypeClass, tyAnything}:
  72. changeType(c, x, formal, check=true)
  73. result = arg
  74. result = skipHiddenSubConv(result, c.graph, c.idgen)
  75. proc fitNode(c: PContext, formal: PType, arg: PNode; info: TLineInfo): PNode =
  76. if arg.typ.isNil:
  77. localError(c.config, arg.info, "expression has no type: " &
  78. renderTree(arg, {renderNoComments}))
  79. # error correction:
  80. result = copyTree(arg)
  81. result.typ = formal
  82. elif arg.kind in nkSymChoices and formal.skipTypes(abstractInst).kind == tyEnum:
  83. # Pick the right 'sym' from the sym choice by looking at 'formal' type:
  84. result = nil
  85. for ch in arg:
  86. if sameType(ch.typ, formal):
  87. return getConstExpr(c.module, ch, c.idgen, c.graph)
  88. typeMismatch(c.config, info, formal, arg.typ, arg)
  89. else:
  90. result = indexTypesMatch(c, formal, arg.typ, arg)
  91. if result == nil:
  92. typeMismatch(c.config, info, formal, arg.typ, arg)
  93. # error correction:
  94. result = copyTree(arg)
  95. result.typ = formal
  96. else:
  97. result = fitNodePostMatch(c, formal, result)
  98. proc fitNodeConsiderViewType(c: PContext, formal: PType, arg: PNode; info: TLineInfo): PNode =
  99. let a = fitNode(c, formal, arg, info)
  100. if formal.kind in {tyVar, tyLent}:
  101. #classifyViewType(formal) != noView:
  102. result = newNodeIT(nkHiddenAddr, a.info, formal)
  103. result.add a
  104. formal.flags.incl tfVarIsPtr
  105. else:
  106. result = a
  107. proc inferWithMetatype(c: PContext, formal: PType,
  108. arg: PNode, coerceDistincts = false): PNode
  109. template commonTypeBegin*(): PType = PType(kind: tyUntyped)
  110. proc commonType*(c: PContext; x, y: PType): PType =
  111. # new type relation that is used for array constructors,
  112. # if expressions, etc.:
  113. if x == nil: return x
  114. if y == nil: return y
  115. var a = skipTypes(x, {tyGenericInst, tyAlias, tySink})
  116. var b = skipTypes(y, {tyGenericInst, tyAlias, tySink})
  117. result = x
  118. if a.kind in {tyUntyped, tyNil}: result = y
  119. elif b.kind in {tyUntyped, tyNil}: result = x
  120. elif a.kind == tyTyped: result = a
  121. elif b.kind == tyTyped: result = b
  122. elif a.kind == tyTypeDesc:
  123. # turn any concrete typedesc into the abstract typedesc type
  124. if a.len == 0: result = a
  125. else:
  126. result = newType(tyTypeDesc, nextTypeId(c.idgen), a.owner)
  127. rawAddSon(result, newType(tyNone, nextTypeId(c.idgen), a.owner))
  128. elif b.kind in {tyArray, tySet, tySequence} and
  129. a.kind == b.kind:
  130. # check for seq[empty] vs. seq[int]
  131. let idx = ord(b.kind == tyArray)
  132. if a[idx].kind == tyEmpty: return y
  133. elif a.kind == tyTuple and b.kind == tyTuple and a.len == b.len:
  134. var nt: PType = nil
  135. for i in 0..<a.len:
  136. let aEmpty = isEmptyContainer(a[i])
  137. let bEmpty = isEmptyContainer(b[i])
  138. if aEmpty != bEmpty:
  139. if nt.isNil:
  140. nt = copyType(a, nextTypeId(c.idgen), a.owner)
  141. copyTypeProps(c.graph, c.idgen.module, nt, a)
  142. nt[i] = if aEmpty: b[i] else: a[i]
  143. if not nt.isNil: result = nt
  144. #elif b[idx].kind == tyEmpty: return x
  145. elif a.kind == tyRange and b.kind == tyRange:
  146. # consider: (range[0..3], range[0..4]) here. We should make that
  147. # range[0..4]. But then why is (range[0..4], 6) not range[0..6]?
  148. # But then why is (2,4) not range[2..4]? But I think this would break
  149. # too much code. So ... it's the same range or the base type. This means
  150. # typeof(if b: 0 else 1) == int and not range[0..1]. For now. In the long
  151. # run people expect ranges to work properly within a tuple.
  152. if not sameType(a, b):
  153. result = skipTypes(a, {tyRange}).skipIntLit(c.idgen)
  154. when false:
  155. if a.kind != tyRange and b.kind == tyRange:
  156. # XXX This really needs a better solution, but a proper fix now breaks
  157. # code.
  158. result = a #.skipIntLit
  159. elif a.kind == tyRange and b.kind != tyRange:
  160. result = b #.skipIntLit
  161. elif a.kind in IntegralTypes and a.n != nil:
  162. result = a #.skipIntLit
  163. elif a.kind == tyProc and b.kind == tyProc:
  164. if a.callConv == ccClosure and b.callConv != ccClosure:
  165. result = x
  166. elif compatibleEffects(a, b) != efCompat or
  167. (b.flags * {tfNoSideEffect, tfGcSafe}) < (a.flags * {tfNoSideEffect, tfGcSafe}):
  168. result = y
  169. else:
  170. var k = tyNone
  171. if a.kind in {tyRef, tyPtr}:
  172. k = a.kind
  173. if b.kind != a.kind: return x
  174. # bug #7601, array construction of ptr generic
  175. a = a.lastSon.skipTypes({tyGenericInst})
  176. b = b.lastSon.skipTypes({tyGenericInst})
  177. if a.kind == tyObject and b.kind == tyObject:
  178. result = commonSuperclass(a, b)
  179. # this will trigger an error later:
  180. if result.isNil or result == a: return x
  181. if result == b: return y
  182. # bug #7906, tyRef/tyPtr + tyGenericInst of ref/ptr object ->
  183. # ill-formed AST, no need for additional tyRef/tyPtr
  184. if k != tyNone and x.kind != tyGenericInst:
  185. let r = result
  186. result = newType(k, nextTypeId(c.idgen), r.owner)
  187. result.addSonSkipIntLit(r, c.idgen)
  188. proc endsInNoReturn(n: PNode): bool =
  189. # check if expr ends in raise exception or call of noreturn proc
  190. var it = n
  191. while it.kind in {nkStmtList, nkStmtListExpr} and it.len > 0:
  192. it = it.lastSon
  193. result = it.kind in nkLastBlockStmts or
  194. it.kind in nkCallKinds and it[0].kind == nkSym and sfNoReturn in it[0].sym.flags
  195. proc commonType*(c: PContext; x: PType, y: PNode): PType =
  196. # ignore exception raising branches in case/if expressions
  197. if endsInNoReturn(y): return x
  198. commonType(c, x, y.typ)
  199. proc newSymS(kind: TSymKind, n: PNode, c: PContext): PSym =
  200. result = newSym(kind, considerQuotedIdent(c, n), c.idgen, getCurrOwner(c), n.info)
  201. when defined(nimsuggest):
  202. suggestDecl(c, n, result)
  203. proc newSymG*(kind: TSymKind, n: PNode, c: PContext): PSym =
  204. # like newSymS, but considers gensym'ed symbols
  205. if n.kind == nkSym:
  206. # and sfGenSym in n.sym.flags:
  207. result = n.sym
  208. if result.kind notin {kind, skTemp}:
  209. localError(c.config, n.info, "cannot use symbol of kind '$1' as a '$2'" %
  210. [result.kind.toHumanStr, kind.toHumanStr])
  211. when false:
  212. if sfGenSym in result.flags and result.kind notin {skTemplate, skMacro, skParam}:
  213. # declarative context, so produce a fresh gensym:
  214. result = copySym(result)
  215. result.ast = n.sym.ast
  216. put(c.p, n.sym, result)
  217. # when there is a nested proc inside a template, semtmpl
  218. # will assign a wrong owner during the first pass over the
  219. # template; we must fix it here: see #909
  220. result.owner = getCurrOwner(c)
  221. else:
  222. result = newSym(kind, considerQuotedIdent(c, n), c.idgen, getCurrOwner(c), n.info)
  223. #if kind in {skForVar, skLet, skVar} and result.owner.kind == skModule:
  224. # incl(result.flags, sfGlobal)
  225. when defined(nimsuggest):
  226. suggestDecl(c, n, result)
  227. proc semIdentVis(c: PContext, kind: TSymKind, n: PNode,
  228. allowed: TSymFlags): PSym
  229. # identifier with visibility
  230. proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode,
  231. allowed: TSymFlags): PSym
  232. proc typeAllowedCheck(c: PContext; info: TLineInfo; typ: PType; kind: TSymKind;
  233. flags: TTypeAllowedFlags = {}) =
  234. let t = typeAllowed(typ, kind, c, flags)
  235. if t != nil:
  236. var err: string
  237. if t == typ:
  238. err = "invalid type: '$1' for $2" % [typeToString(typ), toHumanStr(kind)]
  239. if kind in {skVar, skLet, skConst} and taIsTemplateOrMacro in flags:
  240. err &= ". Did you mean to call the $1 with '()'?" % [toHumanStr(typ.owner.kind)]
  241. else:
  242. err = "invalid type: '$1' in this context: '$2' for $3" % [typeToString(t),
  243. typeToString(typ), toHumanStr(kind)]
  244. localError(c.config, info, err)
  245. proc paramsTypeCheck(c: PContext, typ: PType) {.inline.} =
  246. typeAllowedCheck(c, typ.n.info, typ, skProc)
  247. proc expectMacroOrTemplateCall(c: PContext, n: PNode): PSym
  248. proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode
  249. proc semWhen(c: PContext, n: PNode, semCheck: bool = true): PNode
  250. proc semTemplateExpr(c: PContext, n: PNode, s: PSym,
  251. flags: TExprFlags = {}; expectedType: PType = nil): PNode
  252. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  253. flags: TExprFlags = {}; expectedType: PType = nil): PNode
  254. proc symFromType(c: PContext; t: PType, info: TLineInfo): PSym =
  255. if t.sym != nil: return t.sym
  256. result = newSym(skType, getIdent(c.cache, "AnonType"), c.idgen, t.owner, info)
  257. result.flags.incl sfAnon
  258. result.typ = t
  259. proc symNodeFromType(c: PContext, t: PType, info: TLineInfo): PNode =
  260. result = newSymNode(symFromType(c, t, info), info)
  261. result.typ = makeTypeDesc(c, t)
  262. when false:
  263. proc createEvalContext(c: PContext, mode: TEvalMode): PEvalContext =
  264. result = newEvalContext(c.module, mode)
  265. result.getType = proc (n: PNode): PNode =
  266. result = tryExpr(c, n)
  267. if result == nil:
  268. result = newSymNode(errorSym(c, n))
  269. elif result.typ == nil:
  270. result = newSymNode(getSysSym"void")
  271. else:
  272. result.typ = makeTypeDesc(c, result.typ)
  273. result.handleIsOperator = proc (n: PNode): PNode =
  274. result = isOpImpl(c, n)
  275. proc hasCycle(n: PNode): bool =
  276. result = false
  277. incl n.flags, nfNone
  278. for i in 0..<n.safeLen:
  279. if nfNone in n[i].flags or hasCycle(n[i]):
  280. result = true
  281. break
  282. excl n.flags, nfNone
  283. proc fixupTypeAfterEval(c: PContext, evaluated, eOrig: PNode): PNode =
  284. # recompute the types as 'eval' isn't guaranteed to construct types nor
  285. # that the types are sound:
  286. when true:
  287. if eOrig.typ.kind in {tyUntyped, tyTyped, tyTypeDesc}:
  288. result = semExprWithType(c, evaluated)
  289. else:
  290. result = evaluated
  291. let expectedType = eOrig.typ.skipTypes({tyStatic})
  292. if hasCycle(result):
  293. result = localErrorNode(c, eOrig, "the resulting AST is cyclic and cannot be processed further")
  294. else:
  295. semmacrosanity.annotateType(result, expectedType, c.config)
  296. else:
  297. result = semExprWithType(c, evaluated)
  298. #result = fitNode(c, e.typ, result) inlined with special case:
  299. let arg = result
  300. result = indexTypesMatch(c, eOrig.typ, arg.typ, arg)
  301. if result == nil:
  302. result = arg
  303. # for 'tcnstseq' we support [] to become 'seq'
  304. if eOrig.typ.skipTypes(abstractInst).kind == tySequence and
  305. isArrayConstr(arg):
  306. arg.typ = eOrig.typ
  307. proc tryConstExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  308. var e = semExprWithType(c, n, expectedType = expectedType)
  309. if e == nil: return
  310. result = getConstExpr(c.module, e, c.idgen, c.graph)
  311. if result != nil: return
  312. let oldErrorCount = c.config.errorCounter
  313. let oldErrorMax = c.config.errorMax
  314. let oldErrorOutputs = c.config.m.errorOutputs
  315. c.config.m.errorOutputs = {}
  316. c.config.errorMax = high(int) # `setErrorMaxHighMaybe` not appropriate here
  317. when defined(nimsuggest):
  318. # Remove the error hook so nimsuggest doesn't report errors there
  319. let tempHook = c.graph.config.structuredErrorHook
  320. c.graph.config.structuredErrorHook = nil
  321. try:
  322. result = evalConstExpr(c.module, c.idgen, c.graph, e)
  323. if result == nil or result.kind == nkEmpty:
  324. result = nil
  325. else:
  326. result = fixupTypeAfterEval(c, result, e)
  327. except ERecoverableError:
  328. result = nil
  329. when defined(nimsuggest):
  330. # Restore the error hook
  331. c.graph.config.structuredErrorHook = tempHook
  332. c.config.errorCounter = oldErrorCount
  333. c.config.errorMax = oldErrorMax
  334. c.config.m.errorOutputs = oldErrorOutputs
  335. const
  336. errConstExprExpected = "constant expression expected"
  337. proc semConstExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  338. var e = semExprWithType(c, n, expectedType = expectedType)
  339. if e == nil:
  340. localError(c.config, n.info, errConstExprExpected)
  341. return n
  342. if e.kind in nkSymChoices and e[0].typ.skipTypes(abstractInst).kind == tyEnum:
  343. return e
  344. result = getConstExpr(c.module, e, c.idgen, c.graph)
  345. if result == nil:
  346. #if e.kind == nkEmpty: globalError(n.info, errConstExprExpected)
  347. result = evalConstExpr(c.module, c.idgen, c.graph, e)
  348. if result == nil or result.kind == nkEmpty:
  349. if e.info != n.info:
  350. pushInfoContext(c.config, n.info)
  351. localError(c.config, e.info, errConstExprExpected)
  352. popInfoContext(c.config)
  353. else:
  354. localError(c.config, e.info, errConstExprExpected)
  355. # error correction:
  356. result = e
  357. else:
  358. result = fixupTypeAfterEval(c, result, e)
  359. proc semExprFlagDispatched(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  360. if efNeedStatic in flags:
  361. if efPreferNilResult in flags:
  362. return tryConstExpr(c, n, expectedType)
  363. else:
  364. return semConstExpr(c, n, expectedType)
  365. else:
  366. result = semExprWithType(c, n, flags, expectedType)
  367. if efPreferStatic in flags:
  368. var evaluated = getConstExpr(c.module, result, c.idgen, c.graph)
  369. if evaluated != nil: return evaluated
  370. evaluated = evalAtCompileTime(c, result)
  371. if evaluated != nil: return evaluated
  372. proc semGenericStmt(c: PContext, n: PNode): PNode
  373. include hlo, seminst, semcall
  374. proc resetSemFlag(n: PNode) =
  375. if n != nil:
  376. excl n.flags, nfSem
  377. for i in 0..<n.safeLen:
  378. resetSemFlag(n[i])
  379. proc semAfterMacroCall(c: PContext, call, macroResult: PNode,
  380. s: PSym, flags: TExprFlags; expectedType: PType = nil): PNode =
  381. ## Semantically check the output of a macro.
  382. ## This involves processes such as re-checking the macro output for type
  383. ## coherence, making sure that variables declared with 'let' aren't
  384. ## reassigned, and binding the unbound identifiers that the macro output
  385. ## contains.
  386. inc(c.config.evalTemplateCounter)
  387. if c.config.evalTemplateCounter > evalTemplateLimit:
  388. globalError(c.config, s.info, "template instantiation too nested")
  389. c.friendModules.add(s.owner.getModule)
  390. result = macroResult
  391. resetSemFlag result
  392. if s.typ[0] == nil:
  393. result = semStmt(c, result, flags)
  394. else:
  395. var retType = s.typ[0]
  396. if retType.kind == tyTypeDesc and tfUnresolved in retType.flags and
  397. retType.len == 1:
  398. # bug #11941: template fails(T: type X, v: auto): T
  399. # does not mean we expect a tyTypeDesc.
  400. retType = retType[0]
  401. case retType.kind
  402. of tyUntyped, tyAnything:
  403. # Not expecting a type here allows templates like in ``tmodulealias.in``.
  404. result = semExpr(c, result, flags, expectedType)
  405. of tyTyped:
  406. # More restrictive version.
  407. result = semExprWithType(c, result, flags, expectedType)
  408. of tyTypeDesc:
  409. if result.kind == nkStmtList: result.transitionSonsKind(nkStmtListType)
  410. var typ = semTypeNode(c, result, nil)
  411. if typ == nil:
  412. localError(c.config, result.info, "expression has no type: " &
  413. renderTree(result, {renderNoComments}))
  414. result = newSymNode(errorSym(c, result))
  415. else:
  416. result.typ = makeTypeDesc(c, typ)
  417. #result = symNodeFromType(c, typ, n.info)
  418. else:
  419. if s.ast[genericParamsPos] != nil and retType.isMetaType:
  420. # The return type may depend on the Macro arguments
  421. # e.g. template foo(T: typedesc): seq[T]
  422. # We will instantiate the return type here, because
  423. # we now know the supplied arguments
  424. var paramTypes = initIdTable()
  425. for param, value in genericParamsInMacroCall(s, call):
  426. idTablePut(paramTypes, param.typ, value.typ)
  427. retType = generateTypeInstance(c, paramTypes,
  428. macroResult.info, retType)
  429. if retType.kind == tyVoid:
  430. result = semStmt(c, result, flags)
  431. else:
  432. result = semExpr(c, result, flags, expectedType)
  433. result = fitNode(c, retType, result, result.info)
  434. #globalError(s.info, errInvalidParamKindX, typeToString(s.typ[0]))
  435. dec(c.config.evalTemplateCounter)
  436. discard c.friendModules.pop()
  437. const
  438. errMissingGenericParamsForTemplate = "'$1' has unspecified generic parameters"
  439. errFloatToString = "cannot convert '$1' to '$2'"
  440. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  441. flags: TExprFlags = {}; expectedType: PType = nil): PNode =
  442. rememberExpansion(c, nOrig.info, sym)
  443. pushInfoContext(c.config, nOrig.info, sym.detailedInfo)
  444. let info = getCallLineInfo(n)
  445. markUsed(c, info, sym)
  446. onUse(info, sym)
  447. if sym == c.p.owner:
  448. globalError(c.config, info, "recursive dependency: '$1'" % sym.name.s)
  449. let genericParams = sym.ast[genericParamsPos].len
  450. let suppliedParams = max(n.safeLen - 1, 0)
  451. if suppliedParams < genericParams:
  452. globalError(c.config, info, errMissingGenericParamsForTemplate % n.renderTree)
  453. #if c.evalContext == nil:
  454. # c.evalContext = c.createEvalContext(emStatic)
  455. result = evalMacroCall(c.module, c.idgen, c.graph, c.templInstCounter, n, nOrig, sym)
  456. if efNoSemCheck notin flags:
  457. result = semAfterMacroCall(c, n, result, sym, flags, expectedType)
  458. if c.config.macrosToExpand.hasKey(sym.name.s):
  459. message(c.config, nOrig.info, hintExpandMacro, renderTree(result))
  460. result = wrapInComesFrom(nOrig.info, sym, result)
  461. popInfoContext(c.config)
  462. proc forceBool(c: PContext, n: PNode): PNode =
  463. result = fitNode(c, getSysType(c.graph, n.info, tyBool), n, n.info)
  464. if result == nil: result = n
  465. proc semConstBoolExpr(c: PContext, n: PNode): PNode =
  466. result = forceBool(c, semConstExpr(c, n, getSysType(c.graph, n.info, tyBool)))
  467. if result.kind != nkIntLit:
  468. localError(c.config, n.info, errConstExprExpected)
  469. proc semConceptBody(c: PContext, n: PNode): PNode
  470. include semtypes
  471. proc setGenericParamsMisc(c: PContext; n: PNode) =
  472. ## used by call defs (procs, templates, macros, ...) to analyse their generic
  473. ## params, and store the originals in miscPos for better error reporting.
  474. let orig = n[genericParamsPos]
  475. doAssert orig.kind in {nkEmpty, nkGenericParams}
  476. if n[genericParamsPos].kind == nkEmpty:
  477. n[genericParamsPos] = newNodeI(nkGenericParams, n.info)
  478. else:
  479. # we keep the original params around for better error messages, see
  480. # issue https://github.com/nim-lang/Nim/issues/1713
  481. n[genericParamsPos] = semGenericParamList(c, orig)
  482. if n[miscPos].kind == nkEmpty:
  483. n[miscPos] = newTree(nkBracket, c.graph.emptyNode, orig)
  484. else:
  485. n[miscPos][1] = orig
  486. proc caseBranchMatchesExpr(branch, matched: PNode): bool =
  487. result = false
  488. for i in 0 ..< branch.len-1:
  489. if branch[i].kind == nkRange:
  490. if overlap(branch[i], matched): return true
  491. elif exprStructuralEquivalent(branch[i], matched):
  492. return true
  493. proc pickCaseBranchIndex(caseExpr, matched: PNode): int =
  494. result = 0
  495. let endsWithElse = caseExpr[^1].kind == nkElse
  496. for i in 1..<caseExpr.len - endsWithElse.int:
  497. if caseExpr[i].caseBranchMatchesExpr(matched):
  498. return i
  499. if endsWithElse:
  500. return caseExpr.len - 1
  501. proc defaultFieldsForTheUninitialized(c: PContext, recNode: PNode, checkDefault: bool): seq[PNode]
  502. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType, checkDefault: bool): PNode
  503. proc defaultNodeField(c: PContext, a: PNode, checkDefault: bool): PNode
  504. const defaultFieldsSkipTypes = {tyGenericInst, tyAlias, tySink}
  505. proc defaultFieldsForTuple(c: PContext, recNode: PNode, hasDefault: var bool, checkDefault: bool): seq[PNode] =
  506. result = @[]
  507. case recNode.kind
  508. of nkRecList:
  509. for field in recNode:
  510. result.add defaultFieldsForTuple(c, field, hasDefault, checkDefault)
  511. of nkSym:
  512. let field = recNode.sym
  513. let recType = recNode.typ.skipTypes(defaultFieldsSkipTypes)
  514. if field.ast != nil: #Try to use default value
  515. hasDefault = true
  516. result.add newTree(nkExprColonExpr, recNode, field.ast)
  517. else:
  518. if recType.kind in {tyObject, tyArray, tyTuple}:
  519. let asgnExpr = defaultNodeField(c, recNode, recNode.typ, checkDefault)
  520. if asgnExpr != nil:
  521. hasDefault = true
  522. asgnExpr.flags.incl nfSkipFieldChecking
  523. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  524. return
  525. let asgnType = newType(tyTypeDesc, nextTypeId(c.idgen), recNode.typ.owner)
  526. rawAddSon(asgnType, recNode.typ)
  527. let asgnExpr = newTree(nkCall,
  528. newSymNode(getSysMagic(c.graph, recNode.info, "zeroDefault", mZeroDefault)),
  529. newNodeIT(nkType, recNode.info, asgnType)
  530. )
  531. asgnExpr.flags.incl nfSkipFieldChecking
  532. asgnExpr.typ = recNode.typ
  533. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  534. else:
  535. raiseAssert "unreachable"
  536. proc defaultFieldsForTheUninitialized(c: PContext, recNode: PNode, checkDefault: bool): seq[PNode] =
  537. result = @[]
  538. case recNode.kind
  539. of nkRecList:
  540. for field in recNode:
  541. result.add defaultFieldsForTheUninitialized(c, field, checkDefault)
  542. of nkRecCase:
  543. let discriminator = recNode[0]
  544. var selectedBranch: int
  545. var defaultValue = discriminator.sym.ast
  546. if defaultValue == nil:
  547. # None of the branches were explicitly selected by the user and no value
  548. # was given to the discrimator. We can assume that it will be initialized
  549. # to zero and this will select a particular branch as a result:
  550. if checkDefault: # don't add defaults when checking whether a case branch has default fields
  551. return
  552. defaultValue = newIntNode(nkIntLit#[c.graph]#, 0)
  553. defaultValue.typ = discriminator.typ
  554. selectedBranch = recNode.pickCaseBranchIndex defaultValue
  555. defaultValue.flags.incl nfSkipFieldChecking
  556. result.add newTree(nkExprColonExpr, discriminator, defaultValue)
  557. result.add defaultFieldsForTheUninitialized(c, recNode[selectedBranch][^1], checkDefault)
  558. of nkSym:
  559. let field = recNode.sym
  560. let recType = recNode.typ.skipTypes(defaultFieldsSkipTypes)
  561. if field.ast != nil: #Try to use default value
  562. result.add newTree(nkExprColonExpr, recNode, field.ast)
  563. elif recType.kind in {tyObject, tyArray, tyTuple}:
  564. let asgnExpr = defaultNodeField(c, recNode, recNode.typ, checkDefault)
  565. if asgnExpr != nil:
  566. asgnExpr.typ = recNode.typ
  567. asgnExpr.flags.incl nfSkipFieldChecking
  568. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  569. else:
  570. raiseAssert "unreachable"
  571. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType, checkDefault: bool): PNode =
  572. let aTypSkip = aTyp.skipTypes(defaultFieldsSkipTypes)
  573. if aTypSkip.kind == tyObject:
  574. let child = defaultFieldsForTheUninitialized(c, aTypSkip.n, checkDefault)
  575. if child.len > 0:
  576. var asgnExpr = newTree(nkObjConstr, newNodeIT(nkType, a.info, aTyp))
  577. asgnExpr.typ = aTyp
  578. asgnExpr.sons.add child
  579. result = semExpr(c, asgnExpr)
  580. else:
  581. result = nil
  582. elif aTypSkip.kind == tyArray:
  583. let child = defaultNodeField(c, a, aTypSkip[1], checkDefault)
  584. if child != nil:
  585. let node = newNode(nkIntLit)
  586. node.intVal = toInt64(lengthOrd(c.graph.config, aTypSkip))
  587. result = semExpr(c, newTree(nkCall, newSymNode(getSysSym(c.graph, a.info, "arrayWith"), a.info),
  588. semExprWithType(c, child),
  589. node
  590. ))
  591. result.typ = aTyp
  592. else:
  593. result = nil
  594. elif aTypSkip.kind == tyTuple:
  595. var hasDefault = false
  596. if aTypSkip.n != nil:
  597. let children = defaultFieldsForTuple(c, aTypSkip.n, hasDefault, checkDefault)
  598. if hasDefault and children.len > 0:
  599. result = newNodeI(nkTupleConstr, a.info)
  600. result.typ = aTyp
  601. result.sons.add children
  602. result = semExpr(c, result)
  603. else:
  604. result = nil
  605. else:
  606. result = nil
  607. else:
  608. result = nil
  609. proc defaultNodeField(c: PContext, a: PNode, checkDefault: bool): PNode =
  610. result = defaultNodeField(c, a, a.typ, checkDefault)
  611. include semtempl, semgnrc, semstmts, semexprs
  612. proc addCodeForGenerics(c: PContext, n: PNode) =
  613. for i in c.lastGenericIdx..<c.generics.len:
  614. var prc = c.generics[i].inst.sym
  615. if prc.kind in {skProc, skFunc, skMethod, skConverter} and prc.magic == mNone:
  616. if prc.ast == nil or prc.ast[bodyPos] == nil:
  617. internalError(c.config, prc.info, "no code for " & prc.name.s)
  618. else:
  619. n.add prc.ast
  620. c.lastGenericIdx = c.generics.len
  621. proc preparePContext*(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PContext =
  622. result = newContext(graph, module)
  623. result.idgen = idgen
  624. result.enforceVoidContext = newType(tyTyped, nextTypeId(idgen), nil)
  625. result.voidType = newType(tyVoid, nextTypeId(idgen), nil)
  626. if result.p != nil: internalError(graph.config, module.info, "sem.preparePContext")
  627. result.semConstExpr = semConstExpr
  628. result.semExpr = semExpr
  629. result.semExprWithType = semExprWithType
  630. result.semTryExpr = tryExpr
  631. result.semTryConstExpr = tryConstExpr
  632. result.computeRequiresInit = computeRequiresInit
  633. result.semOperand = semOperand
  634. result.semConstBoolExpr = semConstBoolExpr
  635. result.semOverloadedCall = semOverloadedCall
  636. result.semInferredLambda = semInferredLambda
  637. result.semGenerateInstance = generateInstance
  638. result.semTypeNode = semTypeNode
  639. result.instTypeBoundOp = sigmatch.instTypeBoundOp
  640. result.hasUnresolvedArgs = hasUnresolvedArgs
  641. result.templInstCounter = new int
  642. pushProcCon(result, module)
  643. pushOwner(result, result.module)
  644. result.moduleScope = openScope(result)
  645. result.moduleScope.addSym(module) # a module knows itself
  646. if sfSystemModule in module.flags:
  647. graph.systemModule = module
  648. result.topLevelScope = openScope(result)
  649. proc isImportSystemStmt(g: ModuleGraph; n: PNode): bool =
  650. if g.systemModule == nil: return false
  651. var n = n
  652. if n.kind == nkStmtList:
  653. for i in 0..<n.len-1:
  654. if n[i].kind notin {nkCommentStmt, nkEmpty}:
  655. n = n[i]
  656. break
  657. case n.kind
  658. of nkImportStmt:
  659. result = false
  660. for x in n:
  661. if x.kind == nkIdent:
  662. let f = checkModuleName(g.config, x, false)
  663. if f == g.systemModule.info.fileIndex:
  664. return true
  665. of nkImportExceptStmt, nkFromStmt:
  666. result = false
  667. if n[0].kind == nkIdent:
  668. let f = checkModuleName(g.config, n[0], false)
  669. if f == g.systemModule.info.fileIndex:
  670. return true
  671. else: result = false
  672. proc isEmptyTree(n: PNode): bool =
  673. case n.kind
  674. of nkStmtList:
  675. for it in n:
  676. if not isEmptyTree(it): return false
  677. result = true
  678. of nkEmpty, nkCommentStmt: result = true
  679. else: result = false
  680. proc decl(c: PContext, n: PNode, kind: TSymKind): PNode =
  681. if n[0].kind == nkIdent:
  682. var s = newSym(kind, n[0].ident, c.idgen, getCurrOwner(c), n.info)
  683. s.flags.incl sfToplevelDecl
  684. # pragmaCallable(c, s, n, allRoutinePragmas)
  685. result = n
  686. if n[^1].kind != nkEmpty:
  687. if s.kind in OverloadableSyms:
  688. addInterfaceOverloadableSymAt(c, c.currentScope, s)
  689. else:
  690. addInterfaceDeclAt(c, c.currentScope, s)
  691. result[0] = newSymNode(s)
  692. else:
  693. result = n
  694. import reorder
  695. proc semSignature(c: PContext, n: PNode): PNode =
  696. case n.kind
  697. of nkProcDef:
  698. result = decl(c, n, skProc)
  699. of nkMethodDef:
  700. result = decl(c, n, skMethod)
  701. of nkConverterDef:
  702. result = decl(c, n, skConverter)
  703. of nkMacroDef:
  704. result = decl(c, n, skMacro)
  705. of nkTemplateDef:
  706. result = decl(c, n, skTemplate)
  707. of nkIteratorDef:
  708. result = decl(c, n, skIterator)
  709. of nkIncludeStmt:
  710. result = n
  711. for i in 0..<n.len:
  712. var f = checkModuleName(c.config, n[i])
  713. if f != InvalidFileIdx:
  714. if containsOrIncl(c.includedFiles, f.int):
  715. localError(c.config, n[i].info, "recursive dependency: '$1'" %
  716. toMsgFilename(c.config, f))
  717. else:
  718. let nn = includeModule(c.graph, c.module, f)
  719. result = semSignature(c, nn)
  720. excl(c.includedFiles, f.int)
  721. of nkStmtList:
  722. result = copyNode(n)
  723. for i in 0..<n.len:
  724. result.add semSignature(c, n[i])
  725. else:
  726. result = n
  727. proc semStmtAndGenerateGenerics(c: PContext, n: PNode): PNode =
  728. if c.topStmts == 0 and not isImportSystemStmt(c.graph, n):
  729. if sfSystemModule notin c.module.flags and not isEmptyTree(n):
  730. assert c.graph.systemModule != nil
  731. c.moduleScope.addSym c.graph.systemModule # import the "System" identifier
  732. importAllSymbols(c, c.graph.systemModule)
  733. inc c.topStmts
  734. else:
  735. inc c.topStmts
  736. if sfNoForward in c.module.flags:
  737. result = semAllTypeSections(c, n)
  738. else:
  739. result = n
  740. # if noforwardDecl in c.features:
  741. # debug result
  742. result = semSignature(c, result)
  743. result = semStmt(c, result, {})
  744. when false:
  745. # Code generators are lazy now and can deal with undeclared procs, so these
  746. # steps are not required anymore and actually harmful for the upcoming
  747. # destructor support.
  748. # BUGFIX: process newly generated generics here, not at the end!
  749. if c.lastGenericIdx < c.generics.len:
  750. var a = newNodeI(nkStmtList, n.info)
  751. addCodeForGenerics(c, a)
  752. if a.len > 0:
  753. # a generic has been added to `a`:
  754. if result.kind != nkEmpty: a.add result
  755. result = a
  756. result = hloStmt(c, result)
  757. if c.config.cmd == cmdInteractive and not isEmptyType(result.typ):
  758. result = buildEchoStmt(c, result)
  759. if c.config.cmd == cmdIdeTools:
  760. appendToModule(c.module, result)
  761. trackStmt(c, c.module, result, isTopLevel = true)
  762. proc recoverContext(c: PContext) =
  763. # clean up in case of a semantic error: We clean up the stacks, etc. This is
  764. # faster than wrapping every stack operation in a 'try finally' block and
  765. # requires far less code.
  766. c.currentScope = c.topLevelScope
  767. while getCurrOwner(c).kind != skModule: popOwner(c)
  768. while c.p != nil and c.p.owner.kind != skModule: c.p = c.p.next
  769. proc semWithPContext*(c: PContext, n: PNode): PNode =
  770. # no need for an expensive 'try' if we stop after the first error anyway:
  771. if c.config.errorMax <= 1:
  772. result = semStmtAndGenerateGenerics(c, n)
  773. else:
  774. let oldContextLen = msgs.getInfoContextLen(c.config)
  775. let oldInGenericInst = c.inGenericInst
  776. try:
  777. result = semStmtAndGenerateGenerics(c, n)
  778. except ERecoverableError, ESuggestDone:
  779. recoverContext(c)
  780. c.inGenericInst = oldInGenericInst
  781. msgs.setInfoContextLen(c.config, oldContextLen)
  782. if getCurrentException() of ESuggestDone:
  783. c.suggestionsMade = true
  784. result = nil
  785. else:
  786. result = newNodeI(nkEmpty, n.info)
  787. #if c.config.cmd == cmdIdeTools: findSuggest(c, n)
  788. storeRodNode(c, result)
  789. proc reportUnusedModules(c: PContext) =
  790. for i in 0..high(c.unusedImports):
  791. if sfUsed notin c.unusedImports[i][0].flags:
  792. message(c.config, c.unusedImports[i][1], warnUnusedImportX, c.unusedImports[i][0].name.s)
  793. proc closePContext*(graph: ModuleGraph; c: PContext, n: PNode): PNode =
  794. if c.config.cmd == cmdIdeTools and not c.suggestionsMade:
  795. suggestSentinel(c)
  796. closeScope(c) # close module's scope
  797. rawCloseScope(c) # imported symbols; don't check for unused ones!
  798. reportUnusedModules(c)
  799. result = newNode(nkStmtList)
  800. if n != nil:
  801. internalError(c.config, n.info, "n is not nil") #result := n;
  802. addCodeForGenerics(c, result)
  803. if c.module.ast != nil:
  804. result.add(c.module.ast)
  805. popOwner(c)
  806. popProcCon(c)
  807. sealRodFile(c)