sem.nim 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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. 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, id: var IntSet): seq[PNode]
  489. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType, id: var IntSet): PNode
  490. proc defaultNodeField(c: PContext, a: PNode): PNode
  491. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType): PNode
  492. const defaultFieldsSkipTypes = {tyGenericInst, tyAlias, tySink}
  493. proc defaultFieldsForTuple(c: PContext, recNode: PNode, id: var IntSet, hasDefault: var bool): seq[PNode] =
  494. case recNode.kind
  495. of nkRecList:
  496. for field in recNode:
  497. result.add defaultFieldsForTuple(c, field, id, hasDefault)
  498. of nkSym:
  499. let field = recNode.sym
  500. let recType = recNode.typ.skipTypes(defaultFieldsSkipTypes)
  501. if field.ast != nil: #Try to use default value
  502. hasDefault = true
  503. result.add newTree(nkExprColonExpr, recNode, field.ast)
  504. else:
  505. if recType.kind in {tyObject, tyArray, tyTuple}:
  506. let asgnExpr = defaultNodeField(c, recNode, recNode.typ, id)
  507. if asgnExpr != nil:
  508. hasDefault = true
  509. asgnExpr.flags.incl nfUseDefaultField
  510. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  511. return
  512. let asgnType = newType(tyTypeDesc, nextTypeId(c.idgen), recType.owner)
  513. rawAddSon(asgnType, recType)
  514. let asgnExpr = newTree(nkCall,
  515. newSymNode(getSysMagic(c.graph, recNode.info, "zeroDefault", mZeroDefault)),
  516. newNodeIT(nkType, recNode.info, asgnType)
  517. )
  518. asgnExpr.flags.incl nfUseDefaultField
  519. asgnExpr.typ = recType
  520. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  521. else:
  522. doAssert false
  523. proc defaultFieldsForTheUninitialized(c: PContext, recNode: PNode, id: var IntSet): seq[PNode] =
  524. case recNode.kind
  525. of nkRecList:
  526. for field in recNode:
  527. result.add defaultFieldsForTheUninitialized(c, field, id)
  528. of nkRecCase:
  529. let discriminator = recNode[0]
  530. var selectedBranch: int
  531. var defaultValue = discriminator.sym.ast
  532. if defaultValue == nil:
  533. # None of the branches were explicitly selected by the user and no value
  534. # was given to the discrimator. We can assume that it will be initialized
  535. # to zero and this will select a particular branch as a result:
  536. defaultValue = newIntNode(nkIntLit#[c.graph]#, 0)
  537. defaultValue.typ = discriminator.typ
  538. selectedBranch = recNode.pickCaseBranchIndex defaultValue
  539. defaultValue.flags.incl nfUseDefaultField
  540. result.add newTree(nkExprColonExpr, discriminator, defaultValue)
  541. result.add defaultFieldsForTheUninitialized(c, recNode[selectedBranch][^1], id)
  542. of nkSym:
  543. let field = recNode.sym
  544. let recType = recNode.typ.skipTypes(defaultFieldsSkipTypes)
  545. if field.ast != nil: #Try to use default value
  546. result.add newTree(nkExprColonExpr, recNode, field.ast)
  547. elif recType.kind in {tyObject, tyArray, tyTuple}:
  548. let asgnExpr = defaultNodeField(c, recNode, recType, id)
  549. if asgnExpr != nil:
  550. asgnExpr.typ = recType
  551. asgnExpr.flags.incl nfUseDefaultField
  552. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  553. else:
  554. doAssert false
  555. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType, id: var IntSet): PNode =
  556. let aTypSkip = aTyp.skipTypes(defaultFieldsSkipTypes)
  557. if aTypSkip.kind == tyObject:
  558. if id.containsOrIncl(aTypSkip.id):
  559. return
  560. let child = defaultFieldsForTheUninitialized(c, aTypSkip.n, id)
  561. if child.len > 0:
  562. var asgnExpr = newTree(nkObjConstr, newNodeIT(nkType, a.info, aTypSkip))
  563. asgnExpr.typ = aTypSkip
  564. asgnExpr.sons.add child
  565. result = semExpr(c, asgnExpr)
  566. elif aTypSkip.kind == tyArray:
  567. let child = defaultNodeField(c, a, aTypSkip[1], id)
  568. if child != nil:
  569. let node = newNode(nkIntLit)
  570. node.intVal = toInt64(lengthOrd(c.graph.config, aTypSkip))
  571. result = semExpr(c, newTree(nkCall, newSymNode(getCompilerProc(c.graph, "nimArrayWith"), a.info),
  572. semExprWithType(c, child),
  573. node
  574. ))
  575. result.typ = aTyp
  576. elif aTypSkip.kind == tyTuple:
  577. var hasDefault = false
  578. if aTypSkip.n != nil:
  579. let children = defaultFieldsForTuple(c, aTypSkip.n, id, hasDefault)
  580. if hasDefault and children.len > 0:
  581. result = newNodeI(nkTupleConstr, a.info)
  582. result.typ = aTyp
  583. result.sons.add children
  584. result = semExpr(c, result)
  585. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType): PNode =
  586. var s = initIntSet()
  587. defaultNodeField(c, a, aTyp, s)
  588. proc defaultNodeField(c: PContext, a: PNode): PNode =
  589. var s = initIntSet()
  590. result = defaultNodeField(c, a, a.typ, s)
  591. include semtempl, semgnrc, semstmts, semexprs
  592. proc addCodeForGenerics(c: PContext, n: PNode) =
  593. for i in c.lastGenericIdx..<c.generics.len:
  594. var prc = c.generics[i].inst.sym
  595. if prc.kind in {skProc, skFunc, skMethod, skConverter} and prc.magic == mNone:
  596. if prc.ast == nil or prc.ast[bodyPos] == nil:
  597. internalError(c.config, prc.info, "no code for " & prc.name.s)
  598. else:
  599. n.add prc.ast
  600. c.lastGenericIdx = c.generics.len
  601. proc myOpen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {.nosinks.} =
  602. var c = newContext(graph, module)
  603. c.idgen = idgen
  604. c.enforceVoidContext = newType(tyTyped, nextTypeId(idgen), nil)
  605. c.voidType = newType(tyVoid, nextTypeId(idgen), nil)
  606. if c.p != nil: internalError(graph.config, module.info, "sem.myOpen")
  607. c.semConstExpr = semConstExpr
  608. c.semExpr = semExpr
  609. c.semTryExpr = tryExpr
  610. c.semTryConstExpr = tryConstExpr
  611. c.computeRequiresInit = computeRequiresInit
  612. c.semOperand = semOperand
  613. c.semConstBoolExpr = semConstBoolExpr
  614. c.semOverloadedCall = semOverloadedCall
  615. c.semInferredLambda = semInferredLambda
  616. c.semGenerateInstance = generateInstance
  617. c.semTypeNode = semTypeNode
  618. c.instTypeBoundOp = sigmatch.instTypeBoundOp
  619. c.hasUnresolvedArgs = hasUnresolvedArgs
  620. c.templInstCounter = new int
  621. pushProcCon(c, module)
  622. pushOwner(c, c.module)
  623. c.moduleScope = openScope(c)
  624. c.moduleScope.addSym(module) # a module knows itself
  625. if sfSystemModule in module.flags:
  626. graph.systemModule = module
  627. c.topLevelScope = openScope(c)
  628. result = c
  629. proc isImportSystemStmt(g: ModuleGraph; n: PNode): bool =
  630. if g.systemModule == nil: return false
  631. case n.kind
  632. of nkImportStmt:
  633. for x in n:
  634. if x.kind == nkIdent:
  635. let f = checkModuleName(g.config, x, false)
  636. if f == g.systemModule.info.fileIndex:
  637. return true
  638. of nkImportExceptStmt, nkFromStmt:
  639. if n[0].kind == nkIdent:
  640. let f = checkModuleName(g.config, n[0], false)
  641. if f == g.systemModule.info.fileIndex:
  642. return true
  643. else: discard
  644. proc isEmptyTree(n: PNode): bool =
  645. case n.kind
  646. of nkStmtList:
  647. for it in n:
  648. if not isEmptyTree(it): return false
  649. result = true
  650. of nkEmpty, nkCommentStmt: result = true
  651. else: result = false
  652. proc semStmtAndGenerateGenerics(c: PContext, n: PNode): PNode =
  653. if c.topStmts == 0 and not isImportSystemStmt(c.graph, n):
  654. if sfSystemModule notin c.module.flags and not isEmptyTree(n):
  655. assert c.graph.systemModule != nil
  656. c.moduleScope.addSym c.graph.systemModule # import the "System" identifier
  657. importAllSymbols(c, c.graph.systemModule)
  658. inc c.topStmts
  659. else:
  660. inc c.topStmts
  661. if sfNoForward in c.module.flags:
  662. result = semAllTypeSections(c, n)
  663. else:
  664. result = n
  665. result = semStmt(c, result, {})
  666. when false:
  667. # Code generators are lazy now and can deal with undeclared procs, so these
  668. # steps are not required anymore and actually harmful for the upcoming
  669. # destructor support.
  670. # BUGFIX: process newly generated generics here, not at the end!
  671. if c.lastGenericIdx < c.generics.len:
  672. var a = newNodeI(nkStmtList, n.info)
  673. addCodeForGenerics(c, a)
  674. if a.len > 0:
  675. # a generic has been added to `a`:
  676. if result.kind != nkEmpty: a.add result
  677. result = a
  678. result = hloStmt(c, result)
  679. if c.config.cmd == cmdInteractive and not isEmptyType(result.typ):
  680. result = buildEchoStmt(c, result)
  681. if c.config.cmd == cmdIdeTools:
  682. appendToModule(c.module, result)
  683. trackStmt(c, c.module, result, isTopLevel = true)
  684. proc recoverContext(c: PContext) =
  685. # clean up in case of a semantic error: We clean up the stacks, etc. This is
  686. # faster than wrapping every stack operation in a 'try finally' block and
  687. # requires far less code.
  688. c.currentScope = c.topLevelScope
  689. while getCurrOwner(c).kind != skModule: popOwner(c)
  690. while c.p != nil and c.p.owner.kind != skModule: c.p = c.p.next
  691. proc myProcess(context: PPassContext, n: PNode): PNode {.nosinks.} =
  692. var c = PContext(context)
  693. # no need for an expensive 'try' if we stop after the first error anyway:
  694. if c.config.errorMax <= 1:
  695. result = semStmtAndGenerateGenerics(c, n)
  696. else:
  697. let oldContextLen = msgs.getInfoContextLen(c.config)
  698. let oldInGenericInst = c.inGenericInst
  699. try:
  700. result = semStmtAndGenerateGenerics(c, n)
  701. except ERecoverableError, ESuggestDone:
  702. recoverContext(c)
  703. c.inGenericInst = oldInGenericInst
  704. msgs.setInfoContextLen(c.config, oldContextLen)
  705. if getCurrentException() of ESuggestDone:
  706. c.suggestionsMade = true
  707. result = nil
  708. else:
  709. result = newNodeI(nkEmpty, n.info)
  710. #if c.config.cmd == cmdIdeTools: findSuggest(c, n)
  711. storeRodNode(c, result)
  712. proc reportUnusedModules(c: PContext) =
  713. for i in 0..high(c.unusedImports):
  714. if sfUsed notin c.unusedImports[i][0].flags:
  715. message(c.config, c.unusedImports[i][1], warnUnusedImportX, c.unusedImports[i][0].name.s)
  716. proc myClose(graph: ModuleGraph; context: PPassContext, n: PNode): PNode =
  717. var c = PContext(context)
  718. if c.config.cmd == cmdIdeTools and not c.suggestionsMade:
  719. suggestSentinel(c)
  720. closeScope(c) # close module's scope
  721. rawCloseScope(c) # imported symbols; don't check for unused ones!
  722. reportUnusedModules(c)
  723. result = newNode(nkStmtList)
  724. if n != nil:
  725. internalError(c.config, n.info, "n is not nil") #result := n;
  726. addCodeForGenerics(c, result)
  727. if c.module.ast != nil:
  728. result.add(c.module.ast)
  729. popOwner(c)
  730. popProcCon(c)
  731. sealRodFile(c)
  732. const semPass* = makePass(myOpen, myProcess, myClose,
  733. isFrontend = true)