sem.nim 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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 kind in {skForVar, skLet, skVar} and result.owner.kind == skModule:
  234. # incl(result.flags, sfGlobal)
  235. when defined(nimsuggest):
  236. suggestDecl(c, n, result)
  237. proc semIdentVis(c: PContext, kind: TSymKind, n: PNode,
  238. allowed: TSymFlags): PSym
  239. # identifier with visibility
  240. proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode,
  241. allowed: TSymFlags): PSym
  242. proc typeAllowedCheck(c: PContext; info: TLineInfo; typ: PType; kind: TSymKind;
  243. flags: TTypeAllowedFlags = {}) =
  244. let t = typeAllowed(typ, kind, c, flags)
  245. if t != nil:
  246. var err: string
  247. if t == typ:
  248. err = "invalid type: '$1' for $2" % [typeToString(typ), toHumanStr(kind)]
  249. if kind in {skVar, skLet, skConst} and taIsTemplateOrMacro in flags:
  250. err &= ". Did you mean to call the $1 with '()'?" % [toHumanStr(typ.owner.kind)]
  251. else:
  252. err = "invalid type: '$1' in this context: '$2' for $3" % [typeToString(t),
  253. typeToString(typ), toHumanStr(kind)]
  254. localError(c.config, info, err)
  255. proc paramsTypeCheck(c: PContext, typ: PType) {.inline.} =
  256. typeAllowedCheck(c, typ.n.info, typ, skProc)
  257. proc expectMacroOrTemplateCall(c: PContext, n: PNode): PSym
  258. proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode
  259. proc semWhen(c: PContext, n: PNode, semCheck: bool = true): PNode
  260. proc semTemplateExpr(c: PContext, n: PNode, s: PSym,
  261. flags: TExprFlags = {}; expectedType: PType = nil): PNode
  262. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  263. flags: TExprFlags = {}; expectedType: PType = nil): PNode
  264. when false:
  265. proc createEvalContext(c: PContext, mode: TEvalMode): PEvalContext =
  266. result = newEvalContext(c.module, mode)
  267. result.getType = proc (n: PNode): PNode =
  268. result = tryExpr(c, n)
  269. if result == nil:
  270. result = newSymNode(errorSym(c, n))
  271. elif result.typ == nil:
  272. result = newSymNode(getSysSym"void")
  273. else:
  274. result.typ = makeTypeDesc(c, result.typ)
  275. result.handleIsOperator = proc (n: PNode): PNode =
  276. result = isOpImpl(c, n)
  277. proc hasCycle(n: PNode): bool =
  278. result = false
  279. incl n.flags, nfNone
  280. for i in 0..<n.safeLen:
  281. if nfNone in n[i].flags or hasCycle(n[i]):
  282. result = true
  283. break
  284. excl n.flags, nfNone
  285. proc fixupTypeAfterEval(c: PContext, evaluated, eOrig: PNode): PNode =
  286. # recompute the types as 'eval' isn't guaranteed to construct types nor
  287. # that the types are sound:
  288. when true:
  289. if eOrig.typ.kind in {tyUntyped, tyTyped, tyTypeDesc}:
  290. result = semExprWithType(c, evaluated)
  291. else:
  292. result = evaluated
  293. let expectedType = eOrig.typ.skipTypes({tyStatic})
  294. if hasCycle(result):
  295. result = localErrorNode(c, eOrig, "the resulting AST is cyclic and cannot be processed further")
  296. else:
  297. semmacrosanity.annotateType(result, expectedType, c.config)
  298. else:
  299. result = semExprWithType(c, evaluated)
  300. #result = fitNode(c, e.typ, result) inlined with special case:
  301. let arg = result
  302. result = indexTypesMatch(c, eOrig.typ, arg.typ, arg)
  303. if result == nil:
  304. result = arg
  305. # for 'tcnstseq' we support [] to become 'seq'
  306. if eOrig.typ.skipTypes(abstractInst).kind == tySequence and
  307. isArrayConstr(arg):
  308. arg.typ = eOrig.typ
  309. proc tryConstExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  310. var e = semExprWithType(c, n, expectedType = expectedType)
  311. if e == nil: return
  312. result = getConstExpr(c.module, e, c.idgen, c.graph)
  313. if result != nil: return
  314. let oldErrorCount = c.config.errorCounter
  315. let oldErrorMax = c.config.errorMax
  316. let oldErrorOutputs = c.config.m.errorOutputs
  317. c.config.m.errorOutputs = {}
  318. c.config.errorMax = high(int) # `setErrorMaxHighMaybe` not appropriate here
  319. when defined(nimsuggest):
  320. # Remove the error hook so nimsuggest doesn't report errors there
  321. let tempHook = c.graph.config.structuredErrorHook
  322. c.graph.config.structuredErrorHook = nil
  323. try:
  324. result = evalConstExpr(c.module, c.idgen, c.graph, e)
  325. if result == nil or result.kind == nkEmpty:
  326. result = nil
  327. else:
  328. result = fixupTypeAfterEval(c, result, e)
  329. except ERecoverableError:
  330. result = nil
  331. when defined(nimsuggest):
  332. # Restore the error hook
  333. c.graph.config.structuredErrorHook = tempHook
  334. c.config.errorCounter = oldErrorCount
  335. c.config.errorMax = oldErrorMax
  336. c.config.m.errorOutputs = oldErrorOutputs
  337. const
  338. errConstExprExpected = "constant expression expected"
  339. proc semConstExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  340. var e = semExprWithType(c, n, expectedType = expectedType)
  341. if e == nil:
  342. localError(c.config, n.info, errConstExprExpected)
  343. return n
  344. if e.kind in nkSymChoices and e[0].typ.skipTypes(abstractInst).kind == tyEnum:
  345. return e
  346. result = getConstExpr(c.module, e, c.idgen, c.graph)
  347. if result == nil:
  348. #if e.kind == nkEmpty: globalError(n.info, errConstExprExpected)
  349. result = evalConstExpr(c.module, c.idgen, c.graph, e)
  350. if result == nil or result.kind == nkEmpty:
  351. if e.info != n.info:
  352. pushInfoContext(c.config, n.info)
  353. localError(c.config, e.info, errConstExprExpected)
  354. popInfoContext(c.config)
  355. else:
  356. localError(c.config, e.info, errConstExprExpected)
  357. # error correction:
  358. result = e
  359. else:
  360. result = fixupTypeAfterEval(c, result, e)
  361. proc semExprFlagDispatched(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  362. if efNeedStatic in flags:
  363. if efPreferNilResult in flags:
  364. return tryConstExpr(c, n, expectedType)
  365. else:
  366. return semConstExpr(c, n, expectedType)
  367. else:
  368. result = semExprWithType(c, n, flags, expectedType)
  369. if efPreferStatic in flags:
  370. var evaluated = getConstExpr(c.module, result, c.idgen, c.graph)
  371. if evaluated != nil: return evaluated
  372. evaluated = evalAtCompileTime(c, result)
  373. if evaluated != nil: return evaluated
  374. proc semGenericStmt(c: PContext, n: PNode): PNode
  375. include hlo, seminst, semcall
  376. proc resetSemFlag(n: PNode) =
  377. if n != nil:
  378. excl n.flags, nfSem
  379. for i in 0..<n.safeLen:
  380. resetSemFlag(n[i])
  381. proc semAfterMacroCall(c: PContext, call, macroResult: PNode,
  382. s: PSym, flags: TExprFlags; expectedType: PType = nil): PNode =
  383. ## Semantically check the output of a macro.
  384. ## This involves processes such as re-checking the macro output for type
  385. ## coherence, making sure that variables declared with 'let' aren't
  386. ## reassigned, and binding the unbound identifiers that the macro output
  387. ## contains.
  388. inc(c.config.evalTemplateCounter)
  389. if c.config.evalTemplateCounter > evalTemplateLimit:
  390. globalError(c.config, s.info, "template instantiation too nested")
  391. c.friendModules.add(s.owner.getModule)
  392. result = macroResult
  393. resetSemFlag result
  394. if s.typ.returnType == nil:
  395. result = semStmt(c, result, flags)
  396. else:
  397. var retType = s.typ.returnType
  398. if retType.kind == tyTypeDesc and tfUnresolved in retType.flags and
  399. retType.hasElementType:
  400. # bug #11941: template fails(T: type X, v: auto): T
  401. # does not mean we expect a tyTypeDesc.
  402. retType = retType.skipModifier
  403. case retType.kind
  404. of tyUntyped, tyAnything:
  405. # Not expecting a type here allows templates like in ``tmodulealias.in``.
  406. result = semExpr(c, result, flags, expectedType)
  407. of tyTyped:
  408. # More restrictive version.
  409. result = semExprWithType(c, result, flags, expectedType)
  410. of tyTypeDesc:
  411. if result.kind == nkStmtList: result.transitionSonsKind(nkStmtListType)
  412. var typ = semTypeNode(c, result, nil)
  413. if typ == nil:
  414. localError(c.config, result.info, "expression has no type: " &
  415. renderTree(result, {renderNoComments}))
  416. result = newSymNode(errorSym(c, result))
  417. else:
  418. result.typ = makeTypeDesc(c, typ)
  419. #result = symNodeFromType(c, typ, n.info)
  420. else:
  421. if s.ast[genericParamsPos] != nil and retType.isMetaType:
  422. # The return type may depend on the Macro arguments
  423. # e.g. template foo(T: typedesc): seq[T]
  424. # We will instantiate the return type here, because
  425. # we now know the supplied arguments
  426. var paramTypes = initTypeMapping()
  427. for param, value in genericParamsInMacroCall(s, call):
  428. var givenType = value.typ
  429. # the sym nodes used for the supplied generic arguments for
  430. # templates and macros leave type nil so regular sem can handle it
  431. # in this case, get the type directly from the sym
  432. if givenType == nil and value.kind == nkSym and value.sym.typ != nil:
  433. givenType = value.sym.typ
  434. idTablePut(paramTypes, param.typ, givenType)
  435. retType = generateTypeInstance(c, paramTypes,
  436. macroResult.info, retType)
  437. if retType.kind == tyVoid:
  438. result = semStmt(c, result, flags)
  439. else:
  440. result = semExpr(c, result, flags, expectedType)
  441. result = fitNode(c, retType, result, result.info)
  442. #globalError(s.info, errInvalidParamKindX, typeToString(s.typ.returnType))
  443. dec(c.config.evalTemplateCounter)
  444. discard c.friendModules.pop()
  445. const
  446. errMissingGenericParamsForTemplate = "'$1' has unspecified generic parameters"
  447. errFloatToString = "cannot convert '$1' to '$2'"
  448. proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym,
  449. flags: TExprFlags = {}; expectedType: PType = nil): PNode =
  450. rememberExpansion(c, nOrig.info, sym)
  451. pushInfoContext(c.config, nOrig.info, sym.detailedInfo)
  452. let info = getCallLineInfo(n)
  453. markUsed(c, info, sym)
  454. onUse(info, sym)
  455. if sym == c.p.owner:
  456. globalError(c.config, info, "recursive dependency: '$1'" % sym.name.s)
  457. let genericParams = sym.ast[genericParamsPos].len
  458. let suppliedParams = max(n.safeLen - 1, 0)
  459. if suppliedParams < genericParams:
  460. globalError(c.config, info, errMissingGenericParamsForTemplate % n.renderTree)
  461. #if c.evalContext == nil:
  462. # c.evalContext = c.createEvalContext(emStatic)
  463. result = evalMacroCall(c.module, c.idgen, c.graph, c.templInstCounter, n, nOrig, sym)
  464. if efNoSemCheck notin flags:
  465. result = semAfterMacroCall(c, n, result, sym, flags, expectedType)
  466. if c.config.macrosToExpand.hasKey(sym.name.s):
  467. message(c.config, nOrig.info, hintExpandMacro, renderTree(result))
  468. result = wrapInComesFrom(nOrig.info, sym, result)
  469. popInfoContext(c.config)
  470. proc forceBool(c: PContext, n: PNode): PNode =
  471. result = fitNode(c, getSysType(c.graph, n.info, tyBool), n, n.info)
  472. if result == nil: result = n
  473. proc semConstBoolExpr(c: PContext, n: PNode): PNode =
  474. result = forceBool(c, semConstExpr(c, n, getSysType(c.graph, n.info, tyBool)))
  475. if result.kind != nkIntLit:
  476. localError(c.config, n.info, errConstExprExpected)
  477. proc semConceptBody(c: PContext, n: PNode): PNode
  478. include semtypes
  479. proc setGenericParamsMisc(c: PContext; n: PNode) =
  480. ## used by call defs (procs, templates, macros, ...) to analyse their generic
  481. ## params, and store the originals in miscPos for better error reporting.
  482. let orig = n[genericParamsPos]
  483. doAssert orig.kind in {nkEmpty, nkGenericParams}
  484. if n[genericParamsPos].kind == nkEmpty:
  485. n[genericParamsPos] = newNodeI(nkGenericParams, n.info)
  486. else:
  487. # we keep the original params around for better error messages, see
  488. # issue https://github.com/nim-lang/Nim/issues/1713
  489. n[genericParamsPos] = semGenericParamList(c, orig)
  490. if n[miscPos].kind == nkEmpty:
  491. n[miscPos] = newTree(nkBracket, c.graph.emptyNode, orig)
  492. else:
  493. n[miscPos][1] = orig
  494. proc caseBranchMatchesExpr(branch, matched: PNode): bool =
  495. result = false
  496. for i in 0 ..< branch.len-1:
  497. if branch[i].kind == nkRange:
  498. if overlap(branch[i], matched): return true
  499. elif exprStructuralEquivalent(branch[i], matched):
  500. return true
  501. proc pickCaseBranchIndex(caseExpr, matched: PNode): int =
  502. result = 0
  503. let endsWithElse = caseExpr[^1].kind == nkElse
  504. for i in 1..<caseExpr.len - endsWithElse.int:
  505. if caseExpr[i].caseBranchMatchesExpr(matched):
  506. return i
  507. if endsWithElse:
  508. return caseExpr.len - 1
  509. proc defaultFieldsForTheUninitialized(c: PContext, recNode: PNode, checkDefault: bool): seq[PNode]
  510. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType, checkDefault: bool): PNode
  511. proc defaultNodeField(c: PContext, a: PNode, checkDefault: bool): PNode
  512. const defaultFieldsSkipTypes = {tyGenericInst, tyAlias, tySink}
  513. proc defaultFieldsForTuple(c: PContext, recNode: PNode, hasDefault: var bool, checkDefault: bool): seq[PNode] =
  514. result = @[]
  515. case recNode.kind
  516. of nkRecList:
  517. for field in recNode:
  518. result.add defaultFieldsForTuple(c, field, hasDefault, checkDefault)
  519. of nkSym:
  520. let field = recNode.sym
  521. let recType = recNode.typ.skipTypes(defaultFieldsSkipTypes)
  522. if field.ast != nil: #Try to use default value
  523. hasDefault = true
  524. result.add newTree(nkExprColonExpr, recNode, field.ast)
  525. else:
  526. if recType.kind in {tyObject, tyArray, tyTuple}:
  527. let asgnExpr = defaultNodeField(c, recNode, recNode.typ, checkDefault)
  528. if asgnExpr != nil:
  529. hasDefault = true
  530. asgnExpr.flags.incl nfSkipFieldChecking
  531. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  532. return
  533. let asgnType = newType(tyTypeDesc, c.idgen, recNode.typ.owner)
  534. rawAddSon(asgnType, recNode.typ)
  535. let asgnExpr = newTree(nkCall,
  536. newSymNode(getSysMagic(c.graph, recNode.info, "zeroDefault", mZeroDefault)),
  537. newNodeIT(nkType, recNode.info, asgnType)
  538. )
  539. asgnExpr.flags.incl nfSkipFieldChecking
  540. asgnExpr.typ = recNode.typ
  541. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  542. else:
  543. raiseAssert "unreachable"
  544. proc defaultFieldsForTheUninitialized(c: PContext, recNode: PNode, checkDefault: bool): seq[PNode] =
  545. result = @[]
  546. case recNode.kind
  547. of nkRecList:
  548. for field in recNode:
  549. result.add defaultFieldsForTheUninitialized(c, field, checkDefault)
  550. of nkRecCase:
  551. let discriminator = recNode[0]
  552. var selectedBranch: int
  553. var defaultValue = discriminator.sym.ast
  554. if defaultValue == nil:
  555. # None of the branches were explicitly selected by the user and no value
  556. # was given to the discrimator. We can assume that it will be initialized
  557. # to zero and this will select a particular branch as a result:
  558. if checkDefault: # don't add defaults when checking whether a case branch has default fields
  559. return
  560. defaultValue = newIntNode(nkIntLit#[c.graph]#, 0)
  561. defaultValue.typ = discriminator.typ
  562. selectedBranch = recNode.pickCaseBranchIndex defaultValue
  563. defaultValue.flags.incl nfSkipFieldChecking
  564. result.add newTree(nkExprColonExpr, discriminator, defaultValue)
  565. result.add defaultFieldsForTheUninitialized(c, recNode[selectedBranch][^1], checkDefault)
  566. of nkSym:
  567. let field = recNode.sym
  568. let recType = recNode.typ.skipTypes(defaultFieldsSkipTypes)
  569. if field.ast != nil: #Try to use default value
  570. result.add newTree(nkExprColonExpr, recNode, field.ast)
  571. elif recType.kind in {tyObject, tyArray, tyTuple}:
  572. let asgnExpr = defaultNodeField(c, recNode, recNode.typ, checkDefault)
  573. if asgnExpr != nil:
  574. asgnExpr.typ = recNode.typ
  575. asgnExpr.flags.incl nfSkipFieldChecking
  576. result.add newTree(nkExprColonExpr, recNode, asgnExpr)
  577. else:
  578. raiseAssert "unreachable"
  579. proc defaultNodeField(c: PContext, a: PNode, aTyp: PType, checkDefault: bool): PNode =
  580. let aTypSkip = aTyp.skipTypes(defaultFieldsSkipTypes)
  581. if aTypSkip.kind == tyObject:
  582. let child = defaultFieldsForTheUninitialized(c, aTypSkip.n, checkDefault)
  583. if child.len > 0:
  584. var asgnExpr = newTree(nkObjConstr, newNodeIT(nkType, a.info, aTyp))
  585. asgnExpr.typ = aTyp
  586. asgnExpr.sons.add child
  587. result = semExpr(c, asgnExpr)
  588. else:
  589. result = nil
  590. elif aTypSkip.kind == tyArray:
  591. let child = defaultNodeField(c, a, aTypSkip[1], checkDefault)
  592. if child != nil:
  593. let node = newNode(nkIntLit)
  594. node.intVal = toInt64(lengthOrd(c.graph.config, aTypSkip))
  595. result = semExpr(c, newTree(nkCall, newSymNode(getSysSym(c.graph, a.info, "arrayWith"), a.info),
  596. semExprWithType(c, child),
  597. node
  598. ))
  599. result.typ = aTyp
  600. else:
  601. result = nil
  602. elif aTypSkip.kind == tyTuple:
  603. var hasDefault = false
  604. if aTypSkip.n != nil:
  605. let children = defaultFieldsForTuple(c, aTypSkip.n, hasDefault, checkDefault)
  606. if hasDefault and children.len > 0:
  607. result = newNodeI(nkTupleConstr, a.info)
  608. result.typ = aTyp
  609. result.sons.add children
  610. result = semExpr(c, result)
  611. else:
  612. result = nil
  613. else:
  614. result = nil
  615. else:
  616. result = nil
  617. proc defaultNodeField(c: PContext, a: PNode, checkDefault: bool): PNode =
  618. result = defaultNodeField(c, a, a.typ, checkDefault)
  619. include semtempl, semgnrc, semstmts, semexprs
  620. proc addCodeForGenerics(c: PContext, n: PNode) =
  621. for i in c.lastGenericIdx..<c.generics.len:
  622. var prc = c.generics[i].inst.sym
  623. if prc.kind in {skProc, skFunc, skMethod, skConverter} and prc.magic == mNone:
  624. if prc.ast == nil or prc.ast[bodyPos] == nil:
  625. internalError(c.config, prc.info, "no code for " & prc.name.s)
  626. else:
  627. n.add prc.ast
  628. c.lastGenericIdx = c.generics.len
  629. proc preparePContext*(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PContext =
  630. result = newContext(graph, module)
  631. result.idgen = idgen
  632. result.enforceVoidContext = newType(tyTyped, idgen, nil)
  633. result.voidType = newType(tyVoid, idgen, nil)
  634. if result.p != nil: internalError(graph.config, module.info, "sem.preparePContext")
  635. result.semConstExpr = semConstExpr
  636. result.semExpr = semExpr
  637. result.semExprWithType = semExprWithType
  638. result.semTryExpr = tryExpr
  639. result.semTryConstExpr = tryConstExpr
  640. result.computeRequiresInit = computeRequiresInit
  641. result.semOperand = semOperand
  642. result.semConstBoolExpr = semConstBoolExpr
  643. result.semOverloadedCall = semOverloadedCall
  644. result.semInferredLambda = semInferredLambda
  645. result.semGenerateInstance = generateInstance
  646. result.semTypeNode = semTypeNode
  647. result.instTypeBoundOp = sigmatch.instTypeBoundOp
  648. result.hasUnresolvedArgs = hasUnresolvedArgs
  649. result.templInstCounter = new int
  650. pushProcCon(result, module)
  651. pushOwner(result, result.module)
  652. result.moduleScope = openScope(result)
  653. result.moduleScope.addSym(module) # a module knows itself
  654. if sfSystemModule in module.flags:
  655. graph.systemModule = module
  656. result.topLevelScope = openScope(result)
  657. proc isImportSystemStmt(g: ModuleGraph; n: PNode): bool =
  658. if g.systemModule == nil: return false
  659. var n = n
  660. if n.kind == nkStmtList:
  661. for i in 0..<n.len-1:
  662. if n[i].kind notin {nkCommentStmt, nkEmpty}:
  663. n = n[i]
  664. break
  665. case n.kind
  666. of nkImportStmt:
  667. result = false
  668. for x in n:
  669. if x.kind == nkIdent:
  670. let f = checkModuleName(g.config, x, false)
  671. if f == g.systemModule.info.fileIndex:
  672. return true
  673. of nkImportExceptStmt, nkFromStmt:
  674. result = false
  675. if n[0].kind == nkIdent:
  676. let f = checkModuleName(g.config, n[0], false)
  677. if f == g.systemModule.info.fileIndex:
  678. return true
  679. else: result = false
  680. proc isEmptyTree(n: PNode): bool =
  681. case n.kind
  682. of nkStmtList:
  683. for it in n:
  684. if not isEmptyTree(it): return false
  685. result = true
  686. of nkEmpty, nkCommentStmt: result = true
  687. else: result = false
  688. proc semStmtAndGenerateGenerics(c: PContext, n: PNode): PNode =
  689. if c.topStmts == 0 and not isImportSystemStmt(c.graph, n):
  690. if sfSystemModule notin c.module.flags and not isEmptyTree(n):
  691. assert c.graph.systemModule != nil
  692. c.moduleScope.addSym c.graph.systemModule # import the "System" identifier
  693. importAllSymbols(c, c.graph.systemModule)
  694. inc c.topStmts
  695. else:
  696. inc c.topStmts
  697. if sfNoForward in c.module.flags:
  698. result = semAllTypeSections(c, n)
  699. else:
  700. result = n
  701. result = semStmt(c, result, {})
  702. when false:
  703. # Code generators are lazy now and can deal with undeclared procs, so these
  704. # steps are not required anymore and actually harmful for the upcoming
  705. # destructor support.
  706. # BUGFIX: process newly generated generics here, not at the end!
  707. if c.lastGenericIdx < c.generics.len:
  708. var a = newNodeI(nkStmtList, n.info)
  709. addCodeForGenerics(c, a)
  710. if a.len > 0:
  711. # a generic has been added to `a`:
  712. if result.kind != nkEmpty: a.add result
  713. result = a
  714. result = hloStmt(c, result)
  715. if c.config.cmd == cmdInteractive and not isEmptyType(result.typ):
  716. result = buildEchoStmt(c, result)
  717. if c.config.cmd == cmdIdeTools:
  718. appendToModule(c.module, result)
  719. trackStmt(c, c.module, result, isTopLevel = true)
  720. if optMultiMethods notin c.config.globalOptions and
  721. c.config.selectedGC in {gcArc, gcOrc, gcAtomicArc} and
  722. Feature.vtables in c.config.features:
  723. sortVTableDispatchers(c.graph)
  724. if sfMainModule in c.module.flags:
  725. collectVTableDispatchers(c.graph)
  726. proc recoverContext(c: PContext) =
  727. # clean up in case of a semantic error: We clean up the stacks, etc. This is
  728. # faster than wrapping every stack operation in a 'try finally' block and
  729. # requires far less code.
  730. c.currentScope = c.topLevelScope
  731. while getCurrOwner(c).kind != skModule: popOwner(c)
  732. while c.p != nil and c.p.owner.kind != skModule: c.p = c.p.next
  733. proc semWithPContext*(c: PContext, n: PNode): PNode =
  734. # no need for an expensive 'try' if we stop after the first error anyway:
  735. if c.config.errorMax <= 1:
  736. result = semStmtAndGenerateGenerics(c, n)
  737. else:
  738. let oldContextLen = msgs.getInfoContextLen(c.config)
  739. let oldInGenericInst = c.inGenericInst
  740. try:
  741. result = semStmtAndGenerateGenerics(c, n)
  742. except ERecoverableError, ESuggestDone:
  743. recoverContext(c)
  744. c.inGenericInst = oldInGenericInst
  745. msgs.setInfoContextLen(c.config, oldContextLen)
  746. if getCurrentException() of ESuggestDone:
  747. c.suggestionsMade = true
  748. result = nil
  749. else:
  750. result = newNodeI(nkEmpty, n.info)
  751. #if c.config.cmd == cmdIdeTools: findSuggest(c, n)
  752. storeRodNode(c, result)
  753. proc reportUnusedModules(c: PContext) =
  754. if c.config.cmd == cmdM: return
  755. for i in 0..high(c.unusedImports):
  756. if sfUsed notin c.unusedImports[i][0].flags:
  757. message(c.config, c.unusedImports[i][1], warnUnusedImportX, c.unusedImports[i][0].name.s)
  758. proc closePContext*(graph: ModuleGraph; c: PContext, n: PNode): PNode =
  759. if c.config.cmd == cmdIdeTools and not c.suggestionsMade:
  760. suggestSentinel(c)
  761. closeScope(c) # close module's scope
  762. rawCloseScope(c) # imported symbols; don't check for unused ones!
  763. reportUnusedModules(c)
  764. result = newNode(nkStmtList)
  765. if n != nil:
  766. internalError(c.config, n.info, "n is not nil") #result := n;
  767. addCodeForGenerics(c, result)
  768. if c.module.ast != nil:
  769. result.add(c.module.ast)
  770. popOwner(c)
  771. popProcCon(c)
  772. sealRodFile(c)