sem.nim 35 KB

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