sem.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. semparallel, lowerings, pluginsupport, plugins/active, rod, lineinfos
  18. from modulegraphs import ModuleGraph, PPassContext
  19. when defined(nimfix):
  20. import nimfix/prettybase
  21. # implementation
  22. proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode {.procvar.}
  23. proc semExprWithType(c: PContext, n: PNode, flags: TExprFlags = {}): PNode {.
  24. procvar.}
  25. proc semExprNoType(c: PContext, n: PNode): PNode
  26. proc semExprNoDeref(c: PContext, n: PNode, flags: TExprFlags = {}): PNode
  27. proc semProcBody(c: PContext, n: PNode): PNode
  28. proc fitNode(c: PContext, formal: PType, arg: PNode; info: TLineInfo): PNode
  29. proc changeType(c: PContext; n: PNode, newType: PType, check: bool)
  30. proc semLambda(c: PContext, n: PNode, flags: TExprFlags): PNode
  31. proc semTypeNode(c: PContext, n: PNode, prev: PType): PType
  32. proc semStmt(c: PContext, n: PNode; flags: TExprFlags): PNode
  33. proc semOpAux(c: PContext, n: PNode)
  34. proc semParamList(c: PContext, n, genericParams: PNode, s: PSym)
  35. proc addParams(c: PContext, n: PNode, kind: TSymKind)
  36. proc maybeAddResult(c: PContext, s: PSym, n: PNode)
  37. proc tryExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode
  38. proc activate(c: PContext, n: PNode)
  39. proc semQuoteAst(c: PContext, n: PNode): PNode
  40. proc finishMethod(c: PContext, s: PSym)
  41. proc evalAtCompileTime(c: PContext, n: PNode): PNode
  42. proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode
  43. proc semStaticExpr(c: PContext, n: PNode): PNode
  44. proc semStaticType(c: PContext, childNode: PNode, prev: PType): PType
  45. proc semTypeOf(c: PContext; n: PNode): PNode
  46. proc hasUnresolvedArgs(c: PContext, n: PNode): bool
  47. proc isArrayConstr(n: PNode): bool {.inline.} =
  48. result = n.kind == nkBracket and
  49. n.typ.skipTypes(abstractInst).kind == tyArray
  50. template semIdeForTemplateOrGenericCheck(conf, n, requiresCheck) =
  51. # we check quickly if the node is where the cursor is
  52. when defined(nimsuggest):
  53. if n.info.fileIndex == conf.m.trackPos.fileIndex and n.info.line == conf.m.trackPos.line:
  54. requiresCheck = true
  55. template semIdeForTemplateOrGeneric(c: PContext; n: PNode;
  56. requiresCheck: bool) =
  57. # use only for idetools support; this is pretty slow so generics and
  58. # templates perform some quick check whether the cursor is actually in
  59. # the generic or template.
  60. when defined(nimsuggest):
  61. if c.config.cmd == cmdIdeTools and requiresCheck:
  62. #if optIdeDebug in gGlobalOptions:
  63. # echo "passing to safeSemExpr: ", renderTree(n)
  64. discard safeSemExpr(c, n)
  65. proc fitNodePostMatch(c: PContext, formal: PType, arg: PNode): PNode =
  66. result = arg
  67. let x = result.skipConv
  68. if x.kind in {nkPar, nkTupleConstr, nkCurly} and formal.kind != tyExpr:
  69. changeType(c, x, formal, check=true)
  70. else:
  71. result = skipHiddenSubConv(result)
  72. #result.typ = takeType(formal, arg.typ)
  73. #echo arg.info, " picked ", result.typ.typeToString
  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: tyExpr)
  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 {tyExpr, tyNil}: result = y
  102. elif b.kind in {tyExpr, tyNil}: result = x
  103. elif a.kind == tyStmt: result = a
  104. elif b.kind == tyStmt: 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.sons[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.sons[i])
  120. let bEmpty = isEmptyContainer(b.sons[i])
  121. if aEmpty != bEmpty:
  122. if nt.isNil: nt = copyType(a, a.owner, false)
  123. nt.sons[i] = if aEmpty: b.sons[i] else: a.sons[i]
  124. if not nt.isNil: result = nt
  125. #elif b.sons[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 == nkRaiseStmt 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. proc `$`(kind: TSymKind): string = substr(system.`$`(kind), 2).toLowerAscii
  180. # like newSymS, but considers gensym'ed symbols
  181. if n.kind == nkSym:
  182. # and sfGenSym in n.sym.flags:
  183. result = n.sym
  184. if result.kind != kind:
  185. localError(c.config, n.info, "cannot use symbol of kind '" &
  186. $result.kind & "' as a '" & $kind & "'")
  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. if t == typ:
  212. localError(conf, info, "invalid type: '" & typeToString(typ) &
  213. "' for " & substr($kind, 2).toLowerAscii)
  214. else:
  215. localError(conf, info, "invalid type: '" & typeToString(t) &
  216. "' in this context: '" & typeToString(typ) &
  217. "' for " & substr($kind, 2).toLowerAscii)
  218. proc paramsTypeCheck(c: PContext, typ: PType) {.inline.} =
  219. typeAllowedCheck(c.config, typ.n.info, typ, skProc)
  220. proc expectMacroOrTemplateCall(c: PContext, n: PNode): PSym
  221. proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode
  222. proc semWhen(c: PContext, n: PNode, semCheck: bool = true): PNode
  223. proc semTemplateExpr(c: PContext, n: PNode, s: PSym,
  224. flags: TExprFlags = {}): PNode
  225. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  226. flags: TExprFlags = {}): PNode
  227. proc symFromType(c: PContext; t: PType, info: TLineInfo): PSym =
  228. if t.sym != nil: return t.sym
  229. result = newSym(skType, getIdent(c.cache, "AnonType"), t.owner, info)
  230. result.flags.incl sfAnon
  231. result.typ = t
  232. proc symNodeFromType(c: PContext, t: PType, info: TLineInfo): PNode =
  233. result = newSymNode(symFromType(c, t, info), info)
  234. result.typ = makeTypeDesc(c, t)
  235. when false:
  236. proc createEvalContext(c: PContext, mode: TEvalMode): PEvalContext =
  237. result = newEvalContext(c.module, mode)
  238. result.getType = proc (n: PNode): PNode =
  239. result = tryExpr(c, n)
  240. if result == nil:
  241. result = newSymNode(errorSym(c, n))
  242. elif result.typ == nil:
  243. result = newSymNode(getSysSym"void")
  244. else:
  245. result.typ = makeTypeDesc(c, result.typ)
  246. result.handleIsOperator = proc (n: PNode): PNode =
  247. result = isOpImpl(c, n)
  248. proc hasCycle(n: PNode): bool =
  249. incl n.flags, nfNone
  250. for i in 0..<safeLen(n):
  251. if nfNone in n[i].flags or hasCycle(n[i]):
  252. result = true
  253. break
  254. excl n.flags, nfNone
  255. proc fixupTypeAfterEval(c: PContext, evaluated, eOrig: PNode): PNode =
  256. # recompute the types as 'eval' isn't guaranteed to construct types nor
  257. # that the types are sound:
  258. when true:
  259. if eOrig.typ.kind in {tyExpr, tyStmt, tyTypeDesc}:
  260. result = semExprWithType(c, evaluated)
  261. else:
  262. result = evaluated
  263. let expectedType = eOrig.typ.skipTypes({tyStatic})
  264. if hasCycle(result):
  265. globalError(c.config, eOrig.info, "the resulting AST is cyclic and cannot be processed further")
  266. result = errorNode(c, eOrig)
  267. else:
  268. semmacrosanity.annotateType(result, expectedType, c.config)
  269. else:
  270. result = semExprWithType(c, evaluated)
  271. #result = fitNode(c, e.typ, result) inlined with special case:
  272. let arg = result
  273. result = indexTypesMatch(c, eOrig.typ, arg.typ, arg)
  274. if result == nil:
  275. result = arg
  276. # for 'tcnstseq' we support [] to become 'seq'
  277. if eOrig.typ.skipTypes(abstractInst).kind == tySequence and
  278. isArrayConstr(arg):
  279. arg.typ = eOrig.typ
  280. proc tryConstExpr(c: PContext, n: PNode): PNode =
  281. var e = semExprWithType(c, n)
  282. if e == nil: return
  283. result = getConstExpr(c.module, e, c.graph)
  284. if result != nil: return
  285. let oldErrorCount = c.config.errorCounter
  286. let oldErrorMax = c.config.errorMax
  287. let oldErrorOutputs = c.config.m.errorOutputs
  288. c.config.m.errorOutputs = {}
  289. c.config.errorMax = high(int)
  290. try:
  291. result = evalConstExpr(c.module, c.graph, e)
  292. if result == nil or result.kind == nkEmpty:
  293. result = nil
  294. else:
  295. result = fixupTypeAfterEval(c, result, e)
  296. except ERecoverableError:
  297. result = nil
  298. c.config.errorCounter = oldErrorCount
  299. c.config.errorMax = oldErrorMax
  300. c.config.m.errorOutputs = oldErrorOutputs
  301. const
  302. errConstExprExpected = "constant expression expected"
  303. proc semConstExpr(c: PContext, n: PNode): PNode =
  304. var e = semExprWithType(c, n)
  305. if e == nil:
  306. localError(c.config, n.info, errConstExprExpected)
  307. return n
  308. result = getConstExpr(c.module, e, c.graph)
  309. if result == nil:
  310. #if e.kind == nkEmpty: globalError(n.info, errConstExprExpected)
  311. result = evalConstExpr(c.module, c.graph, e)
  312. if result == nil or result.kind == nkEmpty:
  313. if e.info != n.info:
  314. pushInfoContext(c.config, n.info)
  315. localError(c.config, e.info, errConstExprExpected)
  316. popInfoContext(c.config)
  317. else:
  318. localError(c.config, e.info, errConstExprExpected)
  319. # error correction:
  320. result = e
  321. else:
  322. result = fixupTypeAfterEval(c, result, e)
  323. proc semExprFlagDispatched(c: PContext, n: PNode, flags: TExprFlags): PNode =
  324. if efNeedStatic in flags:
  325. if efPreferNilResult in flags:
  326. return tryConstExpr(c, n)
  327. else:
  328. return semConstExpr(c, n)
  329. else:
  330. result = semExprWithType(c, n, flags)
  331. if efPreferStatic in flags:
  332. var evaluated = getConstExpr(c.module, result, c.graph)
  333. if evaluated != nil: return evaluated
  334. evaluated = evalAtCompileTime(c, result)
  335. if evaluated != nil: return evaluated
  336. include hlo, seminst, semcall
  337. when false:
  338. # hopefully not required:
  339. proc resetSemFlag(n: PNode) =
  340. excl n.flags, nfSem
  341. for i in 0 ..< n.safeLen:
  342. resetSemFlag(n[i])
  343. proc semAfterMacroCall(c: PContext, call, macroResult: PNode,
  344. s: PSym, flags: TExprFlags): PNode =
  345. ## Semantically check the output of a macro.
  346. ## This involves processes such as re-checking the macro output for type
  347. ## coherence, making sure that variables declared with 'let' aren't
  348. ## reassigned, and binding the unbound identifiers that the macro output
  349. ## contains.
  350. inc(c.config.evalTemplateCounter)
  351. if c.config.evalTemplateCounter > evalTemplateLimit:
  352. globalError(c.config, s.info, "template instantiation too nested")
  353. c.friendModules.add(s.owner.getModule)
  354. result = macroResult
  355. excl(result.flags, nfSem)
  356. #resetSemFlag n
  357. if s.typ.sons[0] == nil:
  358. result = semStmt(c, result, flags)
  359. else:
  360. case s.typ.sons[0].kind
  361. of tyExpr:
  362. # BUGFIX: we cannot expect a type here, because module aliases would not
  363. # work then (see the ``tmodulealias`` test)
  364. # semExprWithType(c, result)
  365. result = semExpr(c, result, flags)
  366. of tyStmt:
  367. result = semStmt(c, result, flags)
  368. of tyTypeDesc:
  369. if result.kind == nkStmtList: result.kind = nkStmtListType
  370. var typ = semTypeNode(c, result, nil)
  371. if typ == nil:
  372. localError(c.config, result.info, "expression has no type: " &
  373. renderTree(result, {renderNoComments}))
  374. result = newSymNode(errorSym(c, result))
  375. else:
  376. result.typ = makeTypeDesc(c, typ)
  377. #result = symNodeFromType(c, typ, n.info)
  378. else:
  379. var retType = s.typ.sons[0]
  380. if s.ast[genericParamsPos] != nil and retType.isMetaType:
  381. # The return type may depend on the Macro arguments
  382. # e.g. template foo(T: typedesc): seq[T]
  383. # We will instantiate the return type here, because
  384. # we now know the supplied arguments
  385. var paramTypes = newIdTable()
  386. for param, value in genericParamsInMacroCall(s, call):
  387. idTablePut(paramTypes, param.typ, value.typ)
  388. retType = generateTypeInstance(c, paramTypes,
  389. macroResult.info, retType)
  390. result = semExpr(c, result, flags)
  391. result = fitNode(c, retType, result, result.info)
  392. #globalError(s.info, errInvalidParamKindX, typeToString(s.typ.sons[0]))
  393. dec(c.config.evalTemplateCounter)
  394. discard c.friendModules.pop()
  395. const
  396. errMissingGenericParamsForTemplate = "'$1' has unspecified generic parameters"
  397. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  398. flags: TExprFlags = {}): PNode =
  399. pushInfoContext(c.config, nOrig.info, sym.detailedInfo)
  400. markUsed(c.config, n.info, sym, c.graph.usageSym)
  401. styleCheckUse(n.info, sym)
  402. if sym == c.p.owner:
  403. globalError(c.config, n.info, "recursive dependency: '$1'" % sym.name.s)
  404. let genericParams = if sfImmediate in sym.flags: 0
  405. else: sym.ast[genericParamsPos].len
  406. let suppliedParams = max(n.safeLen - 1, 0)
  407. if suppliedParams < genericParams:
  408. globalError(c.config, n.info, errMissingGenericParamsForTemplate % n.renderTree)
  409. #if c.evalContext == nil:
  410. # c.evalContext = c.createEvalContext(emStatic)
  411. result = evalMacroCall(c.module, c.graph, n, nOrig, sym)
  412. if efNoSemCheck notin flags:
  413. result = semAfterMacroCall(c, n, result, sym, flags)
  414. result = wrapInComesFrom(nOrig.info, sym, result)
  415. popInfoContext(c.config)
  416. proc forceBool(c: PContext, n: PNode): PNode =
  417. result = fitNode(c, getSysType(c.graph, n.info, tyBool), n, n.info)
  418. if result == nil: result = n
  419. proc semConstBoolExpr(c: PContext, n: PNode): PNode =
  420. let nn = semExprWithType(c, n)
  421. result = fitNode(c, getSysType(c.graph, n.info, tyBool), nn, nn.info)
  422. if result == nil:
  423. localError(c.config, n.info, errConstExprExpected)
  424. return nn
  425. result = getConstExpr(c.module, result, c.graph)
  426. if result == nil:
  427. localError(c.config, n.info, errConstExprExpected)
  428. result = nn
  429. proc semGenericStmt(c: PContext, n: PNode): PNode
  430. proc semConceptBody(c: PContext, n: PNode): PNode
  431. include semtypes, semtempl, semgnrc, semstmts, semexprs
  432. proc addCodeForGenerics(c: PContext, n: PNode) =
  433. for i in countup(c.lastGenericIdx, c.generics.len - 1):
  434. var prc = c.generics[i].inst.sym
  435. if prc.kind in {skProc, skFunc, skMethod, skConverter} and prc.magic == mNone:
  436. if prc.ast == nil or prc.ast.sons[bodyPos] == nil:
  437. internalError(c.config, prc.info, "no code for " & prc.name.s)
  438. else:
  439. addSon(n, prc.ast)
  440. c.lastGenericIdx = c.generics.len
  441. proc myOpen(graph: ModuleGraph; module: PSym): PPassContext =
  442. var c = newContext(graph, module)
  443. if c.p != nil: internalError(graph.config, module.info, "sem.myOpen")
  444. c.semConstExpr = semConstExpr
  445. c.semExpr = semExpr
  446. c.semTryExpr = tryExpr
  447. c.semTryConstExpr = tryConstExpr
  448. c.semOperand = semOperand
  449. c.semConstBoolExpr = semConstBoolExpr
  450. c.semOverloadedCall = semOverloadedCall
  451. c.semInferredLambda = semInferredLambda
  452. c.semGenerateInstance = generateInstance
  453. c.semTypeNode = semTypeNode
  454. c.instTypeBoundOp = sigmatch.instTypeBoundOp
  455. pushProcCon(c, module)
  456. pushOwner(c, c.module)
  457. c.importTable = openScope(c)
  458. c.importTable.addSym(module) # a module knows itself
  459. if sfSystemModule in module.flags:
  460. graph.systemModule = module
  461. c.topLevelScope = openScope(c)
  462. # don't be verbose unless the module belongs to the main package:
  463. if module.owner.id == graph.config.mainPackageId:
  464. graph.config.notes = graph.config.mainPackageNotes
  465. else:
  466. if graph.config.mainPackageNotes == {}: graph.config.mainPackageNotes = graph.config.notes
  467. graph.config.notes = graph.config.foreignPackageNotes
  468. result = c
  469. proc isImportSystemStmt(g: ModuleGraph; n: PNode): bool =
  470. if g.systemModule == nil: return false
  471. case n.kind
  472. of nkImportStmt:
  473. for x in n:
  474. if x.kind == nkIdent:
  475. let f = checkModuleName(g.config, x, false)
  476. if f == g.systemModule.info.fileIndex:
  477. return true
  478. of nkImportExceptStmt, nkFromStmt:
  479. if n[0].kind == nkIdent:
  480. let f = checkModuleName(g.config, n[0], false)
  481. if f == g.systemModule.info.fileIndex:
  482. return true
  483. else: discard
  484. proc isEmptyTree(n: PNode): bool =
  485. case n.kind
  486. of nkStmtList:
  487. for it in n:
  488. if not isEmptyTree(it): return false
  489. result = true
  490. of nkEmpty, nkCommentStmt: result = true
  491. else: result = false
  492. proc semStmtAndGenerateGenerics(c: PContext, n: PNode): PNode =
  493. if n.kind == nkDefer:
  494. localError(c.config, n.info, "defer statement not supported at top level")
  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 sonsLen(a) > 0:
  516. # a generic has been added to `a`:
  517. if result.kind != nkEmpty: addSon(a, 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. trackTopLevelStmt(c.graph, c.module, result)
  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 =
  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 myClose(graph: ModuleGraph; context: PPassContext, n: PNode): PNode =
  554. var c = PContext(context)
  555. if c.config.cmd == cmdIdeTools and not c.suggestionsMade:
  556. suggestSentinel(c)
  557. closeScope(c) # close module's scope
  558. rawCloseScope(c) # imported symbols; don't check for unused ones!
  559. result = newNode(nkStmtList)
  560. if n != nil:
  561. internalError(c.config, n.info, "n is not nil") #result := n;
  562. addCodeForGenerics(c, result)
  563. if c.module.ast != nil:
  564. result.add(c.module.ast)
  565. popOwner(c)
  566. popProcCon(c)
  567. storeRemaining(c.graph, c.module)
  568. const semPass* = makePass(myOpen, myProcess, myClose,
  569. isFrontend = true)