sem.nim 33 KB

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