sem.nim 24 KB

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