sem.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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, strutils, options, astalgo, trees,
  12. wordrecg, ropes, msgs, idents, renderer, types, platform, math,
  13. magicsys, nversion, nimsets, semfold, modulepaths, importer,
  14. procfind, lookups, pragmas, passes, semdata, semtypinst, sigmatch,
  15. intsets, transf, vmdef, vm, idgen, aliases, cgmeth, lambdalifting,
  16. evaltempl, patterns, parampatterns, sempass2, linter, semmacrosanity,
  17. lowerings, plugins/active, rod, lineinfos, strtabs, int128
  18. from modulegraphs import ModuleGraph, PPassContext, onUse, onDef, onDefResolveForward
  19. when defined(nimfix):
  20. import nimfix/prettybase
  21. when not defined(leanCompiler):
  22. import spawn
  23. # implementation
  24. proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode
  25. proc semExprWithType(c: PContext, n: PNode, flags: TExprFlags = {}): PNode
  26. proc semExprNoType(c: PContext, n: PNode): PNode
  27. proc semExprNoDeref(c: PContext, n: PNode, flags: TExprFlags = {}): PNode
  28. proc semProcBody(c: PContext, n: PNode): PNode
  29. proc fitNode(c: PContext, formal: PType, arg: PNode; info: TLineInfo): PNode
  30. proc changeType(c: PContext; n: PNode, newType: PType, check: bool)
  31. proc semLambda(c: PContext, n: PNode, flags: TExprFlags): PNode
  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): 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 in {nkPar, nkTupleConstr, nkCurly} and formal.kind != tyUntyped:
  71. changeType(c, x, formal, check=true)
  72. result = arg
  73. result = skipHiddenSubConv(result)
  74. proc fitNode(c: PContext, formal: PType, arg: PNode; info: TLineInfo): PNode =
  75. if arg.typ.isNil:
  76. localError(c.config, arg.info, "expression has no type: " &
  77. renderTree(arg, {renderNoComments}))
  78. # error correction:
  79. result = copyTree(arg)
  80. result.typ = formal
  81. else:
  82. result = indexTypesMatch(c, formal, arg.typ, arg)
  83. if result == nil:
  84. typeMismatch(c.config, info, formal, arg.typ)
  85. # error correction:
  86. result = copyTree(arg)
  87. result.typ = formal
  88. else:
  89. result = fitNodePostMatch(c, formal, result)
  90. proc inferWithMetatype(c: PContext, formal: PType,
  91. arg: PNode, coerceDistincts = false): PNode
  92. template commonTypeBegin*(): PType = PType(kind: tyUntyped)
  93. proc commonType*(x, y: PType): PType =
  94. # new type relation that is used for array constructors,
  95. # if expressions, etc.:
  96. if x == nil: return x
  97. if y == nil: return y
  98. var a = skipTypes(x, {tyGenericInst, tyAlias, tySink})
  99. var b = skipTypes(y, {tyGenericInst, tyAlias, tySink})
  100. result = x
  101. if a.kind in {tyUntyped, tyNil}: result = y
  102. elif b.kind in {tyUntyped, tyNil}: result = x
  103. elif a.kind == tyTyped: result = a
  104. elif b.kind == tyTyped: result = b
  105. elif a.kind == tyTypeDesc:
  106. # turn any concrete typedesc into the abstract typedesc type
  107. if a.len == 0: result = a
  108. else:
  109. result = newType(tyTypeDesc, a.owner)
  110. rawAddSon(result, newType(tyNone, a.owner))
  111. elif b.kind in {tyArray, tySet, tySequence} and
  112. a.kind == b.kind:
  113. # check for seq[empty] vs. seq[int]
  114. let idx = ord(b.kind == tyArray)
  115. if a[idx].kind == tyEmpty: return y
  116. elif a.kind == tyTuple and b.kind == tyTuple and a.len == b.len:
  117. var nt: PType
  118. for i in 0..<a.len:
  119. let aEmpty = isEmptyContainer(a[i])
  120. let bEmpty = isEmptyContainer(b[i])
  121. if aEmpty != bEmpty:
  122. if nt.isNil: nt = copyType(a, a.owner, false)
  123. nt[i] = if aEmpty: b[i] else: a[i]
  124. if not nt.isNil: result = nt
  125. #elif b[idx].kind == tyEmpty: return x
  126. elif a.kind == tyRange and b.kind == tyRange:
  127. # consider: (range[0..3], range[0..4]) here. We should make that
  128. # range[0..4]. But then why is (range[0..4], 6) not range[0..6]?
  129. # But then why is (2,4) not range[2..4]? But I think this would break
  130. # too much code. So ... it's the same range or the base type. This means
  131. # type(if b: 0 else 1) == int and not range[0..1]. For now. In the long
  132. # run people expect ranges to work properly within a tuple.
  133. if not sameType(a, b):
  134. result = skipTypes(a, {tyRange}).skipIntLit
  135. when false:
  136. if a.kind != tyRange and b.kind == tyRange:
  137. # XXX This really needs a better solution, but a proper fix now breaks
  138. # code.
  139. result = a #.skipIntLit
  140. elif a.kind == tyRange and b.kind != tyRange:
  141. result = b #.skipIntLit
  142. elif a.kind in IntegralTypes and a.n != nil:
  143. result = a #.skipIntLit
  144. else:
  145. var k = tyNone
  146. if a.kind in {tyRef, tyPtr}:
  147. k = a.kind
  148. if b.kind != a.kind: return x
  149. # bug #7601, array construction of ptr generic
  150. a = a.lastSon.skipTypes({tyGenericInst})
  151. b = b.lastSon.skipTypes({tyGenericInst})
  152. if a.kind == tyObject and b.kind == tyObject:
  153. result = commonSuperclass(a, b)
  154. # this will trigger an error later:
  155. if result.isNil or result == a: return x
  156. if result == b: return y
  157. # bug #7906, tyRef/tyPtr + tyGenericInst of ref/ptr object ->
  158. # ill-formed AST, no need for additional tyRef/tyPtr
  159. if k != tyNone and x.kind != tyGenericInst:
  160. let r = result
  161. result = newType(k, r.owner)
  162. result.addSonSkipIntLit(r)
  163. proc endsInNoReturn(n: PNode): bool =
  164. # check if expr ends in raise exception or call of noreturn proc
  165. var it = n
  166. while it.kind in {nkStmtList, nkStmtListExpr} and it.len > 0:
  167. it = it.lastSon
  168. result = it.kind in nkLastBlockStmts or
  169. it.kind in nkCallKinds and it[0].kind == nkSym and sfNoReturn in it[0].sym.flags
  170. proc commonType*(x: PType, y: PNode): PType =
  171. # ignore exception raising branches in case/if expressions
  172. if endsInNoReturn(y): return x
  173. commonType(x, y.typ)
  174. proc newSymS(kind: TSymKind, n: PNode, c: PContext): PSym =
  175. result = newSym(kind, considerQuotedIdent(c, n), getCurrOwner(c), n.info)
  176. when defined(nimsuggest):
  177. suggestDecl(c, n, result)
  178. proc newSymG*(kind: TSymKind, n: PNode, c: PContext): PSym =
  179. # like newSymS, but considers gensym'ed symbols
  180. if n.kind == nkSym:
  181. # and sfGenSym in n.sym.flags:
  182. result = n.sym
  183. if result.kind notin {kind, skTemp}:
  184. localError(c.config, n.info, "cannot use symbol of kind '$1' as a '$2'" %
  185. [result.kind.toHumanStr, kind.toHumanStr])
  186. when false:
  187. if sfGenSym in result.flags and result.kind notin {skTemplate, skMacro, skParam}:
  188. # declarative context, so produce a fresh gensym:
  189. result = copySym(result)
  190. result.ast = n.sym.ast
  191. put(c.p, n.sym, result)
  192. # when there is a nested proc inside a template, semtmpl
  193. # will assign a wrong owner during the first pass over the
  194. # template; we must fix it here: see #909
  195. result.owner = getCurrOwner(c)
  196. else:
  197. result = newSym(kind, considerQuotedIdent(c, n), getCurrOwner(c), n.info)
  198. #if kind in {skForVar, skLet, skVar} and result.owner.kind == skModule:
  199. # incl(result.flags, sfGlobal)
  200. when defined(nimsuggest):
  201. suggestDecl(c, n, result)
  202. proc semIdentVis(c: PContext, kind: TSymKind, n: PNode,
  203. allowed: TSymFlags): PSym
  204. # identifier with visibility
  205. proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode,
  206. allowed: TSymFlags): PSym
  207. proc typeAllowedCheck(conf: ConfigRef; info: TLineInfo; typ: PType; kind: TSymKind;
  208. flags: TTypeAllowedFlags = {}) =
  209. let t = typeAllowed(typ, kind, flags)
  210. if t != nil:
  211. var err: string
  212. if t == typ:
  213. err = "invalid type: '$1' for $2" % [typeToString(typ), toHumanStr(kind)]
  214. if kind in {skVar, skLet, skConst} and taIsTemplateOrMacro in flags:
  215. err &= ". Did you mean to call the $1 with '()'?" % [toHumanStr(typ.owner.kind)]
  216. else:
  217. err = "invalid type: '$1' in this context: '$2' for $3" % [typeToString(t),
  218. typeToString(typ), toHumanStr(kind)]
  219. localError(conf, info, err)
  220. proc paramsTypeCheck(c: PContext, typ: PType) {.inline.} =
  221. typeAllowedCheck(c.config, typ.n.info, typ, skProc)
  222. proc expectMacroOrTemplateCall(c: PContext, n: PNode): PSym
  223. proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode
  224. proc semWhen(c: PContext, n: PNode, semCheck: bool = true): PNode
  225. proc semTemplateExpr(c: PContext, n: PNode, s: PSym,
  226. flags: TExprFlags = {}): PNode
  227. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  228. flags: TExprFlags = {}): PNode
  229. proc symFromType(c: PContext; t: PType, info: TLineInfo): PSym =
  230. if t.sym != nil: return t.sym
  231. result = newSym(skType, getIdent(c.cache, "AnonType"), t.owner, info)
  232. result.flags.incl sfAnon
  233. result.typ = t
  234. proc symNodeFromType(c: PContext, t: PType, info: TLineInfo): PNode =
  235. result = newSymNode(symFromType(c, t, info), info)
  236. result.typ = makeTypeDesc(c, t)
  237. when false:
  238. proc createEvalContext(c: PContext, mode: TEvalMode): PEvalContext =
  239. result = newEvalContext(c.module, mode)
  240. result.getType = proc (n: PNode): PNode =
  241. result = tryExpr(c, n)
  242. if result == nil:
  243. result = newSymNode(errorSym(c, n))
  244. elif result.typ == nil:
  245. result = newSymNode(getSysSym"void")
  246. else:
  247. result.typ = makeTypeDesc(c, result.typ)
  248. result.handleIsOperator = proc (n: PNode): PNode =
  249. result = isOpImpl(c, n)
  250. proc hasCycle(n: PNode): bool =
  251. incl n.flags, nfNone
  252. for i in 0..<n.safeLen:
  253. if nfNone in n[i].flags or hasCycle(n[i]):
  254. result = true
  255. break
  256. excl n.flags, nfNone
  257. proc fixupTypeAfterEval(c: PContext, evaluated, eOrig: PNode): PNode =
  258. # recompute the types as 'eval' isn't guaranteed to construct types nor
  259. # that the types are sound:
  260. when true:
  261. if eOrig.typ.kind in {tyUntyped, tyTyped, tyTypeDesc}:
  262. result = semExprWithType(c, evaluated)
  263. else:
  264. result = evaluated
  265. let expectedType = eOrig.typ.skipTypes({tyStatic})
  266. if hasCycle(result):
  267. globalError(c.config, eOrig.info, "the resulting AST is cyclic and cannot be processed further")
  268. result = errorNode(c, eOrig)
  269. else:
  270. semmacrosanity.annotateType(result, expectedType, c.config)
  271. else:
  272. result = semExprWithType(c, evaluated)
  273. #result = fitNode(c, e.typ, result) inlined with special case:
  274. let arg = result
  275. result = indexTypesMatch(c, eOrig.typ, arg.typ, arg)
  276. if result == nil:
  277. result = arg
  278. # for 'tcnstseq' we support [] to become 'seq'
  279. if eOrig.typ.skipTypes(abstractInst).kind == tySequence and
  280. isArrayConstr(arg):
  281. arg.typ = eOrig.typ
  282. proc tryConstExpr(c: PContext, n: PNode): PNode =
  283. var e = semExprWithType(c, n)
  284. if e == nil: return
  285. result = getConstExpr(c.module, e, c.graph)
  286. if result != nil: return
  287. let oldErrorCount = c.config.errorCounter
  288. let oldErrorMax = c.config.errorMax
  289. let oldErrorOutputs = c.config.m.errorOutputs
  290. c.config.m.errorOutputs = {}
  291. c.config.errorMax = high(int) # `setErrorMaxHighMaybe` not appropriate here
  292. try:
  293. result = evalConstExpr(c.module, c.graph, e)
  294. if result == nil or result.kind == nkEmpty:
  295. result = nil
  296. else:
  297. result = fixupTypeAfterEval(c, result, e)
  298. except ERecoverableError:
  299. result = nil
  300. c.config.errorCounter = oldErrorCount
  301. c.config.errorMax = oldErrorMax
  302. c.config.m.errorOutputs = oldErrorOutputs
  303. const
  304. errConstExprExpected = "constant expression expected"
  305. proc semConstExpr(c: PContext, n: PNode): PNode =
  306. var e = semExprWithType(c, n)
  307. if e == nil:
  308. localError(c.config, n.info, errConstExprExpected)
  309. return n
  310. result = getConstExpr(c.module, e, c.graph)
  311. if result == nil:
  312. #if e.kind == nkEmpty: globalError(n.info, errConstExprExpected)
  313. result = evalConstExpr(c.module, c.graph, e)
  314. if result == nil or result.kind == nkEmpty:
  315. if e.info != n.info:
  316. pushInfoContext(c.config, n.info)
  317. localError(c.config, e.info, errConstExprExpected)
  318. popInfoContext(c.config)
  319. else:
  320. localError(c.config, e.info, errConstExprExpected)
  321. # error correction:
  322. result = e
  323. else:
  324. result = fixupTypeAfterEval(c, result, e)
  325. proc semExprFlagDispatched(c: PContext, n: PNode, flags: TExprFlags): PNode =
  326. if efNeedStatic in flags:
  327. if efPreferNilResult in flags:
  328. return tryConstExpr(c, n)
  329. else:
  330. return semConstExpr(c, n)
  331. else:
  332. result = semExprWithType(c, n, flags)
  333. if efPreferStatic in flags:
  334. var evaluated = getConstExpr(c.module, result, c.graph)
  335. if evaluated != nil: return evaluated
  336. evaluated = evalAtCompileTime(c, result)
  337. if evaluated != nil: return evaluated
  338. when not defined(nimHasSinkInference):
  339. {.pragma: nosinks.}
  340. include hlo, seminst, semcall
  341. when false:
  342. # hopefully not required:
  343. proc resetSemFlag(n: PNode) =
  344. excl n.flags, nfSem
  345. for i in 0..<n.safeLen:
  346. resetSemFlag(n[i])
  347. proc semAfterMacroCall(c: PContext, call, macroResult: PNode,
  348. s: PSym, flags: TExprFlags): PNode =
  349. ## Semantically check the output of a macro.
  350. ## This involves processes such as re-checking the macro output for type
  351. ## coherence, making sure that variables declared with 'let' aren't
  352. ## reassigned, and binding the unbound identifiers that the macro output
  353. ## contains.
  354. inc(c.config.evalTemplateCounter)
  355. if c.config.evalTemplateCounter > evalTemplateLimit:
  356. globalError(c.config, s.info, "template instantiation too nested")
  357. c.friendModules.add(s.owner.getModule)
  358. idSynchronizationPoint(5000)
  359. result = macroResult
  360. excl(result.flags, nfSem)
  361. #resetSemFlag n
  362. if s.typ[0] == nil:
  363. result = semStmt(c, result, flags)
  364. else:
  365. var retType = s.typ[0]
  366. if retType.kind == tyTypeDesc and tfUnresolved in retType.flags and
  367. retType.len == 1:
  368. # bug #11941: template fails(T: type X, v: auto): T
  369. # does not mean we expect a tyTypeDesc.
  370. retType = retType[0]
  371. case retType.kind
  372. of tyUntyped:
  373. # Not expecting a type here allows templates like in ``tmodulealias.in``.
  374. result = semExpr(c, result, flags)
  375. of tyTyped:
  376. # More restrictive version.
  377. result = semExprWithType(c, result, flags)
  378. of tyTypeDesc:
  379. if result.kind == nkStmtList: result.transitionSonsKind(nkStmtListType)
  380. var typ = semTypeNode(c, result, nil)
  381. if typ == nil:
  382. localError(c.config, result.info, "expression has no type: " &
  383. renderTree(result, {renderNoComments}))
  384. result = newSymNode(errorSym(c, result))
  385. else:
  386. result.typ = makeTypeDesc(c, typ)
  387. #result = symNodeFromType(c, typ, n.info)
  388. else:
  389. if s.ast[genericParamsPos] != nil and retType.isMetaType:
  390. # The return type may depend on the Macro arguments
  391. # e.g. template foo(T: typedesc): seq[T]
  392. # We will instantiate the return type here, because
  393. # we now know the supplied arguments
  394. var paramTypes = newIdTable()
  395. for param, value in genericParamsInMacroCall(s, call):
  396. idTablePut(paramTypes, param.typ, value.typ)
  397. retType = generateTypeInstance(c, paramTypes,
  398. macroResult.info, retType)
  399. result = semExpr(c, result, flags)
  400. result = fitNode(c, retType, result, result.info)
  401. #globalError(s.info, errInvalidParamKindX, typeToString(s.typ[0]))
  402. dec(c.config.evalTemplateCounter)
  403. discard c.friendModules.pop()
  404. const
  405. errMissingGenericParamsForTemplate = "'$1' has unspecified generic parameters"
  406. errFloatToString = "cannot convert '$1' to '$2'"
  407. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  408. flags: TExprFlags = {}): PNode =
  409. pushInfoContext(c.config, nOrig.info, sym.detailedInfo)
  410. let info = getCallLineInfo(n)
  411. markUsed(c, info, sym)
  412. onUse(info, sym)
  413. if sym == c.p.owner:
  414. globalError(c.config, info, "recursive dependency: '$1'" % sym.name.s)
  415. let genericParams = sym.ast[genericParamsPos].len
  416. let suppliedParams = max(n.safeLen - 1, 0)
  417. if suppliedParams < genericParams:
  418. globalError(c.config, info, errMissingGenericParamsForTemplate % n.renderTree)
  419. #if c.evalContext == nil:
  420. # c.evalContext = c.createEvalContext(emStatic)
  421. result = evalMacroCall(c.module, c.graph, n, nOrig, sym)
  422. if efNoSemCheck notin flags:
  423. result = semAfterMacroCall(c, n, result, sym, flags)
  424. if c.config.macrosToExpand.hasKey(sym.name.s):
  425. message(c.config, nOrig.info, hintExpandMacro, renderTree(result))
  426. result = wrapInComesFrom(nOrig.info, sym, result)
  427. popInfoContext(c.config)
  428. proc forceBool(c: PContext, n: PNode): PNode =
  429. result = fitNode(c, getSysType(c.graph, n.info, tyBool), n, n.info)
  430. if result == nil: result = n
  431. proc semConstBoolExpr(c: PContext, n: PNode): PNode =
  432. result = forceBool(c, semConstExpr(c, n))
  433. if result.kind != nkIntLit:
  434. localError(c.config, n.info, errConstExprExpected)
  435. proc semGenericStmt(c: PContext, n: PNode): PNode
  436. proc semConceptBody(c: PContext, n: PNode): PNode
  437. include semtypes, semtempl, semgnrc, semstmts, semexprs
  438. proc addCodeForGenerics(c: PContext, n: PNode) =
  439. for i in c.lastGenericIdx..<c.generics.len:
  440. var prc = c.generics[i].inst.sym
  441. if prc.kind in {skProc, skFunc, skMethod, skConverter} and prc.magic == mNone:
  442. if prc.ast == nil or prc.ast[bodyPos] == nil:
  443. internalError(c.config, prc.info, "no code for " & prc.name.s)
  444. else:
  445. n.add prc.ast
  446. c.lastGenericIdx = c.generics.len
  447. proc myOpen(graph: ModuleGraph; module: PSym): PPassContext {.nosinks.} =
  448. var c = newContext(graph, module)
  449. if c.p != nil: internalError(graph.config, module.info, "sem.myOpen")
  450. c.semConstExpr = semConstExpr
  451. c.semExpr = semExpr
  452. c.semTryExpr = tryExpr
  453. c.semTryConstExpr = tryConstExpr
  454. c.computeRequiresInit = computeRequiresInit
  455. c.semOperand = semOperand
  456. c.semConstBoolExpr = semConstBoolExpr
  457. c.semOverloadedCall = semOverloadedCall
  458. c.semInferredLambda = semInferredLambda
  459. c.semGenerateInstance = generateInstance
  460. c.semTypeNode = semTypeNode
  461. c.instTypeBoundOp = sigmatch.instTypeBoundOp
  462. c.hasUnresolvedArgs = hasUnresolvedArgs
  463. pushProcCon(c, module)
  464. pushOwner(c, c.module)
  465. c.importTable = openScope(c)
  466. c.importTable.addSym(module) # a module knows itself
  467. if sfSystemModule in module.flags:
  468. graph.systemModule = module
  469. c.topLevelScope = openScope(c)
  470. result = c
  471. proc isImportSystemStmt(g: ModuleGraph; n: PNode): bool =
  472. if g.systemModule == nil: return false
  473. case n.kind
  474. of nkImportStmt:
  475. for x in n:
  476. if x.kind == nkIdent:
  477. let f = checkModuleName(g.config, x, false)
  478. if f == g.systemModule.info.fileIndex:
  479. return true
  480. of nkImportExceptStmt, nkFromStmt:
  481. if n[0].kind == nkIdent:
  482. let f = checkModuleName(g.config, n[0], false)
  483. if f == g.systemModule.info.fileIndex:
  484. return true
  485. else: discard
  486. proc isEmptyTree(n: PNode): bool =
  487. case n.kind
  488. of nkStmtList:
  489. for it in n:
  490. if not isEmptyTree(it): return false
  491. result = true
  492. of nkEmpty, nkCommentStmt: result = true
  493. else: result = false
  494. proc semStmtAndGenerateGenerics(c: PContext, n: PNode): PNode =
  495. if c.topStmts == 0 and not isImportSystemStmt(c.graph, n):
  496. if sfSystemModule notin c.module.flags and not isEmptyTree(n):
  497. c.importTable.addSym c.graph.systemModule # import the "System" identifier
  498. importAllSymbols(c, c.graph.systemModule)
  499. inc c.topStmts
  500. else:
  501. inc c.topStmts
  502. if sfNoForward in c.module.flags:
  503. result = semAllTypeSections(c, n)
  504. else:
  505. result = n
  506. result = semStmt(c, result, {})
  507. when false:
  508. # Code generators are lazy now and can deal with undeclared procs, so these
  509. # steps are not required anymore and actually harmful for the upcoming
  510. # destructor support.
  511. # BUGFIX: process newly generated generics here, not at the end!
  512. if c.lastGenericIdx < c.generics.len:
  513. var a = newNodeI(nkStmtList, n.info)
  514. addCodeForGenerics(c, a)
  515. if a.len > 0:
  516. # a generic has been added to `a`:
  517. if result.kind != nkEmpty: a.add result
  518. result = a
  519. result = hloStmt(c, result)
  520. if c.config.cmd == cmdInteractive and not isEmptyType(result.typ):
  521. result = buildEchoStmt(c, result)
  522. if c.config.cmd == cmdIdeTools:
  523. appendToModule(c.module, result)
  524. trackStmt(c, c.module, result, isTopLevel = true)
  525. proc recoverContext(c: PContext) =
  526. # clean up in case of a semantic error: We clean up the stacks, etc. This is
  527. # faster than wrapping every stack operation in a 'try finally' block and
  528. # requires far less code.
  529. c.currentScope = c.topLevelScope
  530. while getCurrOwner(c).kind != skModule: popOwner(c)
  531. while c.p != nil and c.p.owner.kind != skModule: c.p = c.p.next
  532. proc myProcess(context: PPassContext, n: PNode): PNode {.nosinks.} =
  533. var c = PContext(context)
  534. # no need for an expensive 'try' if we stop after the first error anyway:
  535. if c.config.errorMax <= 1:
  536. result = semStmtAndGenerateGenerics(c, n)
  537. else:
  538. let oldContextLen = msgs.getInfoContextLen(c.config)
  539. let oldInGenericInst = c.inGenericInst
  540. try:
  541. result = semStmtAndGenerateGenerics(c, n)
  542. except ERecoverableError, ESuggestDone:
  543. recoverContext(c)
  544. c.inGenericInst = oldInGenericInst
  545. msgs.setInfoContextLen(c.config, oldContextLen)
  546. if getCurrentException() of ESuggestDone:
  547. c.suggestionsMade = true
  548. result = nil
  549. else:
  550. result = newNodeI(nkEmpty, n.info)
  551. #if c.config.cmd == cmdIdeTools: findSuggest(c, n)
  552. rod.storeNode(c.graph, c.module, result)
  553. proc reportUnusedModules(c: PContext) =
  554. for i in 0..high(c.unusedImports):
  555. if sfUsed notin c.unusedImports[i][0].flags:
  556. message(c.config, c.unusedImports[i][1], warnUnusedImportX, c.unusedImports[i][0].name.s)
  557. proc myClose(graph: ModuleGraph; context: PPassContext, n: PNode): PNode =
  558. var c = PContext(context)
  559. if c.config.cmd == cmdIdeTools and not c.suggestionsMade:
  560. suggestSentinel(c)
  561. closeScope(c) # close module's scope
  562. rawCloseScope(c) # imported symbols; don't check for unused ones!
  563. reportUnusedModules(c)
  564. result = newNode(nkStmtList)
  565. if n != nil:
  566. internalError(c.config, n.info, "n is not nil") #result := n;
  567. addCodeForGenerics(c, result)
  568. if c.module.ast != nil:
  569. result.add(c.module.ast)
  570. popOwner(c)
  571. popProcCon(c)
  572. storeRemaining(c.graph, c.module)
  573. const semPass* = makePass(myOpen, myProcess, myClose,
  574. isFrontend = true)