semdata.nim 24 KB

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