sem.nim 33 KB

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