sem.nim 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements the semantic checking pass.
  10. import
  11. ast, strutils, options, astalgo, trees,
  12. wordrecg, ropes, msgs, idents, renderer, types, platform, math,
  13. magicsys, nversion, nimsets, semfold, modulepaths, importer,
  14. procfind, lookups, pragmas, passes, semdata, semtypinst, sigmatch,
  15. intsets, transf, vmdef, vm, 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. when not defined(nimHasSinkInference):
  365. {.pragma: nosinks.}
  366. include hlo, seminst, semcall
  367. proc resetSemFlag(n: PNode) =
  368. if n != nil:
  369. excl n.flags, nfSem
  370. for i in 0..<n.safeLen:
  371. resetSemFlag(n[i])
  372. proc semAfterMacroCall(c: PContext, call, macroResult: PNode,
  373. s: PSym, flags: TExprFlags; expectedType: PType = nil): PNode =
  374. ## Semantically check the output of a macro.
  375. ## This involves processes such as re-checking the macro output for type
  376. ## coherence, making sure that variables declared with 'let' aren't
  377. ## reassigned, and binding the unbound identifiers that the macro output
  378. ## contains.
  379. inc(c.config.evalTemplateCounter)
  380. if c.config.evalTemplateCounter > evalTemplateLimit:
  381. globalError(c.config, s.info, "template instantiation too nested")
  382. c.friendModules.add(s.owner.getModule)
  383. result = macroResult
  384. resetSemFlag result
  385. if s.typ[0] == nil:
  386. result = semStmt(c, result, flags)
  387. else:
  388. var retType = s.typ[0]
  389. if retType.kind == tyTypeDesc and tfUnresolved in retType.flags and
  390. retType.len == 1:
  391. # bug #11941: template fails(T: type X, v: auto): T
  392. # does not mean we expect a tyTypeDesc.
  393. retType = retType[0]
  394. case retType.kind
  395. of tyUntyped, tyAnything:
  396. # Not expecting a type here allows templates like in ``tmodulealias.in``.
  397. result = semExpr(c, result, flags, expectedType)
  398. of tyTyped:
  399. # More restrictive version.
  400. result = semExprWithType(c, result, flags, expectedType)
  401. of tyTypeDesc:
  402. if result.kind == nkStmtList: result.transitionSonsKind(nkStmtListType)
  403. var typ = semTypeNode(c, result, nil)
  404. if typ == nil:
  405. localError(c.config, result.info, "expression has no type: " &
  406. renderTree(result, {renderNoComments}))
  407. result = newSymNode(errorSym(c, result))
  408. else:
  409. result.typ = makeTypeDesc(c, typ)
  410. #result = symNodeFromType(c, typ, n.info)
  411. else:
  412. if s.ast[genericParamsPos] != nil and retType.isMetaType:
  413. # The return type may depend on the Macro arguments
  414. # e.g. template foo(T: typedesc): seq[T]
  415. # We will instantiate the return type here, because
  416. # we now know the supplied arguments
  417. var paramTypes = newIdTable()
  418. for param, value in genericParamsInMacroCall(s, call):
  419. idTablePut(paramTypes, param.typ, value.typ)
  420. retType = generateTypeInstance(c, paramTypes,
  421. macroResult.info, retType)
  422. result = semExpr(c, result, flags, expectedType)
  423. result = fitNode(c, retType, result, result.info)
  424. #globalError(s.info, errInvalidParamKindX, typeToString(s.typ[0]))
  425. dec(c.config.evalTemplateCounter)
  426. discard c.friendModules.pop()
  427. const
  428. errMissingGenericParamsForTemplate = "'$1' has unspecified generic parameters"
  429. errFloatToString = "cannot convert '$1' to '$2'"
  430. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  431. flags: TExprFlags = {}; expectedType: PType = nil): PNode =
  432. rememberExpansion(c, nOrig.info, sym)
  433. pushInfoContext(c.config, nOrig.info, sym.detailedInfo)
  434. let info = getCallLineInfo(n)
  435. markUsed(c, info, sym)
  436. onUse(info, sym)
  437. if sym == c.p.owner:
  438. globalError(c.config, info, "recursive dependency: '$1'" % sym.name.s)
  439. let genericParams = sym.ast[genericParamsPos].len
  440. let suppliedParams = max(n.safeLen - 1, 0)
  441. if suppliedParams < genericParams:
  442. globalError(c.config, info, errMissingGenericParamsForTemplate % n.renderTree)
  443. #if c.evalContext == nil:
  444. # c.evalContext = c.createEvalContext(emStatic)
  445. result = evalMacroCall(c.module, c.idgen, c.graph, c.templInstCounter, n, nOrig, sym)
  446. if efNoSemCheck notin flags:
  447. result = semAfterMacroCall(c, n, result, sym, flags, expectedType)
  448. if c.config.macrosToExpand.hasKey(sym.name.s):
  449. message(c.config, nOrig.info, hintExpandMacro, renderTree(result))
  450. result = wrapInComesFrom(nOrig.info, sym, result)
  451. popInfoContext(c.config)
  452. proc forceBool(c: PContext, n: PNode): PNode =
  453. result = fitNode(c, getSysType(c.graph, n.info, tyBool), n, n.info)
  454. if result == nil: result = n
  455. proc semConstBoolExpr(c: PContext, n: PNode): PNode =
  456. result = forceBool(c, semConstExpr(c, n, getSysType(c.graph, n.info, tyBool)))
  457. if result.kind != nkIntLit:
  458. localError(c.config, n.info, errConstExprExpected)
  459. proc semGenericStmt(c: PContext, n: PNode): PNode
  460. proc semConceptBody(c: PContext, n: PNode): PNode
  461. include semtypes
  462. proc setGenericParamsMisc(c: PContext; n: PNode) =
  463. ## used by call defs (procs, templates, macros, ...) to analyse their generic
  464. ## params, and store the originals in miscPos for better error reporting.
  465. let orig = n[genericParamsPos]
  466. doAssert orig.kind in {nkEmpty, nkGenericParams}
  467. if n[genericParamsPos].kind == nkEmpty:
  468. n[genericParamsPos] = newNodeI(nkGenericParams, n.info)
  469. else:
  470. # we keep the original params around for better error messages, see
  471. # issue https://github.com/nim-lang/Nim/issues/1713
  472. n[genericParamsPos] = semGenericParamList(c, orig)
  473. if n[miscPos].kind == nkEmpty:
  474. n[miscPos] = newTree(nkBracket, c.graph.emptyNode, orig)
  475. else:
  476. n[miscPos][1] = orig
  477. proc caseBranchMatchesExpr(branch, matched: PNode): bool =
  478. for i in 0 ..< branch.len-1:
  479. if branch[i].kind == nkRange:
  480. if overlap(branch[i], matched): return true
  481. elif exprStructuralEquivalent(branch[i], matched):
  482. return true
  483. proc pickCaseBranchIndex(caseExpr, matched: PNode): int =
  484. let endsWithElse = caseExpr[^1].kind == nkElse
  485. for i in 1..<caseExpr.len - endsWithElse.int:
  486. if caseExpr[i].caseBranchMatchesExpr(matched):
  487. return i
  488. if endsWithElse:
  489. return caseExpr.len - 1
  490. proc defaultFieldsForTheUninitialized(c: PContext, recNode: PNode, id: var IntSet): seq[PNode]
  491. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType, id: var IntSet): PNode
  492. proc defaultNodeField(c: PContext, a: PNode): PNode
  493. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType): PNode
  494. const defaultFieldsSkipTypes = {tyGenericInst, tyAlias, tySink}
  495. proc defaultFieldsForTuple(c: PContext, recNode: PNode, id: var IntSet, hasDefault: var bool): seq[PNode] =
  496. case recNode.kind
  497. of nkRecList:
  498. for field in recNode:
  499. result.add defaultFieldsForTuple(c, field, id, hasDefault)
  500. of nkSym:
  501. let field = recNode.sym
  502. let recType = recNode.typ.skipTypes(defaultFieldsSkipTypes)
  503. if field.ast != nil: #Try to use default value
  504. hasDefault = true
  505. result.add newTree(nkExprColonExpr, recNode, field.ast)
  506. else:
  507. if recType.kind in {tyObject, tyArray, tyTuple}:
  508. let asgnExpr = defaultNodeField(c, recNode, recNode.typ, id)
  509. if asgnExpr != nil:
  510. hasDefault = true
  511. asgnExpr.flags.incl nfUseDefaultField
  512. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  513. return
  514. let asgnType = newType(tyTypeDesc, nextTypeId(c.idgen), recType.owner)
  515. rawAddSon(asgnType, recType)
  516. let asgnExpr = newTree(nkCall,
  517. newSymNode(getSysMagic(c.graph, recNode.info, "zeroDefault", mZeroDefault)),
  518. newNodeIT(nkType, recNode.info, asgnType)
  519. )
  520. asgnExpr.flags.incl nfUseDefaultField
  521. asgnExpr.typ = recType
  522. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  523. else:
  524. doAssert false
  525. proc defaultFieldsForTheUninitialized(c: PContext, recNode: PNode, id: var IntSet): seq[PNode] =
  526. case recNode.kind
  527. of nkRecList:
  528. for field in recNode:
  529. result.add defaultFieldsForTheUninitialized(c, field, id)
  530. of nkRecCase:
  531. let discriminator = recNode[0]
  532. var selectedBranch: int
  533. var defaultValue = discriminator.sym.ast
  534. if defaultValue == nil:
  535. # None of the branches were explicitly selected by the user and no value
  536. # was given to the discrimator. We can assume that it will be initialized
  537. # to zero and this will select a particular branch as a result:
  538. defaultValue = newIntNode(nkIntLit#[c.graph]#, 0)
  539. defaultValue.typ = discriminator.typ
  540. selectedBranch = recNode.pickCaseBranchIndex defaultValue
  541. defaultValue.flags.incl nfUseDefaultField
  542. result.add newTree(nkExprColonExpr, discriminator, defaultValue)
  543. result.add defaultFieldsForTheUninitialized(c, recNode[selectedBranch][^1], id)
  544. of nkSym:
  545. let field = recNode.sym
  546. let recType = recNode.typ.skipTypes(defaultFieldsSkipTypes)
  547. if field.ast != nil: #Try to use default value
  548. result.add newTree(nkExprColonExpr, recNode, field.ast)
  549. elif recType.kind in {tyObject, tyArray, tyTuple}:
  550. let asgnExpr = defaultNodeField(c, recNode, recType, id)
  551. if asgnExpr != nil:
  552. asgnExpr.typ = recType
  553. asgnExpr.flags.incl nfUseDefaultField
  554. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  555. else:
  556. doAssert false
  557. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType, id: var IntSet): PNode =
  558. let aTypSkip = aTyp.skipTypes(defaultFieldsSkipTypes)
  559. if aTypSkip.kind == tyObject:
  560. if id.containsOrIncl(aTypSkip.id):
  561. return
  562. let child = defaultFieldsForTheUninitialized(c, aTypSkip.n, id)
  563. if child.len > 0:
  564. var asgnExpr = newTree(nkObjConstr, newNodeIT(nkType, a.info, aTypSkip))
  565. asgnExpr.typ = aTypSkip
  566. asgnExpr.sons.add child
  567. result = semExpr(c, asgnExpr)
  568. elif aTypSkip.kind == tyArray:
  569. let child = defaultNodeField(c, a, aTypSkip[1], id)
  570. if child != nil:
  571. let node = newNode(nkIntLit)
  572. node.intVal = toInt64(lengthOrd(c.graph.config, aTypSkip))
  573. result = semExpr(c, newTree(nkCall, newSymNode(getCompilerProc(c.graph, "nimArrayWith"), a.info),
  574. semExprWithType(c, child),
  575. node
  576. ))
  577. result.typ = aTyp
  578. elif aTypSkip.kind == tyTuple:
  579. var hasDefault = false
  580. if aTypSkip.n != nil:
  581. let children = defaultFieldsForTuple(c, aTypSkip.n, id, hasDefault)
  582. if hasDefault and children.len > 0:
  583. result = newNodeI(nkTupleConstr, a.info)
  584. result.typ = aTyp
  585. result.sons.add children
  586. result = semExpr(c, result)
  587. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType): PNode =
  588. var s = initIntSet()
  589. defaultNodeField(c, a, aTyp, s)
  590. proc defaultNodeField(c: PContext, a: PNode): PNode =
  591. var s = initIntSet()
  592. result = defaultNodeField(c, a, a.typ, s)
  593. include semtempl, semgnrc, semstmts, semexprs
  594. proc addCodeForGenerics(c: PContext, n: PNode) =
  595. for i in c.lastGenericIdx..<c.generics.len:
  596. var prc = c.generics[i].inst.sym
  597. if prc.kind in {skProc, skFunc, skMethod, skConverter} and prc.magic == mNone:
  598. if prc.ast == nil or prc.ast[bodyPos] == nil:
  599. internalError(c.config, prc.info, "no code for " & prc.name.s)
  600. else:
  601. n.add prc.ast
  602. c.lastGenericIdx = c.generics.len
  603. proc myOpen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {.nosinks.} =
  604. var c = newContext(graph, module)
  605. c.idgen = idgen
  606. c.enforceVoidContext = newType(tyTyped, nextTypeId(idgen), nil)
  607. c.voidType = newType(tyVoid, nextTypeId(idgen), nil)
  608. if c.p != nil: internalError(graph.config, module.info, "sem.myOpen")
  609. c.semConstExpr = semConstExpr
  610. c.semExpr = semExpr
  611. c.semTryExpr = tryExpr
  612. c.semTryConstExpr = tryConstExpr
  613. c.computeRequiresInit = computeRequiresInit
  614. c.semOperand = semOperand
  615. c.semConstBoolExpr = semConstBoolExpr
  616. c.semOverloadedCall = semOverloadedCall
  617. c.semInferredLambda = semInferredLambda
  618. c.semGenerateInstance = generateInstance
  619. c.semTypeNode = semTypeNode
  620. c.instTypeBoundOp = sigmatch.instTypeBoundOp
  621. c.hasUnresolvedArgs = hasUnresolvedArgs
  622. c.templInstCounter = new int
  623. pushProcCon(c, module)
  624. pushOwner(c, c.module)
  625. c.moduleScope = openScope(c)
  626. c.moduleScope.addSym(module) # a module knows itself
  627. if sfSystemModule in module.flags:
  628. graph.systemModule = module
  629. c.topLevelScope = openScope(c)
  630. result = c
  631. proc isImportSystemStmt(g: ModuleGraph; n: PNode): bool =
  632. if g.systemModule == nil: return false
  633. case n.kind
  634. of nkImportStmt:
  635. for x in n:
  636. if x.kind == nkIdent:
  637. let f = checkModuleName(g.config, x, false)
  638. if f == g.systemModule.info.fileIndex:
  639. return true
  640. of nkImportExceptStmt, nkFromStmt:
  641. if n[0].kind == nkIdent:
  642. let f = checkModuleName(g.config, n[0], false)
  643. if f == g.systemModule.info.fileIndex:
  644. return true
  645. else: discard
  646. proc isEmptyTree(n: PNode): bool =
  647. case n.kind
  648. of nkStmtList:
  649. for it in n:
  650. if not isEmptyTree(it): return false
  651. result = true
  652. of nkEmpty, nkCommentStmt: result = true
  653. else: result = false
  654. proc semStmtAndGenerateGenerics(c: PContext, n: PNode): PNode =
  655. if c.topStmts == 0 and not isImportSystemStmt(c.graph, n):
  656. if sfSystemModule notin c.module.flags and not isEmptyTree(n):
  657. assert c.graph.systemModule != nil
  658. c.moduleScope.addSym c.graph.systemModule # import the "System" identifier
  659. importAllSymbols(c, c.graph.systemModule)
  660. inc c.topStmts
  661. else:
  662. inc c.topStmts
  663. if sfNoForward in c.module.flags:
  664. result = semAllTypeSections(c, n)
  665. else:
  666. result = n
  667. result = semStmt(c, result, {})
  668. when false:
  669. # Code generators are lazy now and can deal with undeclared procs, so these
  670. # steps are not required anymore and actually harmful for the upcoming
  671. # destructor support.
  672. # BUGFIX: process newly generated generics here, not at the end!
  673. if c.lastGenericIdx < c.generics.len:
  674. var a = newNodeI(nkStmtList, n.info)
  675. addCodeForGenerics(c, a)
  676. if a.len > 0:
  677. # a generic has been added to `a`:
  678. if result.kind != nkEmpty: a.add result
  679. result = a
  680. result = hloStmt(c, result)
  681. if c.config.cmd == cmdInteractive and not isEmptyType(result.typ):
  682. result = buildEchoStmt(c, result)
  683. if c.config.cmd == cmdIdeTools:
  684. appendToModule(c.module, result)
  685. trackStmt(c, c.module, result, isTopLevel = true)
  686. proc recoverContext(c: PContext) =
  687. # clean up in case of a semantic error: We clean up the stacks, etc. This is
  688. # faster than wrapping every stack operation in a 'try finally' block and
  689. # requires far less code.
  690. c.currentScope = c.topLevelScope
  691. while getCurrOwner(c).kind != skModule: popOwner(c)
  692. while c.p != nil and c.p.owner.kind != skModule: c.p = c.p.next
  693. proc myProcess(context: PPassContext, n: PNode): PNode {.nosinks.} =
  694. var c = PContext(context)
  695. # no need for an expensive 'try' if we stop after the first error anyway:
  696. if c.config.errorMax <= 1:
  697. result = semStmtAndGenerateGenerics(c, n)
  698. else:
  699. let oldContextLen = msgs.getInfoContextLen(c.config)
  700. let oldInGenericInst = c.inGenericInst
  701. try:
  702. result = semStmtAndGenerateGenerics(c, n)
  703. except ERecoverableError, ESuggestDone:
  704. recoverContext(c)
  705. c.inGenericInst = oldInGenericInst
  706. msgs.setInfoContextLen(c.config, oldContextLen)
  707. if getCurrentException() of ESuggestDone:
  708. c.suggestionsMade = true
  709. result = nil
  710. else:
  711. result = newNodeI(nkEmpty, n.info)
  712. #if c.config.cmd == cmdIdeTools: findSuggest(c, n)
  713. storeRodNode(c, result)
  714. proc reportUnusedModules(c: PContext) =
  715. for i in 0..high(c.unusedImports):
  716. if sfUsed notin c.unusedImports[i][0].flags:
  717. message(c.config, c.unusedImports[i][1], warnUnusedImportX, c.unusedImports[i][0].name.s)
  718. proc myClose(graph: ModuleGraph; context: PPassContext, n: PNode): PNode =
  719. var c = PContext(context)
  720. if c.config.cmd == cmdIdeTools and not c.suggestionsMade:
  721. suggestSentinel(c)
  722. closeScope(c) # close module's scope
  723. rawCloseScope(c) # imported symbols; don't check for unused ones!
  724. reportUnusedModules(c)
  725. result = newNode(nkStmtList)
  726. if n != nil:
  727. internalError(c.config, n.info, "n is not nil") #result := n;
  728. addCodeForGenerics(c, result)
  729. if c.module.ast != nil:
  730. result.add(c.module.ast)
  731. popOwner(c)
  732. popProcCon(c)
  733. sealRodFile(c)
  734. const semPass* = makePass(myOpen, myProcess, myClose,
  735. isFrontend = true)