semdata.nim 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains the data structures for the semantic checking phase.
  10. import tables
  11. when defined(nimPreviewSlimSystem):
  12. import std/assertions
  13. import
  14. intsets, options, ast, astalgo, msgs, idents, renderer,
  15. magicsys, vmdef, modulegraphs, lineinfos, sets, pathutils
  16. import ic / ic
  17. type
  18. TOptionEntry* = object # entries to put on a stack for pragma parsing
  19. options*: TOptions
  20. defaultCC*: TCallingConvention
  21. dynlib*: PLib
  22. notes*: TNoteKinds
  23. features*: set[Feature]
  24. otherPragmas*: PNode # every pragma can be pushed
  25. warningAsErrors*: TNoteKinds
  26. POptionEntry* = ref TOptionEntry
  27. PProcCon* = ref TProcCon
  28. TProcCon* {.acyclic.} = object # procedure context; also used for top-level
  29. # statements
  30. owner*: PSym # the symbol this context belongs to
  31. resultSym*: PSym # the result symbol (if we are in a proc)
  32. nestedLoopCounter*: int # whether we are in a loop or not
  33. nestedBlockCounter*: int # whether we are in a block or not
  34. breakInLoop*: bool # whether we are in a loop without block
  35. next*: PProcCon # used for stacking procedure contexts
  36. mappingExists*: bool
  37. mapping*: TIdTable
  38. caseContext*: seq[tuple[n: PNode, idx: int]]
  39. localBindStmts*: seq[PNode]
  40. TMatchedConcept* = object
  41. candidateType*: PType
  42. prev*: ptr TMatchedConcept
  43. depth*: int
  44. TInstantiationPair* = object
  45. genericSym*: PSym
  46. inst*: PInstantiation
  47. TExprFlag* = enum
  48. efLValue, efWantIterator, efWantIterable, efInTypeof,
  49. efNeedStatic,
  50. # Use this in contexts where a static value is mandatory
  51. efPreferStatic,
  52. # Use this in contexts where a static value could bring more
  53. # information, but it's not strictly mandatory. This may become
  54. # the default with implicit statics in the future.
  55. efPreferNilResult,
  56. # Use this if you want a certain result (e.g. static value),
  57. # but you don't want to trigger a hard error. For example,
  58. # you may be in position to supply a better error message
  59. # to the user.
  60. efWantStmt, efAllowStmt, efDetermineType, efExplain,
  61. efWantValue, efOperand, efNoSemCheck,
  62. efNoEvaluateGeneric, efInCall, efFromHlo, efNoSem2Check,
  63. efNoUndeclared, efIsDotCall, efCannotBeDotCall,
  64. # Use this if undeclared identifiers should not raise an error during
  65. # overload resolution.
  66. efNoDiagnostics,
  67. efTypeAllowed # typeAllowed will be called after
  68. TExprFlags* = set[TExprFlag]
  69. ImportMode* = enum
  70. importAll, importSet, importExcept
  71. ImportedModule* = object
  72. m*: PSym
  73. case mode*: ImportMode
  74. of importAll: discard
  75. of importSet:
  76. imported*: IntSet # of PIdent.id
  77. of importExcept:
  78. exceptSet*: IntSet # of PIdent.id
  79. PContext* = ref TContext
  80. TContext* = object of TPassContext # a context represents the module
  81. # that is currently being compiled
  82. enforceVoidContext*: PType
  83. # for `if cond: stmt else: foo`, `foo` will be evaluated under
  84. # enforceVoidContext != nil
  85. voidType*: PType # for typeof(stmt)
  86. module*: PSym # the module sym belonging to the context
  87. currentScope*: PScope # current scope
  88. moduleScope*: PScope # scope for modules
  89. imports*: seq[ImportedModule] # scope for all imported symbols
  90. topLevelScope*: PScope # scope for all top-level symbols
  91. p*: PProcCon # procedure context
  92. intTypeCache*: array[-5..32, PType] # cache some common integer types
  93. # to avoid type allocations
  94. nilTypeCache*: PType
  95. matchedConcept*: ptr TMatchedConcept # the current concept being matched
  96. friendModules*: seq[PSym] # friend modules; may access private data;
  97. # this is used so that generic instantiations
  98. # can access private object fields
  99. instCounter*: int # to prevent endless instantiations
  100. templInstCounter*: ref int # gives every template instantiation a unique id
  101. inGenericContext*: int # > 0 if we are in a generic type
  102. inStaticContext*: int # > 0 if we are inside a static: block
  103. inUnrolledContext*: int # > 0 if we are unrolling a loop
  104. compilesContextId*: int # > 0 if we are in a ``compiles`` magic
  105. compilesContextIdGenerator*: int
  106. inGenericInst*: int # > 0 if we are instantiating a generic
  107. converters*: seq[PSym]
  108. patterns*: seq[PSym] # sequence of pattern matchers
  109. optionStack*: seq[POptionEntry]
  110. symMapping*: TIdTable # every gensym'ed symbol needs to be mapped
  111. # to some new symbol in a generic instantiation
  112. libs*: seq[PLib] # all libs used by this module
  113. semConstExpr*: proc (c: PContext, n: PNode; expectedType: PType = nil): PNode {.nimcall.} # for the pragmas
  114. semExpr*: proc (c: PContext, n: PNode, flags: TExprFlags = {}, expectedType: PType = nil): PNode {.nimcall.}
  115. semTryExpr*: proc (c: PContext, n: PNode, flags: TExprFlags = {}): PNode {.nimcall.}
  116. semTryConstExpr*: proc (c: PContext, n: PNode; expectedType: PType = nil): PNode {.nimcall.}
  117. computeRequiresInit*: proc (c: PContext, t: PType): bool {.nimcall.}
  118. hasUnresolvedArgs*: proc (c: PContext, n: PNode): bool
  119. semOperand*: proc (c: PContext, n: PNode, flags: TExprFlags = {}): PNode {.nimcall.}
  120. semConstBoolExpr*: proc (c: PContext, n: PNode): PNode {.nimcall.} # XXX bite the bullet
  121. semOverloadedCall*: proc (c: PContext, n, nOrig: PNode,
  122. filter: TSymKinds, flags: TExprFlags): PNode {.nimcall.}
  123. semTypeNode*: proc(c: PContext, n: PNode, prev: PType): PType {.nimcall.}
  124. semInferredLambda*: proc(c: PContext, pt: TIdTable, n: PNode): PNode
  125. semGenerateInstance*: proc (c: PContext, fn: PSym, pt: TIdTable,
  126. info: TLineInfo): PSym
  127. includedFiles*: IntSet # used to detect recursive include files
  128. pureEnumFields*: TStrTable # pure enum fields that can be used unambiguously
  129. userPragmas*: TStrTable
  130. evalContext*: PEvalContext
  131. unknownIdents*: IntSet # ids of all unknown identifiers to prevent
  132. # naming it multiple times
  133. generics*: seq[TInstantiationPair] # pending list of instantiated generics to compile
  134. topStmts*: int # counts the number of encountered top level statements
  135. lastGenericIdx*: int # used for the generics stack
  136. hloLoopDetector*: int # used to prevent endless loops in the HLO
  137. inParallelStmt*: int
  138. instTypeBoundOp*: proc (c: PContext; dc: PSym; t: PType; info: TLineInfo;
  139. op: TTypeAttachedOp; col: int): PSym {.nimcall.}
  140. cache*: IdentCache
  141. graph*: ModuleGraph
  142. signatures*: TStrTable
  143. recursiveDep*: string
  144. suggestionsMade*: bool
  145. isAmbiguous*: bool # little hack
  146. features*: set[Feature]
  147. inTypeContext*, inConceptDecl*: int
  148. unusedImports*: seq[(PSym, TLineInfo)]
  149. exportIndirections*: HashSet[(int, int)] # (module.id, symbol.id)
  150. importModuleMap*: Table[int, int] # (module.id, module.id)
  151. lastTLineInfo*: TLineInfo
  152. sideEffects*: Table[int, seq[(TLineInfo, PSym)]] # symbol.id index
  153. inUncheckedAssignSection*: int
  154. template config*(c: PContext): ConfigRef = c.graph.config
  155. proc getIntLitType*(c: PContext; literal: PNode): PType =
  156. # we cache some common integer literal types for performance:
  157. let value = literal.intVal
  158. if value >= low(c.intTypeCache) and value <= high(c.intTypeCache):
  159. result = c.intTypeCache[value.int]
  160. if result == nil:
  161. let ti = getSysType(c.graph, literal.info, tyInt)
  162. result = copyType(ti, nextTypeId(c.idgen), ti.owner)
  163. result.n = literal
  164. c.intTypeCache[value.int] = result
  165. else:
  166. let ti = getSysType(c.graph, literal.info, tyInt)
  167. result = copyType(ti, nextTypeId(c.idgen), ti.owner)
  168. result.n = literal
  169. proc setIntLitType*(c: PContext; result: PNode) =
  170. let i = result.intVal
  171. case c.config.target.intSize
  172. of 8: result.typ = getIntLitType(c, result)
  173. of 4:
  174. if i >= low(int32) and i <= high(int32):
  175. result.typ = getIntLitType(c, result)
  176. else:
  177. result.typ = getSysType(c.graph, result.info, tyInt64)
  178. of 2:
  179. if i >= low(int16) and i <= high(int16):
  180. result.typ = getIntLitType(c, result)
  181. elif i >= low(int32) and i <= high(int32):
  182. result.typ = getSysType(c.graph, result.info, tyInt32)
  183. else:
  184. result.typ = getSysType(c.graph, result.info, tyInt64)
  185. of 1:
  186. # 8 bit CPUs are insane ...
  187. if i >= low(int8) and i <= high(int8):
  188. result.typ = getIntLitType(c, result)
  189. elif i >= low(int16) and i <= high(int16):
  190. result.typ = getSysType(c.graph, result.info, tyInt16)
  191. elif i >= low(int32) and i <= high(int32):
  192. result.typ = getSysType(c.graph, result.info, tyInt32)
  193. else:
  194. result.typ = getSysType(c.graph, result.info, tyInt64)
  195. else:
  196. internalError(c.config, result.info, "invalid int size")
  197. proc makeInstPair*(s: PSym, inst: PInstantiation): TInstantiationPair =
  198. result.genericSym = s
  199. result.inst = inst
  200. proc filename*(c: PContext): string =
  201. # the module's filename
  202. return toFilename(c.config, FileIndex c.module.position)
  203. proc scopeDepth*(c: PContext): int {.inline.} =
  204. result = if c.currentScope != nil: c.currentScope.depthLevel
  205. else: 0
  206. proc getCurrOwner*(c: PContext): PSym =
  207. # owner stack (used for initializing the
  208. # owner field of syms)
  209. # the documentation comment always gets
  210. # assigned to the current owner
  211. result = c.graph.owners[^1]
  212. proc pushOwner*(c: PContext; owner: PSym) =
  213. c.graph.owners.add(owner)
  214. proc popOwner*(c: PContext) =
  215. if c.graph.owners.len > 0: setLen(c.graph.owners, c.graph.owners.len - 1)
  216. else: internalError(c.config, "popOwner")
  217. proc lastOptionEntry*(c: PContext): POptionEntry =
  218. result = c.optionStack[^1]
  219. proc popProcCon*(c: PContext) {.inline.} = c.p = c.p.next
  220. proc put*(p: PProcCon; key, val: PSym) =
  221. if not p.mappingExists:
  222. initIdTable(p.mapping)
  223. p.mappingExists = true
  224. #echo "put into table ", key.info
  225. p.mapping.idTablePut(key, val)
  226. proc get*(p: PProcCon; key: PSym): PSym =
  227. if not p.mappingExists: return nil
  228. result = PSym(p.mapping.idTableGet(key))
  229. proc getGenSym*(c: PContext; s: PSym): PSym =
  230. if sfGenSym notin s.flags: return s
  231. var it = c.p
  232. while it != nil:
  233. result = get(it, s)
  234. if result != nil:
  235. #echo "got from table ", result.name.s, " ", result.info
  236. return result
  237. it = it.next
  238. result = s
  239. proc considerGenSyms*(c: PContext; n: PNode) =
  240. if n == nil:
  241. discard "can happen for nkFormalParams/nkArgList"
  242. elif n.kind == nkSym:
  243. let s = getGenSym(c, n.sym)
  244. if n.sym != s:
  245. n.sym = s
  246. else:
  247. for i in 0..<n.safeLen:
  248. considerGenSyms(c, n[i])
  249. proc newOptionEntry*(conf: ConfigRef): POptionEntry =
  250. new(result)
  251. result.options = conf.options
  252. result.defaultCC = ccNimCall
  253. result.dynlib = nil
  254. result.notes = conf.notes
  255. result.warningAsErrors = conf.warningAsErrors
  256. proc pushOptionEntry*(c: PContext): POptionEntry =
  257. new(result)
  258. var prev = c.optionStack[^1]
  259. result.options = c.config.options
  260. result.defaultCC = prev.defaultCC
  261. result.dynlib = prev.dynlib
  262. result.notes = c.config.notes
  263. result.warningAsErrors = c.config.warningAsErrors
  264. result.features = c.features
  265. c.optionStack.add(result)
  266. proc popOptionEntry*(c: PContext) =
  267. c.config.options = c.optionStack[^1].options
  268. c.config.notes = c.optionStack[^1].notes
  269. c.config.warningAsErrors = c.optionStack[^1].warningAsErrors
  270. c.features = c.optionStack[^1].features
  271. c.optionStack.setLen(c.optionStack.len - 1)
  272. proc newContext*(graph: ModuleGraph; module: PSym): PContext =
  273. new(result)
  274. result.optionStack = @[newOptionEntry(graph.config)]
  275. result.libs = @[]
  276. result.module = module
  277. result.friendModules = @[module]
  278. result.converters = @[]
  279. result.patterns = @[]
  280. result.includedFiles = initIntSet()
  281. initStrTable(result.pureEnumFields)
  282. initStrTable(result.userPragmas)
  283. result.generics = @[]
  284. result.unknownIdents = initIntSet()
  285. result.cache = graph.cache
  286. result.graph = graph
  287. initStrTable(result.signatures)
  288. result.features = graph.config.features
  289. if graph.config.symbolFiles != disabledSf:
  290. let id = module.position
  291. assert graph.packed[id].status in {undefined, outdated}
  292. graph.packed[id].status = storing
  293. graph.packed[id].module = module
  294. initEncoder graph, module
  295. template packedRepr*(c): untyped = c.graph.packed[c.module.position].fromDisk
  296. template encoder*(c): untyped = c.graph.encoders[c.module.position]
  297. proc addIncludeFileDep*(c: PContext; f: FileIndex) =
  298. if c.config.symbolFiles != disabledSf:
  299. addIncludeFileDep(c.encoder, c.packedRepr, f)
  300. proc addImportFileDep*(c: PContext; f: FileIndex) =
  301. if c.config.symbolFiles != disabledSf:
  302. addImportFileDep(c.encoder, c.packedRepr, f)
  303. proc addPragmaComputation*(c: PContext; n: PNode) =
  304. if c.config.symbolFiles != disabledSf:
  305. addPragmaComputation(c.encoder, c.packedRepr, n)
  306. proc inclSym(sq: var seq[PSym], s: PSym): bool =
  307. for i in 0..<sq.len:
  308. if sq[i].id == s.id: return false
  309. sq.add s
  310. result = true
  311. proc addConverter*(c: PContext, conv: LazySym) =
  312. assert conv.sym != nil
  313. if inclSym(c.converters, conv.sym):
  314. add(c.graph.ifaces[c.module.position].converters, conv)
  315. proc addConverterDef*(c: PContext, conv: LazySym) =
  316. addConverter(c, conv)
  317. if c.config.symbolFiles != disabledSf:
  318. addConverter(c.encoder, c.packedRepr, conv.sym)
  319. proc addPureEnum*(c: PContext, e: LazySym) =
  320. assert e.sym != nil
  321. add(c.graph.ifaces[c.module.position].pureEnums, e)
  322. if c.config.symbolFiles != disabledSf:
  323. addPureEnum(c.encoder, c.packedRepr, e.sym)
  324. proc addPattern*(c: PContext, p: LazySym) =
  325. assert p.sym != nil
  326. if inclSym(c.patterns, p.sym):
  327. add(c.graph.ifaces[c.module.position].patterns, p)
  328. if c.config.symbolFiles != disabledSf:
  329. addTrmacro(c.encoder, c.packedRepr, p.sym)
  330. proc exportSym*(c: PContext; s: PSym) =
  331. strTableAdds(c.graph, c.module, s)
  332. if c.config.symbolFiles != disabledSf:
  333. addExported(c.encoder, c.packedRepr, s)
  334. proc reexportSym*(c: PContext; s: PSym) =
  335. strTableAdds(c.graph, c.module, s)
  336. if c.config.symbolFiles != disabledSf:
  337. addReexport(c.encoder, c.packedRepr, s)
  338. proc newLib*(kind: TLibKind): PLib =
  339. new(result)
  340. result.kind = kind #initObjectSet(result.syms)
  341. proc addToLib*(lib: PLib, sym: PSym) =
  342. #if sym.annex != nil and not isGenericRoutine(sym):
  343. # LocalError(sym.info, errInvalidPragma)
  344. sym.annex = lib
  345. proc newTypeS*(kind: TTypeKind, c: PContext): PType =
  346. result = newType(kind, nextTypeId(c.idgen), getCurrOwner(c))
  347. proc makePtrType*(owner: PSym, baseType: PType; idgen: IdGenerator): PType =
  348. result = newType(tyPtr, nextTypeId(idgen), owner)
  349. addSonSkipIntLit(result, baseType, idgen)
  350. proc makePtrType*(c: PContext, baseType: PType): PType =
  351. makePtrType(getCurrOwner(c), baseType, c.idgen)
  352. proc makeTypeWithModifier*(c: PContext,
  353. modifier: TTypeKind,
  354. baseType: PType): PType =
  355. assert modifier in {tyVar, tyLent, tyPtr, tyRef, tyStatic, tyTypeDesc}
  356. if modifier in {tyVar, tyLent, tyTypeDesc} and baseType.kind == modifier:
  357. result = baseType
  358. else:
  359. result = newTypeS(modifier, c)
  360. addSonSkipIntLit(result, baseType, c.idgen)
  361. proc makeVarType*(c: PContext, baseType: PType; kind = tyVar): PType =
  362. if baseType.kind == kind:
  363. result = baseType
  364. else:
  365. result = newTypeS(kind, c)
  366. addSonSkipIntLit(result, baseType, c.idgen)
  367. proc makeVarType*(owner: PSym, baseType: PType; idgen: IdGenerator; kind = tyVar): PType =
  368. if baseType.kind == kind:
  369. result = baseType
  370. else:
  371. result = newType(kind, nextTypeId(idgen), owner)
  372. addSonSkipIntLit(result, baseType, idgen)
  373. proc makeTypeSymNode*(c: PContext, typ: PType, info: TLineInfo): PNode =
  374. let typedesc = newTypeS(tyTypeDesc, c)
  375. incl typedesc.flags, tfCheckedForDestructor
  376. internalAssert(c.config, typ != nil)
  377. typedesc.addSonSkipIntLit(typ, c.idgen)
  378. let sym = newSym(skType, c.cache.idAnon, nextSymId(c.idgen), getCurrOwner(c), info,
  379. c.config.options).linkTo(typedesc)
  380. result = newSymNode(sym, info)
  381. proc makeTypeFromExpr*(c: PContext, n: PNode): PType =
  382. result = newTypeS(tyFromExpr, c)
  383. assert n != nil
  384. result.n = n
  385. proc newTypeWithSons*(owner: PSym, kind: TTypeKind, sons: seq[PType];
  386. idgen: IdGenerator): PType =
  387. result = newType(kind, nextTypeId(idgen), owner)
  388. result.sons = sons
  389. proc newTypeWithSons*(c: PContext, kind: TTypeKind,
  390. sons: seq[PType]): PType =
  391. result = newType(kind, nextTypeId(c.idgen), getCurrOwner(c))
  392. result.sons = sons
  393. proc makeStaticExpr*(c: PContext, n: PNode): PNode =
  394. result = newNodeI(nkStaticExpr, n.info)
  395. result.sons = @[n]
  396. result.typ = if n.typ != nil and n.typ.kind == tyStatic: n.typ
  397. else: newTypeWithSons(c, tyStatic, @[n.typ])
  398. proc makeAndType*(c: PContext, t1, t2: PType): PType =
  399. result = newTypeS(tyAnd, c)
  400. result.sons = @[t1, t2]
  401. propagateToOwner(result, t1)
  402. propagateToOwner(result, t2)
  403. result.flags.incl((t1.flags + t2.flags) * {tfHasStatic})
  404. result.flags.incl tfHasMeta
  405. proc makeOrType*(c: PContext, t1, t2: PType): PType =
  406. result = newTypeS(tyOr, c)
  407. if t1.kind != tyOr and t2.kind != tyOr:
  408. result.sons = @[t1, t2]
  409. else:
  410. template addOr(t1) =
  411. if t1.kind == tyOr:
  412. for x in t1.sons: result.rawAddSon x
  413. else:
  414. result.rawAddSon t1
  415. addOr(t1)
  416. addOr(t2)
  417. propagateToOwner(result, t1)
  418. propagateToOwner(result, t2)
  419. result.flags.incl((t1.flags + t2.flags) * {tfHasStatic})
  420. result.flags.incl tfHasMeta
  421. proc makeNotType*(c: PContext, t1: PType): PType =
  422. result = newTypeS(tyNot, c)
  423. result.sons = @[t1]
  424. propagateToOwner(result, t1)
  425. result.flags.incl(t1.flags * {tfHasStatic})
  426. result.flags.incl tfHasMeta
  427. proc nMinusOne(c: PContext; n: PNode): PNode =
  428. result = newTreeI(nkCall, n.info, newSymNode(getSysMagic(c.graph, n.info, "pred", mPred)), n)
  429. # Remember to fix the procs below this one when you make changes!
  430. proc makeRangeWithStaticExpr*(c: PContext, n: PNode): PType =
  431. let intType = getSysType(c.graph, n.info, tyInt)
  432. result = newTypeS(tyRange, c)
  433. result.sons = @[intType]
  434. if n.typ != nil and n.typ.n == nil:
  435. result.flags.incl tfUnresolved
  436. result.n = newTreeI(nkRange, n.info, newIntTypeNode(0, intType),
  437. makeStaticExpr(c, nMinusOne(c, n)))
  438. template rangeHasUnresolvedStatic*(t: PType): bool =
  439. tfUnresolved in t.flags
  440. proc errorType*(c: PContext): PType =
  441. ## creates a type representing an error state
  442. result = newTypeS(tyError, c)
  443. result.flags.incl tfCheckedForDestructor
  444. proc errorNode*(c: PContext, n: PNode): PNode =
  445. result = newNodeI(nkEmpty, n.info)
  446. result.typ = errorType(c)
  447. # These mimic localError
  448. template localErrorNode*(c: PContext, n: PNode, info: TLineInfo, msg: TMsgKind, arg: string): PNode =
  449. liMessage(c.config, info, msg, arg, doNothing, instLoc())
  450. errorNode(c, n)
  451. template localErrorNode*(c: PContext, n: PNode, info: TLineInfo, arg: string): PNode =
  452. liMessage(c.config, info, errGenerated, arg, doNothing, instLoc())
  453. errorNode(c, n)
  454. template localErrorNode*(c: PContext, n: PNode, msg: TMsgKind, arg: string): PNode =
  455. let n2 = n
  456. liMessage(c.config, n2.info, msg, arg, doNothing, instLoc())
  457. errorNode(c, n2)
  458. template localErrorNode*(c: PContext, n: PNode, arg: string): PNode =
  459. let n2 = n
  460. liMessage(c.config, n2.info, errGenerated, arg, doNothing, instLoc())
  461. errorNode(c, n2)
  462. proc fillTypeS*(dest: PType, kind: TTypeKind, c: PContext) =
  463. dest.kind = kind
  464. dest.owner = getCurrOwner(c)
  465. dest.size = - 1
  466. proc makeRangeType*(c: PContext; first, last: BiggestInt;
  467. info: TLineInfo; intType: PType = nil): PType =
  468. let intType = if intType != nil: intType else: getSysType(c.graph, info, tyInt)
  469. var n = newNodeI(nkRange, info)
  470. n.add newIntTypeNode(first, intType)
  471. n.add newIntTypeNode(last, intType)
  472. result = newTypeS(tyRange, c)
  473. result.n = n
  474. addSonSkipIntLit(result, intType, c.idgen) # basetype of range
  475. proc markIndirect*(c: PContext, s: PSym) {.inline.} =
  476. if s.kind in {skProc, skFunc, skConverter, skMethod, skIterator}:
  477. incl(s.flags, sfAddrTaken)
  478. # XXX add to 'c' for global analysis
  479. proc illFormedAst*(n: PNode; conf: ConfigRef) =
  480. globalError(conf, n.info, errIllFormedAstX, renderTree(n, {renderNoComments}))
  481. proc illFormedAstLocal*(n: PNode; conf: ConfigRef) =
  482. localError(conf, n.info, errIllFormedAstX, renderTree(n, {renderNoComments}))
  483. proc checkSonsLen*(n: PNode, length: int; conf: ConfigRef) =
  484. if n.len != length: illFormedAst(n, conf)
  485. proc checkMinSonsLen*(n: PNode, length: int; conf: ConfigRef) =
  486. if n.len < length: illFormedAst(n, conf)
  487. proc isTopLevel*(c: PContext): bool {.inline.} =
  488. result = c.currentScope.depthLevel <= 2
  489. proc isTopLevelInsideDeclaration*(c: PContext, sym: PSym): bool {.inline.} =
  490. # for routeKinds the scope isn't closed yet:
  491. c.currentScope.depthLevel <= 2 + ord(sym.kind in routineKinds)
  492. proc pushCaseContext*(c: PContext, caseNode: PNode) =
  493. c.p.caseContext.add((caseNode, 0))
  494. proc popCaseContext*(c: PContext) =
  495. discard pop(c.p.caseContext)
  496. proc setCaseContextIdx*(c: PContext, idx: int) =
  497. c.p.caseContext[^1].idx = idx
  498. template addExport*(c: PContext; s: PSym) =
  499. ## convenience to export a symbol from the current module
  500. addExport(c.graph, c.module, s)
  501. proc storeRodNode*(c: PContext, n: PNode) =
  502. if c.config.symbolFiles != disabledSf:
  503. toPackedNodeTopLevel(n, c.encoder, c.packedRepr)
  504. proc addToGenericProcCache*(c: PContext; s: PSym; inst: PInstantiation) =
  505. c.graph.procInstCache.mgetOrPut(s.itemId, @[]).add LazyInstantiation(module: c.module.position, inst: inst)
  506. if c.config.symbolFiles != disabledSf:
  507. storeInstantiation(c.encoder, c.packedRepr, s, inst)
  508. proc addToGenericCache*(c: PContext; s: PSym; inst: PType) =
  509. c.graph.typeInstCache.mgetOrPut(s.itemId, @[]).add LazyType(typ: inst)
  510. if c.config.symbolFiles != disabledSf:
  511. storeTypeInst(c.encoder, c.packedRepr, s, inst)
  512. proc sealRodFile*(c: PContext) =
  513. if c.config.symbolFiles != disabledSf:
  514. if c.graph.vm != nil:
  515. for (m, n) in PCtx(c.graph.vm).vmstateDiff:
  516. if m == c.module:
  517. addPragmaComputation(c, n)
  518. c.idgen.sealed = true # no further additions are allowed
  519. proc rememberExpansion*(c: PContext; info: TLineInfo; expandedSym: PSym) =
  520. ## Templates and macros are very special in Nim; these have
  521. ## inlining semantics so after semantic checking they leave no trace
  522. ## in the sem'checked AST. This is very bad for IDE-like tooling
  523. ## ("find all usages of this template" would not work). We need special
  524. ## logic to remember macro/template expansions. This is done here and
  525. ## delegated to the "rod" file mechanism.
  526. if c.config.symbolFiles != disabledSf:
  527. storeExpansion(c.encoder, c.packedRepr, info, expandedSym)