semdata.nim 22 KB

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