sem.nim 31 KB

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