sem.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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, strtabs
  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 != tyUntyped:
  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: tyUntyped)
  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 {tyUntyped, tyNil}: result = y
  104. elif b.kind in {tyUntyped, tyNil}: result = x
  105. elif a.kind == tyTyped: result = a
  106. elif b.kind == tyTyped: 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 {tyUntyped, tyTyped, 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 tyUntyped:
  365. # Not expecting a type here allows templates like in ``tmodulealias.in``.
  366. result = semExpr(c, result, flags)
  367. of tyTyped:
  368. # More restrictive version.
  369. result = semExprWithType(c, result, flags)
  370. of tyTypeDesc:
  371. if result.kind == nkStmtList: result.kind = nkStmtListType
  372. var typ = semTypeNode(c, result, nil)
  373. if typ == nil:
  374. localError(c.config, result.info, "expression has no type: " &
  375. renderTree(result, {renderNoComments}))
  376. result = newSymNode(errorSym(c, result))
  377. else:
  378. result.typ = makeTypeDesc(c, typ)
  379. #result = symNodeFromType(c, typ, n.info)
  380. else:
  381. var retType = s.typ.sons[0]
  382. if s.ast[genericParamsPos] != nil and retType.isMetaType:
  383. # The return type may depend on the Macro arguments
  384. # e.g. template foo(T: typedesc): seq[T]
  385. # We will instantiate the return type here, because
  386. # we now know the supplied arguments
  387. var paramTypes = newIdTable()
  388. for param, value in genericParamsInMacroCall(s, call):
  389. idTablePut(paramTypes, param.typ, value.typ)
  390. retType = generateTypeInstance(c, paramTypes,
  391. macroResult.info, retType)
  392. result = semExpr(c, result, flags)
  393. result = fitNode(c, retType, result, result.info)
  394. #globalError(s.info, errInvalidParamKindX, typeToString(s.typ.sons[0]))
  395. dec(c.config.evalTemplateCounter)
  396. discard c.friendModules.pop()
  397. const
  398. errMissingGenericParamsForTemplate = "'$1' has unspecified generic parameters"
  399. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  400. flags: TExprFlags = {}): PNode =
  401. pushInfoContext(c.config, nOrig.info, sym.detailedInfo)
  402. let info = getCallLineInfo(n)
  403. markUsed(c.config, info, sym, c.graph.usageSym)
  404. onUse(info, sym)
  405. if sym == c.p.owner:
  406. globalError(c.config, info, "recursive dependency: '$1'" % sym.name.s)
  407. let genericParams = sym.ast[genericParamsPos].len
  408. let suppliedParams = max(n.safeLen - 1, 0)
  409. if suppliedParams < genericParams:
  410. globalError(c.config, info, errMissingGenericParamsForTemplate % n.renderTree)
  411. #if c.evalContext == nil:
  412. # c.evalContext = c.createEvalContext(emStatic)
  413. result = evalMacroCall(c.module, c.graph, n, nOrig, sym)
  414. if efNoSemCheck notin flags:
  415. result = semAfterMacroCall(c, n, result, sym, flags)
  416. if c.config.macrosToExpand.hasKey(sym.name.s):
  417. message(c.config, nOrig.info, hintExpandMacro, renderTree(result))
  418. result = wrapInComesFrom(nOrig.info, sym, result)
  419. popInfoContext(c.config)
  420. proc forceBool(c: PContext, n: PNode): PNode =
  421. result = fitNode(c, getSysType(c.graph, n.info, tyBool), n, n.info)
  422. if result == nil: result = n
  423. proc semConstBoolExpr(c: PContext, n: PNode): PNode =
  424. let nn = semExprWithType(c, n)
  425. result = fitNode(c, getSysType(c.graph, n.info, tyBool), nn, nn.info)
  426. if result == nil:
  427. localError(c.config, n.info, errConstExprExpected)
  428. return nn
  429. result = getConstExpr(c.module, result, c.graph)
  430. if result == nil:
  431. localError(c.config, n.info, errConstExprExpected)
  432. result = nn
  433. proc semGenericStmt(c: PContext, n: PNode): PNode
  434. proc semConceptBody(c: PContext, n: PNode): PNode
  435. include semtypes, semtempl, semgnrc, semstmts, semexprs
  436. proc addCodeForGenerics(c: PContext, n: PNode) =
  437. for i in c.lastGenericIdx ..< c.generics.len:
  438. var prc = c.generics[i].inst.sym
  439. if prc.kind in {skProc, skFunc, skMethod, skConverter} and prc.magic == mNone:
  440. if prc.ast == nil or prc.ast.sons[bodyPos] == nil:
  441. internalError(c.config, prc.info, "no code for " & prc.name.s)
  442. else:
  443. addSon(n, prc.ast)
  444. c.lastGenericIdx = c.generics.len
  445. proc myOpen(graph: ModuleGraph; module: PSym): PPassContext =
  446. var c = newContext(graph, module)
  447. if c.p != nil: internalError(graph.config, module.info, "sem.myOpen")
  448. c.semConstExpr = semConstExpr
  449. c.semExpr = semExpr
  450. c.semTryExpr = tryExpr
  451. c.semTryConstExpr = tryConstExpr
  452. c.semOperand = semOperand
  453. c.semConstBoolExpr = semConstBoolExpr
  454. c.semOverloadedCall = semOverloadedCall
  455. c.semInferredLambda = semInferredLambda
  456. c.semGenerateInstance = generateInstance
  457. c.semTypeNode = semTypeNode
  458. c.instTypeBoundOp = sigmatch.instTypeBoundOp
  459. pushProcCon(c, module)
  460. pushOwner(c, c.module)
  461. c.importTable = openScope(c)
  462. c.importTable.addSym(module) # a module knows itself
  463. if sfSystemModule in module.flags:
  464. graph.systemModule = module
  465. c.topLevelScope = openScope(c)
  466. # don't be verbose unless the module belongs to the main package:
  467. if module.owner.id == graph.config.mainPackageId:
  468. graph.config.notes = graph.config.mainPackageNotes
  469. else:
  470. if graph.config.mainPackageNotes == {}: graph.config.mainPackageNotes = graph.config.notes
  471. graph.config.notes = graph.config.foreignPackageNotes
  472. result = c
  473. proc isImportSystemStmt(g: ModuleGraph; n: PNode): bool =
  474. if g.systemModule == nil: return false
  475. case n.kind
  476. of nkImportStmt:
  477. for x in n:
  478. if x.kind == nkIdent:
  479. let f = checkModuleName(g.config, x, false)
  480. if f == g.systemModule.info.fileIndex:
  481. return true
  482. of nkImportExceptStmt, nkFromStmt:
  483. if n[0].kind == nkIdent:
  484. let f = checkModuleName(g.config, n[0], false)
  485. if f == g.systemModule.info.fileIndex:
  486. return true
  487. else: discard
  488. proc isEmptyTree(n: PNode): bool =
  489. case n.kind
  490. of nkStmtList:
  491. for it in n:
  492. if not isEmptyTree(it): return false
  493. result = true
  494. of nkEmpty, nkCommentStmt: result = true
  495. else: result = false
  496. proc semStmtAndGenerateGenerics(c: PContext, n: PNode): PNode =
  497. if c.topStmts == 0 and not isImportSystemStmt(c.graph, n):
  498. if sfSystemModule notin c.module.flags and not isEmptyTree(n):
  499. c.importTable.addSym c.graph.systemModule # import the "System" identifier
  500. importAllSymbols(c, c.graph.systemModule)
  501. inc c.topStmts
  502. else:
  503. inc c.topStmts
  504. if sfNoForward in c.module.flags:
  505. result = semAllTypeSections(c, n)
  506. else:
  507. result = n
  508. result = semStmt(c, result, {})
  509. when false:
  510. # Code generators are lazy now and can deal with undeclared procs, so these
  511. # steps are not required anymore and actually harmful for the upcoming
  512. # destructor support.
  513. # BUGFIX: process newly generated generics here, not at the end!
  514. if c.lastGenericIdx < c.generics.len:
  515. var a = newNodeI(nkStmtList, n.info)
  516. addCodeForGenerics(c, a)
  517. if sonsLen(a) > 0:
  518. # a generic has been added to `a`:
  519. if result.kind != nkEmpty: addSon(a, result)
  520. result = a
  521. result = hloStmt(c, result)
  522. if c.config.cmd == cmdInteractive and not isEmptyType(result.typ):
  523. result = buildEchoStmt(c, result)
  524. if c.config.cmd == cmdIdeTools:
  525. appendToModule(c.module, result)
  526. trackTopLevelStmt(c, c.module, result)
  527. proc recoverContext(c: PContext) =
  528. # clean up in case of a semantic error: We clean up the stacks, etc. This is
  529. # faster than wrapping every stack operation in a 'try finally' block and
  530. # requires far less code.
  531. c.currentScope = c.topLevelScope
  532. while getCurrOwner(c).kind != skModule: popOwner(c)
  533. while c.p != nil and c.p.owner.kind != skModule: c.p = c.p.next
  534. proc myProcess(context: PPassContext, n: PNode): PNode =
  535. var c = PContext(context)
  536. # no need for an expensive 'try' if we stop after the first error anyway:
  537. if c.config.errorMax <= 1:
  538. result = semStmtAndGenerateGenerics(c, n)
  539. else:
  540. let oldContextLen = msgs.getInfoContextLen(c.config)
  541. let oldInGenericInst = c.inGenericInst
  542. try:
  543. result = semStmtAndGenerateGenerics(c, n)
  544. except ERecoverableError, ESuggestDone:
  545. recoverContext(c)
  546. c.inGenericInst = oldInGenericInst
  547. msgs.setInfoContextLen(c.config, oldContextLen)
  548. if getCurrentException() of ESuggestDone:
  549. c.suggestionsMade = true
  550. result = nil
  551. else:
  552. result = newNodeI(nkEmpty, n.info)
  553. #if c.config.cmd == cmdIdeTools: findSuggest(c, n)
  554. rod.storeNode(c.graph, c.module, result)
  555. proc myClose(graph: ModuleGraph; context: PPassContext, n: PNode): PNode =
  556. var c = PContext(context)
  557. if c.config.cmd == cmdIdeTools and not c.suggestionsMade:
  558. suggestSentinel(c)
  559. closeScope(c) # close module's scope
  560. rawCloseScope(c) # imported symbols; don't check for unused ones!
  561. result = newNode(nkStmtList)
  562. if n != nil:
  563. internalError(c.config, n.info, "n is not nil") #result := n;
  564. addCodeForGenerics(c, result)
  565. if c.module.ast != nil:
  566. result.add(c.module.ast)
  567. popOwner(c)
  568. popProcCon(c)
  569. storeRemaining(c.graph, c.module)
  570. const semPass* = makePass(myOpen, myProcess, myClose,
  571. isFrontend = true)