ast.nim 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # abstract syntax tree + symbol table
  10. import
  11. lineinfos, options, ropes, idents, int128, wordrecg
  12. import std/[tables, hashes]
  13. from std/strutils import toLowerAscii
  14. when defined(nimPreviewSlimSystem):
  15. import std/assertions
  16. export int128
  17. import nodekinds
  18. export nodekinds
  19. type
  20. TCallingConvention* = enum
  21. ccNimCall = "nimcall" # nimcall, also the default
  22. ccStdCall = "stdcall" # procedure is stdcall
  23. ccCDecl = "cdecl" # cdecl
  24. ccSafeCall = "safecall" # safecall
  25. ccSysCall = "syscall" # system call
  26. ccInline = "inline" # proc should be inlined
  27. ccNoInline = "noinline" # proc should not be inlined
  28. ccFastCall = "fastcall" # fastcall (pass parameters in registers)
  29. ccThisCall = "thiscall" # thiscall (parameters are pushed right-to-left)
  30. ccClosure = "closure" # proc has a closure
  31. ccNoConvention = "noconv" # needed for generating proper C procs sometimes
  32. ccMember = "member" # proc is a (cpp) member
  33. TNodeKinds* = set[TNodeKind]
  34. type
  35. TSymFlag* = enum # 63 flags!
  36. sfUsed, # read access of sym (for warnings) or simply used
  37. sfExported, # symbol is exported from module
  38. sfFromGeneric, # symbol is instantiation of a generic; this is needed
  39. # for symbol file generation; such symbols should always
  40. # be written into the ROD file
  41. sfGlobal, # symbol is at global scope
  42. sfForward, # symbol is forward declared
  43. sfWasForwarded, # symbol had a forward declaration
  44. # (implies it's too dangerous to patch its type signature)
  45. sfImportc, # symbol is external; imported
  46. sfExportc, # symbol is exported (under a specified name)
  47. sfMangleCpp, # mangle as cpp (combines with `sfExportc`)
  48. sfVolatile, # variable is volatile
  49. sfRegister, # variable should be placed in a register
  50. sfPure, # object is "pure" that means it has no type-information
  51. # enum is "pure", its values need qualified access
  52. # variable is "pure"; it's an explicit "global"
  53. sfNoSideEffect, # proc has no side effects
  54. sfSideEffect, # proc may have side effects; cannot prove it has none
  55. sfMainModule, # module is the main module
  56. sfSystemModule, # module is the system module
  57. sfNoReturn, # proc never returns (an exit proc)
  58. sfAddrTaken, # the variable's address is taken (ex- or implicitly);
  59. # *OR*: a proc is indirectly called (used as first class)
  60. sfCompilerProc, # proc is a compiler proc, that is a C proc that is
  61. # needed for the code generator
  62. sfEscapes # param escapes
  63. # currently unimplemented
  64. sfDiscriminant, # field is a discriminant in a record/object
  65. sfRequiresInit, # field must be initialized during construction
  66. sfDeprecated, # symbol is deprecated
  67. sfExplain, # provide more diagnostics when this symbol is used
  68. sfError, # usage of symbol should trigger a compile-time error
  69. sfShadowed, # a symbol that was shadowed in some inner scope
  70. sfThread, # proc will run as a thread
  71. # variable is a thread variable
  72. sfCppNonPod, # tells compiler to treat such types as non-pod's, so that
  73. # `thread_local` is used instead of `__thread` for
  74. # {.threadvar.} + `--threads`. Only makes sense for importcpp types.
  75. # This has a performance impact so isn't set by default.
  76. sfCompileTime, # proc can be evaluated at compile time
  77. sfConstructor, # proc is a C++ constructor
  78. sfDispatcher, # copied method symbol is the dispatcher
  79. # deprecated and unused, except for the con
  80. sfBorrow, # proc is borrowed
  81. sfInfixCall, # symbol needs infix call syntax in target language;
  82. # for interfacing with C++, JS
  83. sfNamedParamCall, # symbol needs named parameter call syntax in target
  84. # language; for interfacing with Objective C
  85. sfDiscardable, # returned value may be discarded implicitly
  86. sfOverridden, # proc is overridden
  87. sfCallsite # A flag for template symbols to tell the
  88. # compiler it should use line information from
  89. # the calling side of the macro, not from the
  90. # implementation.
  91. sfGenSym # symbol is 'gensym'ed; do not add to symbol table
  92. sfNonReloadable # symbol will be left as-is when hot code reloading is on -
  93. # meaning that it won't be renamed and/or changed in any way
  94. sfGeneratedOp # proc is a generated '='; do not inject destructors in it
  95. # variable is generated closure environment; requires early
  96. # destruction for --newruntime.
  97. sfTemplateParam # symbol is a template parameter
  98. sfCursor # variable/field is a cursor, see RFC 177 for details
  99. sfInjectDestructors # whether the proc needs the 'injectdestructors' transformation
  100. sfNeverRaises # proc can never raise an exception, not even OverflowDefect
  101. # or out-of-memory
  102. sfSystemRaisesDefect # proc in the system can raise defects
  103. sfUsedInFinallyOrExcept # symbol is used inside an 'except' or 'finally'
  104. sfSingleUsedTemp # For temporaries that we know will only be used once
  105. sfNoalias # 'noalias' annotation, means C's 'restrict'
  106. # for templates and macros, means cannot be called
  107. # as a lone symbol (cannot use alias syntax)
  108. sfEffectsDelayed # an 'effectsDelayed' parameter
  109. sfGeneratedType # A anonymous generic type that is generated by the compiler for
  110. # objects that do not have generic parameters in case one of the
  111. # object fields has one.
  112. #
  113. # This is disallowed but can cause the typechecking to go into
  114. # an infinite loop, this flag is used as a sentinel to stop it.
  115. sfVirtual # proc is a C++ virtual function
  116. sfByCopy # param is marked as pass bycopy
  117. sfMember # proc is a C++ member of a type
  118. sfCodegenDecl # type, proc, global or proc param is marked as codegenDecl
  119. sfWasGenSym # symbol was 'gensym'ed
  120. sfForceLift # variable has to be lifted into closure environment
  121. sfDirty # template is not hygienic (old styled template) module,
  122. # compiled from a dirty-buffer
  123. sfCustomPragma # symbol is custom pragma template
  124. sfBase, # a base method
  125. sfGoto # var is used for 'goto' code generation
  126. sfAnon, # symbol name that was generated by the compiler
  127. # the compiler will avoid printing such names
  128. # in user messages.
  129. sfAllUntyped # macro or template is immediately expanded in a generic context
  130. sfTemplateRedefinition # symbol is a redefinition of an earlier template
  131. TSymFlags* = set[TSymFlag]
  132. const
  133. sfNoInit* = sfMainModule # don't generate code to init the variable
  134. sfNoForward* = sfRegister
  135. # forward declarations are not required (per module)
  136. sfReorder* = sfForward
  137. # reordering pass is enabled
  138. sfCompileToCpp* = sfInfixCall # compile the module as C++ code
  139. sfCompileToObjc* = sfNamedParamCall # compile the module as Objective-C code
  140. sfExperimental* = sfOverridden # module uses the .experimental switch
  141. sfWrittenTo* = sfBorrow # param is assigned to
  142. # currently unimplemented
  143. sfCppMember* = { sfVirtual, sfMember, sfConstructor } # proc is a C++ member, meaning it will be attached to the type definition
  144. const
  145. # getting ready for the future expr/stmt merge
  146. nkWhen* = nkWhenStmt
  147. nkWhenExpr* = nkWhenStmt
  148. nkEffectList* = nkArgList
  149. # hacks ahead: an nkEffectList is a node with 4 children:
  150. exceptionEffects* = 0 # exceptions at position 0
  151. requiresEffects* = 1 # 'requires' annotation
  152. ensuresEffects* = 2 # 'ensures' annotation
  153. tagEffects* = 3 # user defined tag ('gc', 'time' etc.)
  154. pragmasEffects* = 4 # not an effect, but a slot for pragmas in proc type
  155. forbiddenEffects* = 5 # list of illegal effects
  156. effectListLen* = 6 # list of effects list
  157. nkLastBlockStmts* = {nkRaiseStmt, nkReturnStmt, nkBreakStmt, nkContinueStmt}
  158. # these must be last statements in a block
  159. type
  160. TTypeKind* = enum # order is important!
  161. # Don't forget to change hti.nim if you make a change here
  162. # XXX put this into an include file to avoid this issue!
  163. # several types are no longer used (guess which), but a
  164. # spot in the sequence is kept for backwards compatibility
  165. # (apparently something with bootstrapping)
  166. # if you need to add a type, they can apparently be reused
  167. tyNone, tyBool, tyChar,
  168. tyEmpty, tyAlias, tyNil, tyUntyped, tyTyped, tyTypeDesc,
  169. tyGenericInvocation, # ``T[a, b]`` for types to invoke
  170. tyGenericBody, # ``T[a, b, body]`` last parameter is the body
  171. tyGenericInst, # ``T[a, b, realInstance]`` instantiated generic type
  172. # realInstance will be a concrete type like tyObject
  173. # unless this is an instance of a generic alias type.
  174. # then realInstance will be the tyGenericInst of the
  175. # completely (recursively) resolved alias.
  176. tyGenericParam, # ``a`` in the above patterns
  177. tyDistinct,
  178. tyEnum,
  179. tyOrdinal, # integer types (including enums and boolean)
  180. tyArray,
  181. tyObject,
  182. tyTuple,
  183. tySet,
  184. tyRange,
  185. tyPtr, tyRef,
  186. tyVar,
  187. tySequence,
  188. tyProc,
  189. tyPointer, tyOpenArray,
  190. tyString, tyCstring, tyForward,
  191. tyInt, tyInt8, tyInt16, tyInt32, tyInt64, # signed integers
  192. tyFloat, tyFloat32, tyFloat64, tyFloat128,
  193. tyUInt, tyUInt8, tyUInt16, tyUInt32, tyUInt64,
  194. tyOwned, tySink, tyLent,
  195. tyVarargs,
  196. tyUncheckedArray
  197. # An array with boundaries [0,+∞]
  198. tyError # used as erroneous type (for idetools)
  199. # as an erroneous node should match everything
  200. tyBuiltInTypeClass
  201. # Type such as the catch-all object, tuple, seq, etc
  202. tyUserTypeClass
  203. # the body of a user-defined type class
  204. tyUserTypeClassInst
  205. # Instance of a parametric user-defined type class.
  206. # Structured similarly to tyGenericInst.
  207. # tyGenericInst represents concrete types, while
  208. # this is still a "generic param" that will bind types
  209. # and resolves them during sigmatch and instantiation.
  210. tyCompositeTypeClass
  211. # Type such as seq[Number]
  212. # The notes for tyUserTypeClassInst apply here as well
  213. # sons[0]: the original expression used by the user.
  214. # sons[1]: fully expanded and instantiated meta type
  215. # (potentially following aliases)
  216. tyInferred
  217. # In the initial state `base` stores a type class constraining
  218. # the types that can be inferred. After a candidate type is
  219. # selected, it's stored in `last`. Between `base` and `last`
  220. # there may be 0, 2 or more types that were also considered as
  221. # possible candidates in the inference process (i.e. last will
  222. # be updated to store a type best conforming to all candidates)
  223. tyAnd, tyOr, tyNot
  224. # boolean type classes such as `string|int`,`not seq`,
  225. # `Sortable and Enumable`, etc
  226. tyAnything
  227. # a type class matching any type
  228. tyStatic
  229. # a value known at compile type (the underlying type is .base)
  230. tyFromExpr
  231. # This is a type representing an expression that depends
  232. # on generic parameters (the expression is stored in t.n)
  233. # It will be converted to a real type only during generic
  234. # instantiation and prior to this it has the potential to
  235. # be any type.
  236. tyConcept
  237. # new style concept.
  238. tyVoid
  239. # now different from tyEmpty, hurray!
  240. tyIterable
  241. static:
  242. # remind us when TTypeKind stops to fit in a single 64-bit word
  243. # assert TTypeKind.high.ord <= 63
  244. discard
  245. const
  246. tyPureObject* = tyTuple
  247. GcTypeKinds* = {tyRef, tySequence, tyString}
  248. tyTypeClasses* = {tyBuiltInTypeClass, tyCompositeTypeClass,
  249. tyUserTypeClass, tyUserTypeClassInst, tyConcept,
  250. tyAnd, tyOr, tyNot, tyAnything}
  251. tyMetaTypes* = {tyGenericParam, tyTypeDesc, tyUntyped} + tyTypeClasses
  252. tyUserTypeClasses* = {tyUserTypeClass, tyUserTypeClassInst}
  253. # consider renaming as `tyAbstractVarRange`
  254. abstractVarRange* = {tyGenericInst, tyRange, tyVar, tyDistinct, tyOrdinal,
  255. tyTypeDesc, tyAlias, tyInferred, tySink, tyOwned}
  256. abstractInst* = {tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias,
  257. tyInferred, tySink, tyOwned} # xxx what about tyStatic?
  258. type
  259. TTypeKinds* = set[TTypeKind]
  260. TNodeFlag* = enum
  261. nfNone,
  262. nfBase2, # nfBase10 is default, so not needed
  263. nfBase8,
  264. nfBase16,
  265. nfAllConst, # used to mark complex expressions constant; easy to get rid of
  266. # but unfortunately it has measurable impact for compilation
  267. # efficiency
  268. nfTransf, # node has been transformed
  269. nfNoRewrite # node should not be transformed anymore
  270. nfSem # node has been checked for semantics
  271. nfLL # node has gone through lambda lifting
  272. nfDotField # the call can use a dot operator
  273. nfDotSetter # the call can use a setter dot operarator
  274. nfExplicitCall # x.y() was used instead of x.y
  275. nfExprCall # this is an attempt to call a regular expression
  276. nfIsRef # this node is a 'ref' node; used for the VM
  277. nfIsPtr # this node is a 'ptr' node; used for the VM
  278. nfPreventCg # this node should be ignored by the codegen
  279. nfBlockArg # this a stmtlist appearing in a call (e.g. a do block)
  280. nfFromTemplate # a top-level node returned from a template
  281. nfDefaultParam # an automatically inserter default parameter
  282. nfDefaultRefsParam # a default param value references another parameter
  283. # the flag is applied to proc default values and to calls
  284. nfExecuteOnReload # A top-level statement that will be executed during reloads
  285. nfLastRead # this node is a last read
  286. nfFirstWrite # this node is a first write
  287. nfHasComment # node has a comment
  288. nfSkipFieldChecking # node skips field visable checking
  289. nfDisabledOpenSym # temporary: node should be nkOpenSym but cannot
  290. # because openSym experimental switch is disabled
  291. # gives warning instead
  292. TNodeFlags* = set[TNodeFlag]
  293. TTypeFlag* = enum # keep below 32 for efficiency reasons (now: 47)
  294. tfVarargs, # procedure has C styled varargs
  295. # tyArray type represeting a varargs list
  296. tfNoSideEffect, # procedure type does not allow side effects
  297. tfFinal, # is the object final?
  298. tfInheritable, # is the object inheritable?
  299. tfHasOwned, # type contains an 'owned' type and must be moved
  300. tfEnumHasHoles, # enum cannot be mapped into a range
  301. tfShallow, # type can be shallow copied on assignment
  302. tfThread, # proc type is marked as ``thread``; alias for ``gcsafe``
  303. tfFromGeneric, # type is an instantiation of a generic; this is needed
  304. # because for instantiations of objects, structural
  305. # type equality has to be used
  306. tfUnresolved, # marks unresolved typedesc/static params: e.g.
  307. # proc foo(T: typedesc, list: seq[T]): var T
  308. # proc foo(L: static[int]): array[L, int]
  309. # can be attached to ranges to indicate that the range
  310. # can be attached to generic procs with free standing
  311. # type parameters: e.g. proc foo[T]()
  312. # depends on unresolved static params.
  313. tfResolved # marks a user type class, after it has been bound to a
  314. # concrete type (lastSon becomes the concrete type)
  315. tfRetType, # marks return types in proc (used to detect type classes
  316. # used as return types for return type inference)
  317. tfCapturesEnv, # whether proc really captures some environment
  318. tfByCopy, # pass object/tuple by copy (C backend)
  319. tfByRef, # pass object/tuple by reference (C backend)
  320. tfIterator, # type is really an iterator, not a tyProc
  321. tfPartial, # type is declared as 'partial'
  322. tfNotNil, # type cannot be 'nil'
  323. tfRequiresInit, # type contains a "not nil" constraint somewhere or
  324. # a `requiresInit` field, so the default zero init
  325. # is not appropriate
  326. tfNeedsFullInit, # object type marked with {.requiresInit.}
  327. # all fields must be initialized
  328. tfVarIsPtr, # 'var' type is translated like 'ptr' even in C++ mode
  329. tfHasMeta, # type contains "wildcard" sub-types such as generic params
  330. # or other type classes
  331. tfHasGCedMem, # type contains GC'ed memory
  332. tfPacked
  333. tfHasStatic
  334. tfGenericTypeParam
  335. tfImplicitTypeParam
  336. tfInferrableStatic
  337. tfConceptMatchedTypeSym
  338. tfExplicit # for typedescs, marks types explicitly prefixed with the
  339. # `type` operator (e.g. type int)
  340. tfWildcard # consider a proc like foo[T, I](x: Type[T, I])
  341. # T and I here can bind to both typedesc and static types
  342. # before this is determined, we'll consider them to be a
  343. # wildcard type.
  344. tfHasAsgn # type has overloaded assignment operator
  345. tfBorrowDot # distinct type borrows '.'
  346. tfTriggersCompileTime # uses the NimNode type which make the proc
  347. # implicitly '.compiletime'
  348. tfRefsAnonObj # used for 'ref object' and 'ptr object'
  349. tfCovariant # covariant generic param mimicking a ptr type
  350. tfWeakCovariant # covariant generic param mimicking a seq/array type
  351. tfContravariant # contravariant generic param
  352. tfCheckedForDestructor # type was checked for having a destructor.
  353. # If it has one, t.destructor is not nil.
  354. tfAcyclic # object type was annotated as .acyclic
  355. tfIncompleteStruct # treat this type as if it had sizeof(pointer)
  356. tfCompleteStruct
  357. # (for importc types); type is fully specified, allowing to compute
  358. # sizeof, alignof, offsetof at CT
  359. tfExplicitCallConv
  360. tfIsConstructor
  361. tfEffectSystemWorkaround
  362. tfIsOutParam
  363. tfSendable
  364. tfImplicitStatic
  365. TTypeFlags* = set[TTypeFlag]
  366. TSymKind* = enum # the different symbols (start with the prefix sk);
  367. # order is important for the documentation generator!
  368. skUnknown, # unknown symbol: used for parsing assembler blocks
  369. # and first phase symbol lookup in generics
  370. skConditional, # symbol for the preprocessor (may become obsolete)
  371. skDynLib, # symbol represents a dynamic library; this is used
  372. # internally; it does not exist in Nim code
  373. skParam, # a parameter
  374. skGenericParam, # a generic parameter; eq in ``proc x[eq=`==`]()``
  375. skTemp, # a temporary variable (introduced by compiler)
  376. skModule, # module identifier
  377. skType, # a type
  378. skVar, # a variable
  379. skLet, # a 'let' symbol
  380. skConst, # a constant
  381. skResult, # special 'result' variable
  382. skProc, # a proc
  383. skFunc, # a func
  384. skMethod, # a method
  385. skIterator, # an iterator
  386. skConverter, # a type converter
  387. skMacro, # a macro
  388. skTemplate, # a template; currently also misused for user-defined
  389. # pragmas
  390. skField, # a field in a record or object
  391. skEnumField, # an identifier in an enum
  392. skForVar, # a for loop variable
  393. skLabel, # a label (for block statement)
  394. skStub, # symbol is a stub and not yet loaded from the ROD
  395. # file (it is loaded on demand, which may
  396. # mean: never)
  397. skPackage, # symbol is a package (used for canonicalization)
  398. TSymKinds* = set[TSymKind]
  399. const
  400. routineKinds* = {skProc, skFunc, skMethod, skIterator,
  401. skConverter, skMacro, skTemplate}
  402. ExportableSymKinds* = {skVar, skLet, skConst, skType, skEnumField, skStub} + routineKinds
  403. tfUnion* = tfNoSideEffect
  404. tfGcSafe* = tfThread
  405. tfObjHasKids* = tfEnumHasHoles
  406. tfReturnsNew* = tfInheritable
  407. tfNonConstExpr* = tfExplicitCallConv
  408. ## tyFromExpr where the expression shouldn't be evaluated as a static value
  409. tfGenericHasDestructor* = tfExplicitCallConv
  410. ## tyGenericBody where an instance has a generated destructor
  411. skError* = skUnknown
  412. var
  413. eqTypeFlags* = {tfIterator, tfNotNil, tfVarIsPtr, tfGcSafe, tfNoSideEffect, tfIsOutParam}
  414. ## type flags that are essential for type equality.
  415. ## This is now a variable because for emulation of version:1.0 we
  416. ## might exclude {tfGcSafe, tfNoSideEffect}.
  417. type
  418. TMagic* = enum # symbols that require compiler magic:
  419. mNone,
  420. mDefined, mDeclared, mDeclaredInScope, mCompiles, mArrGet, mArrPut, mAsgn,
  421. mLow, mHigh, mSizeOf, mAlignOf, mOffsetOf, mTypeTrait,
  422. mIs, mOf, mAddr, mType, mTypeOf,
  423. mPlugin, mEcho, mShallowCopy, mSlurp, mStaticExec, mStatic,
  424. mParseExprToAst, mParseStmtToAst, mExpandToAst, mQuoteAst,
  425. mInc, mDec, mOrd,
  426. mNew, mNewFinalize, mNewSeq, mNewSeqOfCap,
  427. mLengthOpenArray, mLengthStr, mLengthArray, mLengthSeq,
  428. mIncl, mExcl, mCard, mChr,
  429. mGCref, mGCunref,
  430. mAddI, mSubI, mMulI, mDivI, mModI,
  431. mSucc, mPred,
  432. mAddF64, mSubF64, mMulF64, mDivF64,
  433. mShrI, mShlI, mAshrI, mBitandI, mBitorI, mBitxorI,
  434. mMinI, mMaxI,
  435. mAddU, mSubU, mMulU, mDivU, mModU,
  436. mEqI, mLeI, mLtI,
  437. mEqF64, mLeF64, mLtF64,
  438. mLeU, mLtU,
  439. mEqEnum, mLeEnum, mLtEnum,
  440. mEqCh, mLeCh, mLtCh,
  441. mEqB, mLeB, mLtB,
  442. mEqRef, mLePtr, mLtPtr,
  443. mXor, mEqCString, mEqProc,
  444. mUnaryMinusI, mUnaryMinusI64, mAbsI, mNot,
  445. mUnaryPlusI, mBitnotI,
  446. mUnaryPlusF64, mUnaryMinusF64,
  447. mCharToStr, mBoolToStr,
  448. mCStrToStr,
  449. mStrToStr, mEnumToStr,
  450. mAnd, mOr,
  451. mImplies, mIff, mExists, mForall, mOld,
  452. mEqStr, mLeStr, mLtStr,
  453. mEqSet, mLeSet, mLtSet, mMulSet, mPlusSet, mMinusSet, mXorSet,
  454. mConStrStr, mSlice,
  455. mDotDot, # this one is only necessary to give nice compile time warnings
  456. mFields, mFieldPairs, mOmpParFor,
  457. mAppendStrCh, mAppendStrStr, mAppendSeqElem,
  458. mInSet, mRepr, mExit,
  459. mSetLengthStr, mSetLengthSeq,
  460. mIsPartOf, mAstToStr, mParallel,
  461. mSwap, mIsNil, mArrToSeq, mOpenArrayToSeq,
  462. mNewString, mNewStringOfCap, mParseBiggestFloat,
  463. mMove, mEnsureMove, mWasMoved, mDup, mDestroy, mTrace,
  464. mDefault, mUnown, mFinished, mIsolate, mAccessEnv, mAccessTypeField,
  465. mArray, mOpenArray, mRange, mSet, mSeq, mVarargs,
  466. mRef, mPtr, mVar, mDistinct, mVoid, mTuple,
  467. mOrdinal, mIterableType,
  468. mInt, mInt8, mInt16, mInt32, mInt64,
  469. mUInt, mUInt8, mUInt16, mUInt32, mUInt64,
  470. mFloat, mFloat32, mFloat64, mFloat128,
  471. mBool, mChar, mString, mCstring,
  472. mPointer, mNil, mExpr, mStmt, mTypeDesc,
  473. mVoidType, mPNimrodNode, mSpawn, mDeepCopy,
  474. mIsMainModule, mCompileDate, mCompileTime, mProcCall,
  475. mCpuEndian, mHostOS, mHostCPU, mBuildOS, mBuildCPU, mAppType,
  476. mCompileOption, mCompileOptionArg,
  477. mNLen, mNChild, mNSetChild, mNAdd, mNAddMultiple, mNDel,
  478. mNKind, mNSymKind,
  479. mNccValue, mNccInc, mNcsAdd, mNcsIncl, mNcsLen, mNcsAt,
  480. mNctPut, mNctLen, mNctGet, mNctHasNext, mNctNext,
  481. mNIntVal, mNFloatVal, mNSymbol, mNIdent, mNGetType, mNStrVal, mNSetIntVal,
  482. mNSetFloatVal, mNSetSymbol, mNSetIdent, mNSetStrVal, mNLineInfo,
  483. mNNewNimNode, mNCopyNimNode, mNCopyNimTree, mStrToIdent, mNSigHash, mNSizeOf,
  484. mNBindSym, mNCallSite,
  485. mEqIdent, mEqNimrodNode, mSameNodeType, mGetImpl, mNGenSym,
  486. mNHint, mNWarning, mNError,
  487. mInstantiationInfo, mGetTypeInfo, mGetTypeInfoV2,
  488. mNimvm, mIntDefine, mStrDefine, mBoolDefine, mGenericDefine, mRunnableExamples,
  489. mException, mBuiltinType, mSymOwner, mUncheckedArray, mGetImplTransf,
  490. mSymIsInstantiationOf, mNodeId, mPrivateAccess, mZeroDefault
  491. const
  492. # things that we can evaluate safely at compile time, even if not asked for it:
  493. ctfeWhitelist* = {mNone, mSucc,
  494. mPred, mInc, mDec, mOrd, mLengthOpenArray,
  495. mLengthStr, mLengthArray, mLengthSeq,
  496. mArrGet, mArrPut, mAsgn, mDestroy,
  497. mIncl, mExcl, mCard, mChr,
  498. mAddI, mSubI, mMulI, mDivI, mModI,
  499. mAddF64, mSubF64, mMulF64, mDivF64,
  500. mShrI, mShlI, mBitandI, mBitorI, mBitxorI,
  501. mMinI, mMaxI,
  502. mAddU, mSubU, mMulU, mDivU, mModU,
  503. mEqI, mLeI, mLtI,
  504. mEqF64, mLeF64, mLtF64,
  505. mLeU, mLtU,
  506. mEqEnum, mLeEnum, mLtEnum,
  507. mEqCh, mLeCh, mLtCh,
  508. mEqB, mLeB, mLtB,
  509. mEqRef, mEqProc, mLePtr, mLtPtr, mEqCString, mXor,
  510. mUnaryMinusI, mUnaryMinusI64, mAbsI, mNot, mUnaryPlusI, mBitnotI,
  511. mUnaryPlusF64, mUnaryMinusF64,
  512. mCharToStr, mBoolToStr,
  513. mCStrToStr,
  514. mStrToStr, mEnumToStr,
  515. mAnd, mOr,
  516. mEqStr, mLeStr, mLtStr,
  517. mEqSet, mLeSet, mLtSet, mMulSet, mPlusSet, mMinusSet, mXorSet,
  518. mConStrStr, mAppendStrCh, mAppendStrStr, mAppendSeqElem,
  519. mInSet, mRepr, mOpenArrayToSeq}
  520. generatedMagics* = {mNone, mIsolate, mFinished, mOpenArrayToSeq}
  521. ## magics that are generated as normal procs in the backend
  522. type
  523. ItemId* = object
  524. module*: int32
  525. item*: int32
  526. proc `$`*(x: ItemId): string =
  527. "(module: " & $x.module & ", item: " & $x.item & ")"
  528. proc `==`*(a, b: ItemId): bool {.inline.} =
  529. a.item == b.item and a.module == b.module
  530. proc hash*(x: ItemId): Hash =
  531. var h: Hash = hash(x.module)
  532. h = h !& hash(x.item)
  533. result = !$h
  534. type
  535. PNode* = ref TNode
  536. TNodeSeq* = seq[PNode]
  537. PType* = ref TType
  538. PSym* = ref TSym
  539. TNode*{.final, acyclic.} = object # on a 32bit machine, this takes 32 bytes
  540. when defined(useNodeIds):
  541. id*: int
  542. typField: PType
  543. info*: TLineInfo
  544. flags*: TNodeFlags
  545. case kind*: TNodeKind
  546. of nkCharLit..nkUInt64Lit:
  547. intVal*: BiggestInt
  548. of nkFloatLit..nkFloat128Lit:
  549. floatVal*: BiggestFloat
  550. of nkStrLit..nkTripleStrLit:
  551. strVal*: string
  552. of nkSym:
  553. sym*: PSym
  554. of nkIdent:
  555. ident*: PIdent
  556. else:
  557. sons*: TNodeSeq
  558. when defined(nimsuggest):
  559. endInfo*: TLineInfo
  560. TStrTable* = object # a table[PIdent] of PSym
  561. counter*: int
  562. data*: seq[PSym]
  563. # -------------- backend information -------------------------------
  564. TLocKind* = enum
  565. locNone, # no location
  566. locTemp, # temporary location
  567. locLocalVar, # location is a local variable
  568. locGlobalVar, # location is a global variable
  569. locParam, # location is a parameter
  570. locField, # location is a record field
  571. locExpr, # "location" is really an expression
  572. locProc, # location is a proc (an address of a procedure)
  573. locData, # location is a constant
  574. locCall, # location is a call expression
  575. locOther # location is something other
  576. TLocFlag* = enum
  577. lfIndirect, # backend introduced a pointer
  578. lfNoDeepCopy, # no need for a deep copy
  579. lfNoDecl, # do not declare it in C
  580. lfDynamicLib, # link symbol to dynamic library
  581. lfExportLib, # export symbol for dynamic library generation
  582. lfHeader, # include header file for symbol
  583. lfImportCompilerProc, # ``importc`` of a compilerproc
  584. lfSingleUse # no location yet and will only be used once
  585. lfEnforceDeref # a copyMem is required to dereference if this a
  586. # ptr array due to C array limitations.
  587. # See #1181, #6422, #11171
  588. lfPrepareForMutation # string location is about to be mutated (V2)
  589. TStorageLoc* = enum
  590. OnUnknown, # location is unknown (stack, heap or static)
  591. OnStatic, # in a static section
  592. OnStack, # location is on hardware stack
  593. OnHeap # location is on heap or global
  594. # (reference counting needed)
  595. TLocFlags* = set[TLocFlag]
  596. TLoc* = object
  597. k*: TLocKind # kind of location
  598. storage*: TStorageLoc
  599. flags*: TLocFlags # location's flags
  600. lode*: PNode # Node where the location came from; can be faked
  601. snippet*: Rope # C code snippet of location (code generators)
  602. # ---------------- end of backend information ------------------------------
  603. TLibKind* = enum
  604. libHeader, libDynamic
  605. TLib* = object # also misused for headers!
  606. # keep in sync with PackedLib
  607. kind*: TLibKind
  608. generated*: bool # needed for the backends:
  609. isOverridden*: bool
  610. name*: Rope
  611. path*: PNode # can be a string literal!
  612. CompilesId* = int ## id that is used for the caching logic within
  613. ## ``system.compiles``. See the seminst module.
  614. TInstantiation* = object
  615. sym*: PSym
  616. concreteTypes*: seq[PType]
  617. compilesId*: CompilesId
  618. PInstantiation* = ref TInstantiation
  619. TScope* {.acyclic.} = object
  620. depthLevel*: int
  621. symbols*: TStrTable
  622. parent*: PScope
  623. allowPrivateAccess*: seq[PSym] # # enable access to private fields
  624. PScope* = ref TScope
  625. PLib* = ref TLib
  626. TSym* {.acyclic.} = object # Keep in sync with PackedSym
  627. itemId*: ItemId
  628. # proc and type instantiations are cached in the generic symbol
  629. case kind*: TSymKind
  630. of routineKinds:
  631. #procInstCache*: seq[PInstantiation]
  632. gcUnsafetyReason*: PSym # for better error messages regarding gcsafe
  633. transformedBody*: PNode # cached body after transf pass
  634. of skLet, skVar, skField, skForVar:
  635. guard*: PSym
  636. bitsize*: int
  637. alignment*: int # for alignment
  638. else: nil
  639. magic*: TMagic
  640. typ*: PType
  641. name*: PIdent
  642. info*: TLineInfo
  643. when defined(nimsuggest):
  644. endInfo*: TLineInfo
  645. hasUserSpecifiedType*: bool # used for determining whether to display inlay type hints
  646. ownerField: PSym
  647. flags*: TSymFlags
  648. ast*: PNode # syntax tree of proc, iterator, etc.:
  649. # the whole proc including header; this is used
  650. # for easy generation of proper error messages
  651. # for variant record fields the discriminant
  652. # expression
  653. # for modules, it's a placeholder for compiler
  654. # generated code that will be appended to the
  655. # module after the sem pass (see appendToModule)
  656. options*: TOptions
  657. position*: int # used for many different things:
  658. # for enum fields its position;
  659. # for fields its offset
  660. # for parameters its position (starting with 0)
  661. # for a conditional:
  662. # 1 iff the symbol is defined, else 0
  663. # (or not in symbol table)
  664. # for modules, an unique index corresponding
  665. # to the module's fileIdx
  666. # for variables a slot index for the evaluator
  667. offset*: int32 # offset of record field
  668. disamb*: int32 # disambiguation number; the basic idea is that
  669. # `<procname>__<module>_<disamb>` is unique
  670. loc*: TLoc
  671. annex*: PLib # additional fields (seldom used, so we use a
  672. # reference to another object to save space)
  673. when hasFFI:
  674. cname*: string # resolved C declaration name in importc decl, e.g.:
  675. # proc fun() {.importc: "$1aux".} => cname = funaux
  676. constraint*: PNode # additional constraints like 'lit|result'; also
  677. # misused for the codegenDecl and virtual pragmas in the hope
  678. # it won't cause problems
  679. # for skModule the string literal to output for
  680. # deprecated modules.
  681. instantiatedFrom*: PSym # for instances, the generic symbol where it came from.
  682. when defined(nimsuggest):
  683. allUsages*: seq[TLineInfo]
  684. TTypeSeq* = seq[PType]
  685. TTypeAttachedOp* = enum ## as usual, order is important here
  686. attachedWasMoved,
  687. attachedDestructor,
  688. attachedAsgn,
  689. attachedDup,
  690. attachedSink,
  691. attachedTrace,
  692. attachedDeepCopy
  693. TType* {.acyclic.} = object # \
  694. # types are identical iff they have the
  695. # same id; there may be multiple copies of a type
  696. # in memory!
  697. # Keep in sync with PackedType
  698. itemId*: ItemId
  699. kind*: TTypeKind # kind of type
  700. callConv*: TCallingConvention # for procs
  701. flags*: TTypeFlags # flags of the type
  702. sons: TTypeSeq # base types, etc.
  703. n*: PNode # node for types:
  704. # for range types a nkRange node
  705. # for record types a nkRecord node
  706. # for enum types a list of symbols
  707. # if kind == tyInt: it is an 'int literal(x)' type
  708. # for procs and tyGenericBody, it's the
  709. # formal param list
  710. # for concepts, the concept body
  711. # else: unused
  712. ownerField: PSym # the 'owner' of the type
  713. sym*: PSym # types have the sym associated with them
  714. # it is used for converting types to strings
  715. size*: BiggestInt # the size of the type in bytes
  716. # -1 means that the size is unkwown
  717. align*: int16 # the type's alignment requirements
  718. paddingAtEnd*: int16 #
  719. loc*: TLoc
  720. typeInst*: PType # for generic instantiations the tyGenericInst that led to this
  721. # type.
  722. uniqueId*: ItemId # due to a design mistake, we need to keep the real ID here as it
  723. # is required by the --incremental:on mode.
  724. TPair* = object
  725. key*, val*: RootRef
  726. TPairSeq* = seq[TPair]
  727. TNodePair* = object
  728. h*: Hash # because it is expensive to compute!
  729. key*: PNode
  730. val*: int
  731. TNodePairSeq* = seq[TNodePair]
  732. TNodeTable* = object # the same as table[PNode] of int;
  733. # nodes are compared by structure!
  734. counter*: int
  735. data*: TNodePairSeq
  736. TObjectSeq* = seq[RootRef]
  737. TObjectSet* = object
  738. counter*: int
  739. data*: TObjectSeq
  740. TImplication* = enum
  741. impUnknown, impNo, impYes
  742. template nodeId(n: PNode): int = cast[int](n)
  743. template typ*(n: PNode): PType =
  744. n.typField
  745. proc owner*(s: PSym|PType): PSym {.inline.} =
  746. result = s.ownerField
  747. proc setOwner*(s: PSym|PType, owner: PSym) {.inline.} =
  748. s.ownerField = owner
  749. type Gconfig = object
  750. # we put comments in a side channel to avoid increasing `sizeof(TNode)`, which
  751. # reduces memory usage given that `PNode` is the most allocated type by far.
  752. comments: Table[int, string] # nodeId => comment
  753. useIc*: bool
  754. var gconfig {.threadvar.}: Gconfig
  755. proc setUseIc*(useIc: bool) = gconfig.useIc = useIc
  756. proc comment*(n: PNode): string =
  757. if nfHasComment in n.flags and not gconfig.useIc:
  758. # IC doesn't track comments, see `packed_ast`, so this could fail
  759. result = gconfig.comments[n.nodeId]
  760. else:
  761. result = ""
  762. proc `comment=`*(n: PNode, a: string) =
  763. let id = n.nodeId
  764. if a.len > 0:
  765. # if needed, we could periodically cleanup gconfig.comments when its size increases,
  766. # to ensure only live nodes (and with nfHasComment) have an entry in gconfig.comments;
  767. # for compiling compiler, the waste is very small:
  768. # num calls to newNodeImpl: 14984160 (num of PNode allocations)
  769. # size of gconfig.comments: 33585
  770. # num of nodes with comments that were deleted and hence wasted: 3081
  771. n.flags.incl nfHasComment
  772. gconfig.comments[id] = a
  773. elif nfHasComment in n.flags:
  774. n.flags.excl nfHasComment
  775. gconfig.comments.del(id)
  776. # BUGFIX: a module is overloadable so that a proc can have the
  777. # same name as an imported module. This is necessary because of
  778. # the poor naming choices in the standard library.
  779. const
  780. OverloadableSyms* = {skProc, skFunc, skMethod, skIterator,
  781. skConverter, skModule, skTemplate, skMacro, skEnumField}
  782. GenericTypes*: TTypeKinds = {tyGenericInvocation, tyGenericBody,
  783. tyGenericParam}
  784. StructuralEquivTypes*: TTypeKinds = {tyNil, tyTuple, tyArray,
  785. tySet, tyRange, tyPtr, tyRef, tyVar, tyLent, tySequence, tyProc, tyOpenArray,
  786. tyVarargs}
  787. ConcreteTypes*: TTypeKinds = { # types of the expr that may occur in::
  788. # var x = expr
  789. tyBool, tyChar, tyEnum, tyArray, tyObject,
  790. tySet, tyTuple, tyRange, tyPtr, tyRef, tyVar, tyLent, tySequence, tyProc,
  791. tyPointer,
  792. tyOpenArray, tyString, tyCstring, tyInt..tyInt64, tyFloat..tyFloat128,
  793. tyUInt..tyUInt64}
  794. IntegralTypes* = {tyBool, tyChar, tyEnum, tyInt..tyInt64,
  795. tyFloat..tyFloat128, tyUInt..tyUInt64} # weird name because it contains tyFloat
  796. ConstantDataTypes*: TTypeKinds = {tyArray, tySet,
  797. tyTuple, tySequence}
  798. NilableTypes*: TTypeKinds = {tyPointer, tyCstring, tyRef, tyPtr,
  799. tyProc, tyError} # TODO
  800. PtrLikeKinds*: TTypeKinds = {tyPointer, tyPtr} # for VM
  801. PersistentNodeFlags*: TNodeFlags = {nfBase2, nfBase8, nfBase16,
  802. nfDotSetter, nfDotField,
  803. nfIsRef, nfIsPtr, nfPreventCg, nfLL,
  804. nfFromTemplate, nfDefaultRefsParam,
  805. nfExecuteOnReload, nfLastRead,
  806. nfFirstWrite, nfSkipFieldChecking,
  807. nfDisabledOpenSym}
  808. namePos* = 0
  809. patternPos* = 1 # empty except for term rewriting macros
  810. genericParamsPos* = 2
  811. paramsPos* = 3
  812. pragmasPos* = 4
  813. miscPos* = 5 # used for undocumented and hacky stuff
  814. bodyPos* = 6 # position of body; use rodread.getBody() instead!
  815. resultPos* = 7
  816. dispatcherPos* = 8
  817. nfAllFieldsSet* = nfBase2
  818. nkIdentKinds* = {nkIdent, nkSym, nkAccQuoted, nkOpenSymChoice,
  819. nkClosedSymChoice, nkOpenSym}
  820. nkPragmaCallKinds* = {nkExprColonExpr, nkCall, nkCallStrLit}
  821. nkLiterals* = {nkCharLit..nkTripleStrLit}
  822. nkFloatLiterals* = {nkFloatLit..nkFloat128Lit}
  823. nkLambdaKinds* = {nkLambda, nkDo}
  824. declarativeDefs* = {nkProcDef, nkFuncDef, nkMethodDef, nkIteratorDef, nkConverterDef}
  825. routineDefs* = declarativeDefs + {nkMacroDef, nkTemplateDef}
  826. procDefs* = nkLambdaKinds + declarativeDefs
  827. callableDefs* = nkLambdaKinds + routineDefs
  828. nkSymChoices* = {nkClosedSymChoice, nkOpenSymChoice}
  829. nkStrKinds* = {nkStrLit..nkTripleStrLit}
  830. skLocalVars* = {skVar, skLet, skForVar, skParam, skResult}
  831. skProcKinds* = {skProc, skFunc, skTemplate, skMacro, skIterator,
  832. skMethod, skConverter}
  833. defaultSize = -1
  834. defaultAlignment = -1
  835. defaultOffset* = -1
  836. proc getPIdent*(a: PNode): PIdent {.inline.} =
  837. ## Returns underlying `PIdent` for `{nkSym, nkIdent}`, or `nil`.
  838. case a.kind
  839. of nkSym: a.sym.name
  840. of nkIdent: a.ident
  841. of nkOpenSymChoice, nkClosedSymChoice, nkOpenSym: a.sons[0].sym.name
  842. else: nil
  843. const
  844. moduleShift = when defined(cpu32): 20 else: 24
  845. template id*(a: PType | PSym): int =
  846. let x = a
  847. (x.itemId.module.int shl moduleShift) + x.itemId.item.int
  848. type
  849. IdGenerator* = ref object # unfortunately, we really need the 'shared mutable' aspect here.
  850. module*: int32
  851. symId*: int32
  852. typeId*: int32
  853. sealed*: bool
  854. disambTable*: CountTable[PIdent]
  855. const
  856. PackageModuleId* = -3'i32
  857. proc idGeneratorFromModule*(m: PSym): IdGenerator =
  858. assert m.kind == skModule
  859. result = IdGenerator(module: m.itemId.module, symId: m.itemId.item, typeId: 0, disambTable: initCountTable[PIdent]())
  860. proc idGeneratorForPackage*(nextIdWillBe: int32): IdGenerator =
  861. result = IdGenerator(module: PackageModuleId, symId: nextIdWillBe - 1'i32, typeId: 0, disambTable: initCountTable[PIdent]())
  862. proc nextSymId(x: IdGenerator): ItemId {.inline.} =
  863. assert(not x.sealed)
  864. inc x.symId
  865. result = ItemId(module: x.module, item: x.symId)
  866. proc nextTypeId*(x: IdGenerator): ItemId {.inline.} =
  867. assert(not x.sealed)
  868. inc x.typeId
  869. result = ItemId(module: x.module, item: x.typeId)
  870. when false:
  871. proc nextId*(x: IdGenerator): ItemId {.inline.} =
  872. inc x.item
  873. result = x[]
  874. when false:
  875. proc storeBack*(dest: var IdGenerator; src: IdGenerator) {.inline.} =
  876. assert dest.ItemId.module == src.ItemId.module
  877. if dest.ItemId.item > src.ItemId.item:
  878. echo dest.ItemId.item, " ", src.ItemId.item, " ", src.ItemId.module
  879. assert dest.ItemId.item <= src.ItemId.item
  880. dest = src
  881. var ggDebug* {.deprecated.}: bool ## convenience switch for trying out things
  882. proc isCallExpr*(n: PNode): bool =
  883. result = n.kind in nkCallKinds
  884. proc discardSons*(father: PNode)
  885. proc len*(n: PNode): int {.inline.} =
  886. result = n.sons.len
  887. proc safeLen*(n: PNode): int {.inline.} =
  888. ## works even for leaves.
  889. if n.kind in {nkNone..nkNilLit}: result = 0
  890. else: result = n.len
  891. proc safeArrLen*(n: PNode): int {.inline.} =
  892. ## works for array-like objects (strings passed as openArray in VM).
  893. if n.kind in {nkStrLit..nkTripleStrLit}: result = n.strVal.len
  894. elif n.kind in {nkNone..nkFloat128Lit}: result = 0
  895. else: result = n.len
  896. proc add*(father, son: PNode) =
  897. assert son != nil
  898. father.sons.add(son)
  899. proc addAllowNil*(father, son: PNode) {.inline.} =
  900. father.sons.add(son)
  901. template `[]`*(n: PNode, i: int): PNode = n.sons[i]
  902. template `[]=`*(n: PNode, i: int; x: PNode) = n.sons[i] = x
  903. template `[]`*(n: PNode, i: BackwardsIndex): PNode = n[n.len - i.int]
  904. template `[]=`*(n: PNode, i: BackwardsIndex; x: PNode) = n[n.len - i.int] = x
  905. proc add*(father, son: PType) =
  906. assert son != nil
  907. father.sons.add(son)
  908. proc addAllowNil*(father, son: PType) {.inline.} =
  909. father.sons.add(son)
  910. template `[]`*(n: PType, i: int): PType = n.sons[i]
  911. template `[]=`*(n: PType, i: int; x: PType) = n.sons[i] = x
  912. template `[]`*(n: PType, i: BackwardsIndex): PType = n[n.len - i.int]
  913. template `[]=`*(n: PType, i: BackwardsIndex; x: PType) = n[n.len - i.int] = x
  914. proc getDeclPragma*(n: PNode): PNode =
  915. ## return the `nkPragma` node for declaration `n`, or `nil` if no pragma was found.
  916. ## Currently only supports routineDefs + {nkTypeDef}.
  917. case n.kind
  918. of routineDefs:
  919. if n[pragmasPos].kind != nkEmpty: result = n[pragmasPos]
  920. else: result = nil
  921. of nkTypeDef:
  922. #[
  923. type F3*{.deprecated: "x3".} = int
  924. TypeSection
  925. TypeDef
  926. PragmaExpr
  927. Postfix
  928. Ident "*"
  929. Ident "F3"
  930. Pragma
  931. ExprColonExpr
  932. Ident "deprecated"
  933. StrLit "x3"
  934. Empty
  935. Ident "int"
  936. ]#
  937. if n[0].kind == nkPragmaExpr:
  938. result = n[0][1]
  939. else:
  940. result = nil
  941. else:
  942. # support as needed for `nkIdentDefs` etc.
  943. result = nil
  944. if result != nil:
  945. assert result.kind == nkPragma, $(result.kind, n.kind)
  946. proc extractPragma*(s: PSym): PNode =
  947. ## gets the pragma node of routine/type/var/let/const symbol `s`
  948. if s.kind in routineKinds: # bug #24167
  949. if s.ast[pragmasPos] != nil and s.ast[pragmasPos].kind != nkEmpty:
  950. result = s.ast[pragmasPos]
  951. else:
  952. result = nil
  953. elif s.kind in {skType, skVar, skLet, skConst}:
  954. if s.ast != nil and s.ast.len > 0:
  955. if s.ast[0].kind == nkPragmaExpr and s.ast[0].len > 1:
  956. # s.ast = nkTypedef / nkPragmaExpr / [nkSym, nkPragma]
  957. result = s.ast[0][1]
  958. else:
  959. result = nil
  960. else:
  961. result = nil
  962. else:
  963. result = nil
  964. assert result == nil or result.kind == nkPragma
  965. proc skipPragmaExpr*(n: PNode): PNode =
  966. ## if pragma expr, give the node the pragmas are applied to,
  967. ## otherwise give node itself
  968. if n.kind == nkPragmaExpr:
  969. result = n[0]
  970. else:
  971. result = n
  972. proc setInfoRecursive*(n: PNode, info: TLineInfo) =
  973. ## set line info recursively
  974. if n != nil:
  975. for i in 0..<n.safeLen: setInfoRecursive(n[i], info)
  976. n.info = info
  977. when defined(useNodeIds):
  978. const nodeIdToDebug* = -1 # 2322968
  979. var gNodeId: int
  980. template newNodeImpl(info2) =
  981. result = PNode(kind: kind, info: info2)
  982. when false:
  983. # this would add overhead, so we skip it; it results in a small amount of leaked entries
  984. # for old PNode that gets re-allocated at the same address as a PNode that
  985. # has `nfHasComment` set (and an entry in that table). Only `nfHasComment`
  986. # should be used to test whether a PNode has a comment; gconfig.comments
  987. # can contain extra entries for deleted PNode's with comments.
  988. gconfig.comments.del(cast[int](result))
  989. template setIdMaybe() =
  990. when defined(useNodeIds):
  991. result.id = gNodeId
  992. if result.id == nodeIdToDebug:
  993. echo "KIND ", result.kind
  994. writeStackTrace()
  995. inc gNodeId
  996. proc newNode*(kind: TNodeKind): PNode =
  997. ## new node with unknown line info, no type, and no children
  998. newNodeImpl(unknownLineInfo)
  999. setIdMaybe()
  1000. proc newNodeI*(kind: TNodeKind, info: TLineInfo): PNode =
  1001. ## new node with line info, no type, and no children
  1002. newNodeImpl(info)
  1003. setIdMaybe()
  1004. proc newNodeI*(kind: TNodeKind, info: TLineInfo, children: int): PNode =
  1005. ## new node with line info, type, and children
  1006. newNodeImpl(info)
  1007. if children > 0:
  1008. newSeq(result.sons, children)
  1009. setIdMaybe()
  1010. proc newNodeIT*(kind: TNodeKind, info: TLineInfo, typ: PType): PNode =
  1011. ## new node with line info, type, and no children
  1012. result = newNode(kind)
  1013. result.info = info
  1014. result.typ() = typ
  1015. proc newNode*(kind: TNodeKind, info: TLineInfo): PNode =
  1016. ## new node with line info, no type, and no children
  1017. newNodeImpl(info)
  1018. setIdMaybe()
  1019. proc newAtom*(ident: PIdent, info: TLineInfo): PNode =
  1020. result = newNode(nkIdent, info)
  1021. result.ident = ident
  1022. proc newAtom*(kind: TNodeKind, intVal: BiggestInt, info: TLineInfo): PNode =
  1023. result = newNode(kind, info)
  1024. result.intVal = intVal
  1025. proc newAtom*(kind: TNodeKind, floatVal: BiggestFloat, info: TLineInfo): PNode =
  1026. result = newNode(kind, info)
  1027. result.floatVal = floatVal
  1028. proc newAtom*(kind: TNodeKind; strVal: sink string; info: TLineInfo): PNode =
  1029. result = newNode(kind, info)
  1030. result.strVal = strVal
  1031. proc newTree*(kind: TNodeKind; info: TLineInfo; children: varargs[PNode]): PNode =
  1032. result = newNodeI(kind, info)
  1033. if children.len > 0:
  1034. result.info = children[0].info
  1035. result.sons = @children
  1036. proc newTree*(kind: TNodeKind; children: varargs[PNode]): PNode =
  1037. result = newNode(kind)
  1038. if children.len > 0:
  1039. result.info = children[0].info
  1040. result.sons = @children
  1041. proc newTreeI*(kind: TNodeKind; info: TLineInfo; children: varargs[PNode]): PNode =
  1042. result = newNodeI(kind, info)
  1043. if children.len > 0:
  1044. result.info = children[0].info
  1045. result.sons = @children
  1046. proc newTreeIT*(kind: TNodeKind; info: TLineInfo; typ: PType; children: varargs[PNode]): PNode =
  1047. result = newNodeIT(kind, info, typ)
  1048. if children.len > 0:
  1049. result.info = children[0].info
  1050. result.sons = @children
  1051. template previouslyInferred*(t: PType): PType =
  1052. if t.sons.len > 1: t.last else: nil
  1053. when false:
  1054. import tables, strutils
  1055. var x: CountTable[string]
  1056. addQuitProc proc () {.noconv.} =
  1057. for k, v in pairs(x):
  1058. echo k
  1059. echo v
  1060. proc newSym*(symKind: TSymKind, name: PIdent, idgen: IdGenerator; owner: PSym,
  1061. info: TLineInfo; options: TOptions = {}): PSym =
  1062. # generates a symbol and initializes the hash field too
  1063. assert not name.isNil
  1064. let id = nextSymId idgen
  1065. result = PSym(name: name, kind: symKind, flags: {}, info: info, itemId: id,
  1066. options: options, ownerField: owner, offset: defaultOffset,
  1067. disamb: getOrDefault(idgen.disambTable, name).int32)
  1068. idgen.disambTable.inc name
  1069. when false:
  1070. if id.module == 48 and id.item == 39:
  1071. writeStackTrace()
  1072. echo "kind ", symKind, " ", name.s
  1073. if owner != nil: echo owner.name.s
  1074. proc astdef*(s: PSym): PNode =
  1075. # get only the definition (initializer) portion of the ast
  1076. if s.ast != nil and s.ast.kind in {nkIdentDefs, nkConstDef}:
  1077. s.ast[2]
  1078. else:
  1079. s.ast
  1080. proc isMetaType*(t: PType): bool =
  1081. return t.kind in tyMetaTypes or
  1082. (t.kind == tyStatic and t.n == nil) or
  1083. tfHasMeta in t.flags
  1084. proc isUnresolvedStatic*(t: PType): bool =
  1085. return t.kind == tyStatic and t.n == nil
  1086. proc linkTo*(t: PType, s: PSym): PType {.discardable.} =
  1087. t.sym = s
  1088. s.typ = t
  1089. result = t
  1090. proc linkTo*(s: PSym, t: PType): PSym {.discardable.} =
  1091. t.sym = s
  1092. s.typ = t
  1093. result = s
  1094. template fileIdx*(c: PSym): FileIndex =
  1095. # XXX: this should be used only on module symbols
  1096. c.position.FileIndex
  1097. template filename*(c: PSym): string =
  1098. # XXX: this should be used only on module symbols
  1099. c.position.FileIndex.toFilename
  1100. proc appendToModule*(m: PSym, n: PNode) =
  1101. ## The compiler will use this internally to add nodes that will be
  1102. ## appended to the module after the sem pass
  1103. if m.ast == nil:
  1104. m.ast = newNode(nkStmtList)
  1105. m.ast.sons = @[n]
  1106. else:
  1107. assert m.ast.kind == nkStmtList
  1108. m.ast.sons.add(n)
  1109. const # for all kind of hash tables:
  1110. GrowthFactor* = 2 # must be power of 2, > 0
  1111. StartSize* = 8 # must be power of 2, > 0
  1112. proc copyStrTable*(dest: var TStrTable, src: TStrTable) =
  1113. dest.counter = src.counter
  1114. setLen(dest.data, src.data.len)
  1115. for i in 0..high(src.data): dest.data[i] = src.data[i]
  1116. proc copyObjectSet*(dest: var TObjectSet, src: TObjectSet) =
  1117. dest.counter = src.counter
  1118. setLen(dest.data, src.data.len)
  1119. for i in 0..high(src.data): dest.data[i] = src.data[i]
  1120. proc discardSons*(father: PNode) =
  1121. father.sons = @[]
  1122. proc withInfo*(n: PNode, info: TLineInfo): PNode =
  1123. n.info = info
  1124. return n
  1125. proc newIdentNode*(ident: PIdent, info: TLineInfo): PNode =
  1126. result = newNode(nkIdent)
  1127. result.ident = ident
  1128. result.info = info
  1129. proc newSymNode*(sym: PSym): PNode =
  1130. result = newNode(nkSym)
  1131. result.sym = sym
  1132. result.typ() = sym.typ
  1133. result.info = sym.info
  1134. proc newSymNode*(sym: PSym, info: TLineInfo): PNode =
  1135. result = newNode(nkSym)
  1136. result.sym = sym
  1137. result.typ() = sym.typ
  1138. result.info = info
  1139. proc newOpenSym*(n: PNode): PNode {.inline.} =
  1140. result = newTreeI(nkOpenSym, n.info, n)
  1141. proc newIntNode*(kind: TNodeKind, intVal: BiggestInt): PNode =
  1142. result = newNode(kind)
  1143. result.intVal = intVal
  1144. proc newIntNode*(kind: TNodeKind, intVal: Int128): PNode =
  1145. result = newNode(kind)
  1146. result.intVal = castToInt64(intVal)
  1147. proc lastSon*(n: PNode): PNode {.inline.} = n.sons[^1]
  1148. template setLastSon*(n: PNode, s: PNode) = n.sons[^1] = s
  1149. template firstSon*(n: PNode): PNode = n.sons[0]
  1150. template secondSon*(n: PNode): PNode = n.sons[1]
  1151. template hasSon*(n: PNode): bool = n.len > 0
  1152. template has2Sons*(n: PNode): bool = n.len > 1
  1153. proc replaceFirstSon*(n, newson: PNode) {.inline.} =
  1154. n.sons[0] = newson
  1155. proc replaceSon*(n: PNode; i: int; newson: PNode) {.inline.} =
  1156. n.sons[i] = newson
  1157. proc last*(n: PType): PType {.inline.} = n.sons[^1]
  1158. proc elementType*(n: PType): PType {.inline.} = n.sons[^1]
  1159. proc skipModifier*(n: PType): PType {.inline.} = n.sons[^1]
  1160. proc indexType*(n: PType): PType {.inline.} = n.sons[0]
  1161. proc baseClass*(n: PType): PType {.inline.} = n.sons[0]
  1162. proc base*(t: PType): PType {.inline.} =
  1163. result = t.sons[0]
  1164. proc returnType*(n: PType): PType {.inline.} = n.sons[0]
  1165. proc setReturnType*(n, r: PType) {.inline.} = n.sons[0] = r
  1166. proc setIndexType*(n, idx: PType) {.inline.} = n.sons[0] = idx
  1167. proc firstParamType*(n: PType): PType {.inline.} = n.sons[1]
  1168. proc firstGenericParam*(n: PType): PType {.inline.} = n.sons[1]
  1169. proc typeBodyImpl*(n: PType): PType {.inline.} = n.sons[^1]
  1170. proc genericHead*(n: PType): PType {.inline.} = n.sons[0]
  1171. proc skipTypes*(t: PType, kinds: TTypeKinds): PType =
  1172. ## Used throughout the compiler code to test whether a type tree contains or
  1173. ## doesn't contain a specific type/types - it is often the case that only the
  1174. ## last child nodes of a type tree need to be searched. This is a really hot
  1175. ## path within the compiler!
  1176. result = t
  1177. while result.kind in kinds: result = last(result)
  1178. proc newIntTypeNode*(intVal: BiggestInt, typ: PType): PNode =
  1179. let kind = skipTypes(typ, abstractVarRange).kind
  1180. case kind
  1181. of tyInt: result = newNode(nkIntLit)
  1182. of tyInt8: result = newNode(nkInt8Lit)
  1183. of tyInt16: result = newNode(nkInt16Lit)
  1184. of tyInt32: result = newNode(nkInt32Lit)
  1185. of tyInt64: result = newNode(nkInt64Lit)
  1186. of tyChar: result = newNode(nkCharLit)
  1187. of tyUInt: result = newNode(nkUIntLit)
  1188. of tyUInt8: result = newNode(nkUInt8Lit)
  1189. of tyUInt16: result = newNode(nkUInt16Lit)
  1190. of tyUInt32: result = newNode(nkUInt32Lit)
  1191. of tyUInt64: result = newNode(nkUInt64Lit)
  1192. of tyBool, tyEnum:
  1193. # XXX: does this really need to be the kind nkIntLit?
  1194. result = newNode(nkIntLit)
  1195. of tyStatic: # that's a pre-existing bug, will fix in another PR
  1196. result = newNode(nkIntLit)
  1197. else: raiseAssert $kind
  1198. result.intVal = intVal
  1199. result.typ() = typ
  1200. proc newIntTypeNode*(intVal: Int128, typ: PType): PNode =
  1201. # XXX: introduce range check
  1202. newIntTypeNode(castToInt64(intVal), typ)
  1203. proc newFloatNode*(kind: TNodeKind, floatVal: BiggestFloat): PNode =
  1204. result = newNode(kind)
  1205. result.floatVal = floatVal
  1206. proc newStrNode*(kind: TNodeKind, strVal: string): PNode =
  1207. result = newNode(kind)
  1208. result.strVal = strVal
  1209. proc newStrNode*(strVal: string; info: TLineInfo): PNode =
  1210. result = newNodeI(nkStrLit, info)
  1211. result.strVal = strVal
  1212. proc newProcNode*(kind: TNodeKind, info: TLineInfo, body: PNode,
  1213. params,
  1214. name, pattern, genericParams,
  1215. pragmas, exceptions: PNode): PNode =
  1216. result = newNodeI(kind, info)
  1217. result.sons = @[name, pattern, genericParams, params,
  1218. pragmas, exceptions, body]
  1219. const
  1220. AttachedOpToStr*: array[TTypeAttachedOp, string] = [
  1221. "=wasMoved", "=destroy", "=copy", "=dup", "=sink", "=trace", "=deepcopy"]
  1222. proc `$`*(s: PSym): string =
  1223. if s != nil:
  1224. result = s.name.s & "@" & $s.id
  1225. else:
  1226. result = "<nil>"
  1227. when false:
  1228. iterator items*(t: PType): PType =
  1229. for i in 0..<t.sons.len: yield t.sons[i]
  1230. iterator pairs*(n: PType): tuple[i: int, n: PType] =
  1231. for i in 0..<n.sons.len: yield (i, n.sons[i])
  1232. when true:
  1233. proc len*(n: PType): int {.inline.} =
  1234. result = n.sons.len
  1235. proc sameTupleLengths*(a, b: PType): bool {.inline.} =
  1236. result = a.sons.len == b.sons.len
  1237. iterator tupleTypePairs*(a, b: PType): (int, PType, PType) =
  1238. for i in 0 ..< a.sons.len:
  1239. yield (i, a.sons[i], b.sons[i])
  1240. iterator underspecifiedPairs*(a, b: PType; start = 0; without = 0): (PType, PType) =
  1241. # XXX Figure out with what typekinds this is called.
  1242. for i in start ..< min(a.sons.len, b.sons.len) + without:
  1243. yield (a.sons[i], b.sons[i])
  1244. proc signatureLen*(t: PType): int {.inline.} =
  1245. result = t.sons.len
  1246. proc paramsLen*(t: PType): int {.inline.} =
  1247. result = t.sons.len - 1
  1248. proc genericParamsLen*(t: PType): int {.inline.} =
  1249. assert t.kind == tyGenericInst
  1250. result = t.sons.len - 2 # without 'head' and 'body'
  1251. proc genericInvocationParamsLen*(t: PType): int {.inline.} =
  1252. assert t.kind == tyGenericInvocation
  1253. result = t.sons.len - 1 # without 'head'
  1254. proc kidsLen*(t: PType): int {.inline.} =
  1255. result = t.sons.len
  1256. proc genericParamHasConstraints*(t: PType): bool {.inline.} = t.sons.len > 0
  1257. proc hasElementType*(t: PType): bool {.inline.} = t.sons.len > 0
  1258. proc isEmptyTupleType*(t: PType): bool {.inline.} = t.sons.len == 0
  1259. proc isSingletonTupleType*(t: PType): bool {.inline.} = t.sons.len == 1
  1260. proc genericConstraint*(t: PType): PType {.inline.} = t.sons[0]
  1261. iterator genericInstParams*(t: PType): (bool, PType) =
  1262. for i in 1..<t.sons.len-1:
  1263. yield (i!=1, t.sons[i])
  1264. iterator genericInstParamPairs*(a, b: PType): (int, PType, PType) =
  1265. for i in 1..<min(a.sons.len, b.sons.len)-1:
  1266. yield (i-1, a.sons[i], b.sons[i])
  1267. iterator genericInvocationParams*(t: PType): (bool, PType) =
  1268. for i in 1..<t.sons.len:
  1269. yield (i!=1, t.sons[i])
  1270. iterator genericInvocationAndBodyElements*(a, b: PType): (PType, PType) =
  1271. for i in 1..<a.sons.len:
  1272. yield (a.sons[i], b.sons[i-1])
  1273. iterator genericInvocationParamPairs*(a, b: PType): (bool, PType, PType) =
  1274. for i in 1..<a.sons.len:
  1275. if i >= b.sons.len:
  1276. yield (false, nil, nil)
  1277. else:
  1278. yield (true, a.sons[i], b.sons[i])
  1279. iterator genericBodyParams*(t: PType): (int, PType) =
  1280. for i in 0..<t.sons.len-1:
  1281. yield (i, t.sons[i])
  1282. iterator userTypeClassInstParams*(t: PType): (bool, PType) =
  1283. for i in 1..<t.sons.len-1:
  1284. yield (i!=1, t.sons[i])
  1285. iterator ikids*(t: PType): (int, PType) =
  1286. for i in 0..<t.sons.len: yield (i, t.sons[i])
  1287. const
  1288. FirstParamAt* = 1
  1289. FirstGenericParamAt* = 1
  1290. iterator paramTypes*(t: PType): (int, PType) =
  1291. for i in FirstParamAt..<t.sons.len: yield (i, t.sons[i])
  1292. iterator paramTypePairs*(a, b: PType): (PType, PType) =
  1293. for i in FirstParamAt..<a.sons.len: yield (a.sons[i], b.sons[i])
  1294. template paramTypeToNodeIndex*(x: int): int = x
  1295. iterator kids*(t: PType): PType =
  1296. for i in 0..<t.sons.len: yield t.sons[i]
  1297. iterator signature*(t: PType): PType =
  1298. # yields return type + parameter types
  1299. for i in 0..<t.sons.len: yield t.sons[i]
  1300. proc newType*(kind: TTypeKind; idgen: IdGenerator; owner: PSym; son: sink PType = nil): PType =
  1301. let id = nextTypeId idgen
  1302. result = PType(kind: kind, ownerField: owner, size: defaultSize,
  1303. align: defaultAlignment, itemId: id,
  1304. uniqueId: id, sons: @[])
  1305. if son != nil: result.sons.add son
  1306. when false:
  1307. if result.itemId.module == 55 and result.itemId.item == 2:
  1308. echo "KNID ", kind
  1309. writeStackTrace()
  1310. proc setSons*(dest: PType; sons: sink seq[PType]) {.inline.} = dest.sons = sons
  1311. proc setSon*(dest: PType; son: sink PType) {.inline.} = dest.sons = @[son]
  1312. proc setSonsLen*(dest: PType; len: int) {.inline.} = setLen(dest.sons, len)
  1313. proc mergeLoc(a: var TLoc, b: TLoc) =
  1314. if a.k == low(typeof(a.k)): a.k = b.k
  1315. if a.storage == low(typeof(a.storage)): a.storage = b.storage
  1316. a.flags.incl b.flags
  1317. if a.lode == nil: a.lode = b.lode
  1318. if a.snippet == "": a.snippet = b.snippet
  1319. proc newSons*(father: PNode, length: int) =
  1320. setLen(father.sons, length)
  1321. proc newSons*(father: PType, length: int) =
  1322. setLen(father.sons, length)
  1323. proc truncateInferredTypeCandidates*(t: PType) {.inline.} =
  1324. assert t.kind == tyInferred
  1325. if t.sons.len > 1:
  1326. setLen(t.sons, 1)
  1327. proc assignType*(dest, src: PType) =
  1328. dest.kind = src.kind
  1329. dest.flags = src.flags
  1330. dest.callConv = src.callConv
  1331. dest.n = src.n
  1332. dest.size = src.size
  1333. dest.align = src.align
  1334. # this fixes 'type TLock = TSysLock':
  1335. if src.sym != nil:
  1336. if dest.sym != nil:
  1337. dest.sym.flags.incl src.sym.flags-{sfUsed, sfExported}
  1338. if dest.sym.annex == nil: dest.sym.annex = src.sym.annex
  1339. mergeLoc(dest.sym.loc, src.sym.loc)
  1340. else:
  1341. dest.sym = src.sym
  1342. newSons(dest, src.sons.len)
  1343. for i in 0..<src.sons.len: dest[i] = src[i]
  1344. proc copyType*(t: PType, idgen: IdGenerator, owner: PSym): PType =
  1345. result = newType(t.kind, idgen, owner)
  1346. assignType(result, t)
  1347. result.sym = t.sym # backend-info should not be copied
  1348. proc exactReplica*(t: PType): PType =
  1349. result = PType(kind: t.kind, ownerField: t.owner, size: defaultSize,
  1350. align: defaultAlignment, itemId: t.itemId,
  1351. uniqueId: t.uniqueId)
  1352. assignType(result, t)
  1353. result.sym = t.sym # backend-info should not be copied
  1354. proc copySym*(s: PSym; idgen: IdGenerator): PSym =
  1355. result = newSym(s.kind, s.name, idgen, s.owner, s.info, s.options)
  1356. #result.ast = nil # BUGFIX; was: s.ast which made problems
  1357. result.typ = s.typ
  1358. result.flags = s.flags
  1359. result.magic = s.magic
  1360. result.options = s.options
  1361. result.position = s.position
  1362. result.loc = s.loc
  1363. result.annex = s.annex # BUGFIX
  1364. result.constraint = s.constraint
  1365. if result.kind in {skVar, skLet, skField}:
  1366. result.guard = s.guard
  1367. result.bitsize = s.bitsize
  1368. result.alignment = s.alignment
  1369. proc createModuleAlias*(s: PSym, idgen: IdGenerator, newIdent: PIdent, info: TLineInfo;
  1370. options: TOptions): PSym =
  1371. result = newSym(s.kind, newIdent, idgen, s.owner, info, options)
  1372. # keep ID!
  1373. result.ast = s.ast
  1374. #result.id = s.id # XXX figure out what to do with the ID.
  1375. result.flags = s.flags
  1376. result.options = s.options
  1377. result.position = s.position
  1378. result.loc = s.loc
  1379. result.annex = s.annex
  1380. proc initStrTable*(): TStrTable =
  1381. result = TStrTable(counter: 0)
  1382. newSeq(result.data, StartSize)
  1383. proc initObjectSet*(): TObjectSet =
  1384. result = TObjectSet(counter: 0)
  1385. newSeq(result.data, StartSize)
  1386. proc initNodeTable*(): TNodeTable =
  1387. result = TNodeTable(counter: 0)
  1388. newSeq(result.data, StartSize)
  1389. proc skipTypes*(t: PType, kinds: TTypeKinds; maxIters: int): PType =
  1390. result = t
  1391. var i = maxIters
  1392. while result.kind in kinds:
  1393. result = last(result)
  1394. dec i
  1395. if i == 0: return nil
  1396. proc skipTypesOrNil*(t: PType, kinds: TTypeKinds): PType =
  1397. ## same as skipTypes but handles 'nil'
  1398. result = t
  1399. while result != nil and result.kind in kinds:
  1400. if result.sons.len == 0: return nil
  1401. result = last(result)
  1402. proc isGCedMem*(t: PType): bool {.inline.} =
  1403. result = t.kind in {tyString, tyRef, tySequence} or
  1404. t.kind == tyProc and t.callConv == ccClosure
  1405. proc propagateToOwner*(owner, elem: PType; propagateHasAsgn = true) =
  1406. owner.flags.incl elem.flags * {tfHasMeta, tfTriggersCompileTime}
  1407. if tfNotNil in elem.flags:
  1408. if owner.kind in {tyGenericInst, tyGenericBody, tyGenericInvocation}:
  1409. owner.flags.incl tfNotNil
  1410. if elem.isMetaType:
  1411. owner.flags.incl tfHasMeta
  1412. let mask = elem.flags * {tfHasAsgn, tfHasOwned}
  1413. if mask != {} and propagateHasAsgn:
  1414. let o2 = owner.skipTypes({tyGenericInst, tyAlias, tySink})
  1415. if o2.kind in {tyTuple, tyObject, tyArray,
  1416. tySequence, tyString, tySet, tyDistinct}:
  1417. o2.flags.incl mask
  1418. owner.flags.incl mask
  1419. if owner.kind notin {tyProc, tyGenericInst, tyGenericBody,
  1420. tyGenericInvocation, tyPtr}:
  1421. let elemB = elem.skipTypes({tyGenericInst, tyAlias, tySink})
  1422. if elemB.isGCedMem or tfHasGCedMem in elemB.flags:
  1423. # for simplicity, we propagate this flag even to generics. We then
  1424. # ensure this doesn't bite us in sempass2.
  1425. owner.flags.incl tfHasGCedMem
  1426. proc rawAddSon*(father, son: PType; propagateHasAsgn = true) =
  1427. father.sons.add(son)
  1428. if not son.isNil: propagateToOwner(father, son, propagateHasAsgn)
  1429. proc addSonNilAllowed*(father, son: PNode) =
  1430. father.sons.add(son)
  1431. proc delSon*(father: PNode, idx: int) =
  1432. if father.len == 0: return
  1433. for i in idx..<father.len - 1: father[i] = father[i + 1]
  1434. father.sons.setLen(father.len - 1)
  1435. proc copyNode*(src: PNode): PNode =
  1436. # does not copy its sons!
  1437. if src == nil:
  1438. return nil
  1439. result = newNode(src.kind)
  1440. result.info = src.info
  1441. result.typ() = src.typ
  1442. result.flags = src.flags * PersistentNodeFlags
  1443. result.comment = src.comment
  1444. when defined(useNodeIds):
  1445. if result.id == nodeIdToDebug:
  1446. echo "COMES FROM ", src.id
  1447. case src.kind
  1448. of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
  1449. of nkFloatLiterals: result.floatVal = src.floatVal
  1450. of nkSym: result.sym = src.sym
  1451. of nkIdent: result.ident = src.ident
  1452. of nkStrLit..nkTripleStrLit: result.strVal = src.strVal
  1453. else: discard
  1454. when defined(nimsuggest):
  1455. result.endInfo = src.endInfo
  1456. template transitionNodeKindCommon(k: TNodeKind) =
  1457. let obj {.inject.} = n[]
  1458. n[] = TNode(kind: k, typField: n.typ, info: obj.info, flags: obj.flags)
  1459. # n.comment = obj.comment # shouldn't be needed, the address doesnt' change
  1460. when defined(useNodeIds):
  1461. n.id = obj.id
  1462. proc transitionSonsKind*(n: PNode, kind: range[nkComesFrom..nkTupleConstr]) =
  1463. transitionNodeKindCommon(kind)
  1464. n.sons = obj.sons
  1465. proc transitionIntKind*(n: PNode, kind: range[nkCharLit..nkUInt64Lit]) =
  1466. transitionNodeKindCommon(kind)
  1467. n.intVal = obj.intVal
  1468. proc transitionIntToFloatKind*(n: PNode, kind: range[nkFloatLit..nkFloat128Lit]) =
  1469. transitionNodeKindCommon(kind)
  1470. n.floatVal = BiggestFloat(obj.intVal)
  1471. proc transitionNoneToSym*(n: PNode) =
  1472. transitionNodeKindCommon(nkSym)
  1473. template transitionSymKindCommon*(k: TSymKind) =
  1474. let obj {.inject.} = s[]
  1475. s[] = TSym(kind: k, itemId: obj.itemId, magic: obj.magic, typ: obj.typ, name: obj.name,
  1476. info: obj.info, ownerField: obj.ownerField, flags: obj.flags, ast: obj.ast,
  1477. options: obj.options, position: obj.position, offset: obj.offset,
  1478. loc: obj.loc, annex: obj.annex, constraint: obj.constraint)
  1479. when hasFFI:
  1480. s.cname = obj.cname
  1481. when defined(nimsuggest):
  1482. s.allUsages = obj.allUsages
  1483. proc transitionGenericParamToType*(s: PSym) =
  1484. transitionSymKindCommon(skType)
  1485. proc transitionRoutineSymKind*(s: PSym, kind: range[skProc..skTemplate]) =
  1486. transitionSymKindCommon(kind)
  1487. s.gcUnsafetyReason = obj.gcUnsafetyReason
  1488. s.transformedBody = obj.transformedBody
  1489. proc transitionToLet*(s: PSym) =
  1490. transitionSymKindCommon(skLet)
  1491. s.guard = obj.guard
  1492. s.bitsize = obj.bitsize
  1493. s.alignment = obj.alignment
  1494. template copyNodeImpl(dst, src, processSonsStmt) =
  1495. if src == nil: return
  1496. dst = newNode(src.kind)
  1497. dst.info = src.info
  1498. when defined(nimsuggest):
  1499. result.endInfo = src.endInfo
  1500. dst.typ() = src.typ
  1501. dst.flags = src.flags * PersistentNodeFlags
  1502. dst.comment = src.comment
  1503. when defined(useNodeIds):
  1504. if dst.id == nodeIdToDebug:
  1505. echo "COMES FROM ", src.id
  1506. case src.kind
  1507. of nkCharLit..nkUInt64Lit: dst.intVal = src.intVal
  1508. of nkFloatLiterals: dst.floatVal = src.floatVal
  1509. of nkSym: dst.sym = src.sym
  1510. of nkIdent: dst.ident = src.ident
  1511. of nkStrLit..nkTripleStrLit: dst.strVal = src.strVal
  1512. else: processSonsStmt
  1513. proc shallowCopy*(src: PNode): PNode =
  1514. # does not copy its sons, but provides space for them:
  1515. copyNodeImpl(result, src):
  1516. newSeq(result.sons, src.len)
  1517. proc copyTree*(src: PNode): PNode =
  1518. # copy a whole syntax tree; performs deep copying
  1519. copyNodeImpl(result, src):
  1520. newSeq(result.sons, src.len)
  1521. for i in 0..<src.len:
  1522. result[i] = copyTree(src[i])
  1523. proc copyTreeWithoutNode*(src, skippedNode: PNode): PNode =
  1524. copyNodeImpl(result, src):
  1525. result.sons = newSeqOfCap[PNode](src.len)
  1526. for n in src.sons:
  1527. if n != skippedNode:
  1528. result.sons.add copyTreeWithoutNode(n, skippedNode)
  1529. proc hasSonWith*(n: PNode, kind: TNodeKind): bool =
  1530. for i in 0..<n.len:
  1531. if n[i].kind == kind:
  1532. return true
  1533. result = false
  1534. proc hasNilSon*(n: PNode): bool =
  1535. for i in 0..<n.safeLen:
  1536. if n[i] == nil:
  1537. return true
  1538. elif hasNilSon(n[i]):
  1539. return true
  1540. result = false
  1541. proc containsNode*(n: PNode, kinds: TNodeKinds): bool =
  1542. result = false
  1543. if n == nil: return
  1544. case n.kind
  1545. of nkEmpty..nkNilLit: result = n.kind in kinds
  1546. else:
  1547. for i in 0..<n.len:
  1548. if n.kind in kinds or containsNode(n[i], kinds): return true
  1549. proc hasSubnodeWith*(n: PNode, kind: TNodeKind): bool =
  1550. case n.kind
  1551. of nkEmpty..nkNilLit, nkFormalParams: result = n.kind == kind
  1552. else:
  1553. for i in 0..<n.len:
  1554. if (n[i].kind == kind) or hasSubnodeWith(n[i], kind):
  1555. return true
  1556. result = false
  1557. proc getInt*(a: PNode): Int128 =
  1558. case a.kind
  1559. of nkCharLit, nkUIntLit..nkUInt64Lit:
  1560. result = toInt128(cast[uint64](a.intVal))
  1561. of nkInt8Lit..nkInt64Lit:
  1562. result = toInt128(a.intVal)
  1563. of nkIntLit:
  1564. # XXX: enable this assert
  1565. # assert a.typ.kind notin {tyChar, tyUint..tyUInt64}
  1566. result = toInt128(a.intVal)
  1567. else:
  1568. raiseRecoverableError("cannot extract number from invalid AST node")
  1569. proc getInt64*(a: PNode): int64 {.deprecated: "use getInt".} =
  1570. case a.kind
  1571. of nkCharLit, nkUIntLit..nkUInt64Lit, nkIntLit..nkInt64Lit:
  1572. result = a.intVal
  1573. else:
  1574. raiseRecoverableError("cannot extract number from invalid AST node")
  1575. proc getFloat*(a: PNode): BiggestFloat =
  1576. case a.kind
  1577. of nkFloatLiterals: result = a.floatVal
  1578. of nkCharLit, nkUIntLit..nkUInt64Lit, nkIntLit..nkInt64Lit:
  1579. result = BiggestFloat a.intVal
  1580. else:
  1581. raiseRecoverableError("cannot extract number from invalid AST node")
  1582. #doAssert false, "getFloat"
  1583. #internalError(a.info, "getFloat")
  1584. #result = 0.0
  1585. proc getStr*(a: PNode): string =
  1586. case a.kind
  1587. of nkStrLit..nkTripleStrLit: result = a.strVal
  1588. of nkNilLit:
  1589. # let's hope this fixes more problems than it creates:
  1590. result = ""
  1591. else:
  1592. raiseRecoverableError("cannot extract string from invalid AST node")
  1593. #doAssert false, "getStr"
  1594. #internalError(a.info, "getStr")
  1595. #result = ""
  1596. proc getStrOrChar*(a: PNode): string =
  1597. case a.kind
  1598. of nkStrLit..nkTripleStrLit: result = a.strVal
  1599. of nkCharLit..nkUInt64Lit: result = $chr(int(a.intVal))
  1600. else:
  1601. raiseRecoverableError("cannot extract string from invalid AST node")
  1602. #doAssert false, "getStrOrChar"
  1603. #internalError(a.info, "getStrOrChar")
  1604. #result = ""
  1605. proc isGenericParams*(n: PNode): bool {.inline.} =
  1606. ## used to judge whether a node is generic params.
  1607. n != nil and n.kind == nkGenericParams
  1608. proc isGenericRoutine*(n: PNode): bool {.inline.} =
  1609. n != nil and n.kind in callableDefs and n[genericParamsPos].isGenericParams
  1610. proc isGenericRoutineStrict*(s: PSym): bool {.inline.} =
  1611. ## determines if this symbol represents a generic routine
  1612. ## the unusual name is so it doesn't collide and eventually replaces
  1613. ## `isGenericRoutine`
  1614. s.kind in skProcKinds and s.ast.isGenericRoutine
  1615. proc isGenericRoutine*(s: PSym): bool {.inline.} =
  1616. ## determines if this symbol represents a generic routine or an instance of
  1617. ## one. This should be renamed accordingly and `isGenericRoutineStrict`
  1618. ## should take this name instead.
  1619. ##
  1620. ## Warning/XXX: Unfortunately, it considers a proc kind symbol flagged with
  1621. ## sfFromGeneric as a generic routine. Instead this should likely not be the
  1622. ## case and the concepts should be teased apart:
  1623. ## - generic definition
  1624. ## - generic instance
  1625. ## - either generic definition or instance
  1626. s.kind in skProcKinds and (sfFromGeneric in s.flags or
  1627. s.ast.isGenericRoutine)
  1628. proc skipGenericOwner*(s: PSym): PSym =
  1629. ## Generic instantiations are owned by their originating generic
  1630. ## symbol. This proc skips such owners and goes straight to the owner
  1631. ## of the generic itself (the module or the enclosing proc).
  1632. result = if s.kind == skModule:
  1633. s
  1634. elif s.kind in skProcKinds and sfFromGeneric in s.flags and s.owner.kind != skModule:
  1635. s.owner.owner
  1636. else:
  1637. s.owner
  1638. proc originatingModule*(s: PSym): PSym =
  1639. result = s
  1640. while result.kind != skModule: result = result.owner
  1641. proc isRoutine*(s: PSym): bool {.inline.} =
  1642. result = s.kind in skProcKinds
  1643. proc isCompileTimeProc*(s: PSym): bool {.inline.} =
  1644. result = s.kind == skMacro or
  1645. s.kind in {skProc, skFunc} and sfCompileTime in s.flags
  1646. proc hasPattern*(s: PSym): bool {.inline.} =
  1647. result = isRoutine(s) and s.ast[patternPos].kind != nkEmpty
  1648. iterator items*(n: PNode): PNode =
  1649. for i in 0..<n.safeLen: yield n[i]
  1650. iterator pairs*(n: PNode): tuple[i: int, n: PNode] =
  1651. for i in 0..<n.safeLen: yield (i, n[i])
  1652. proc isAtom*(n: PNode): bool {.inline.} =
  1653. result = n.kind >= nkNone and n.kind <= nkNilLit
  1654. proc isEmptyType*(t: PType): bool {.inline.} =
  1655. ## 'void' and 'typed' types are often equivalent to 'nil' these days:
  1656. result = t == nil or t.kind in {tyVoid, tyTyped}
  1657. proc makeStmtList*(n: PNode): PNode =
  1658. if n.kind == nkStmtList:
  1659. result = n
  1660. else:
  1661. result = newNodeI(nkStmtList, n.info)
  1662. result.add n
  1663. proc skipStmtList*(n: PNode): PNode =
  1664. if n.kind in {nkStmtList, nkStmtListExpr}:
  1665. for i in 0..<n.len-1:
  1666. if n[i].kind notin {nkEmpty, nkCommentStmt}: return n
  1667. result = n.lastSon
  1668. else:
  1669. result = n
  1670. proc toVar*(typ: PType; kind: TTypeKind; idgen: IdGenerator): PType =
  1671. ## If ``typ`` is not a tyVar then it is converted into a `var <typ>` and
  1672. ## returned. Otherwise ``typ`` is simply returned as-is.
  1673. result = typ
  1674. if typ.kind != kind:
  1675. result = newType(kind, idgen, typ.owner, typ)
  1676. proc toRef*(typ: PType; idgen: IdGenerator): PType =
  1677. ## If ``typ`` is a tyObject then it is converted into a `ref <typ>` and
  1678. ## returned. Otherwise ``typ`` is simply returned as-is.
  1679. result = typ
  1680. if typ.skipTypes({tyAlias, tyGenericInst}).kind == tyObject:
  1681. result = newType(tyRef, idgen, typ.owner, typ)
  1682. proc toObject*(typ: PType): PType =
  1683. ## If ``typ`` is a tyRef then its immediate son is returned (which in many
  1684. ## cases should be a ``tyObject``).
  1685. ## Otherwise ``typ`` is simply returned as-is.
  1686. let t = typ.skipTypes({tyAlias, tyGenericInst})
  1687. if t.kind == tyRef: t.elementType
  1688. else: typ
  1689. proc toObjectFromRefPtrGeneric*(typ: PType): PType =
  1690. #[
  1691. See also `toObject`.
  1692. Finds the underlying `object`, even in cases like these:
  1693. type
  1694. B[T] = object f0: int
  1695. A1[T] = ref B[T]
  1696. A2[T] = ref object f1: int
  1697. A3 = ref object f2: int
  1698. A4 = object f3: int
  1699. ]#
  1700. result = typ
  1701. while true:
  1702. case result.kind
  1703. of tyGenericBody: result = result.last
  1704. of tyRef, tyPtr, tyGenericInst, tyGenericInvocation, tyAlias: result = result[0]
  1705. # automatic dereferencing is deep, refs #18298.
  1706. else: break
  1707. # result does not have to be object type
  1708. proc isImportedException*(t: PType; conf: ConfigRef): bool =
  1709. assert t != nil
  1710. if conf.exc != excCpp:
  1711. return false
  1712. let base = t.skipTypes({tyAlias, tyPtr, tyDistinct, tyGenericInst})
  1713. result = base.sym != nil and {sfCompileToCpp, sfImportc} * base.sym.flags != {}
  1714. proc isInfixAs*(n: PNode): bool =
  1715. return n.kind == nkInfix and n[0].kind == nkIdent and n[0].ident.id == ord(wAs)
  1716. proc skipColon*(n: PNode): PNode =
  1717. result = n
  1718. if n.kind == nkExprColonExpr:
  1719. result = n[1]
  1720. proc findUnresolvedStatic*(n: PNode): PNode =
  1721. if n.kind == nkSym and n.typ != nil and n.typ.kind == tyStatic and n.typ.n == nil:
  1722. return n
  1723. if n.typ != nil and n.typ.kind == tyTypeDesc:
  1724. let t = skipTypes(n.typ, {tyTypeDesc})
  1725. if t.kind == tyGenericParam and not t.genericParamHasConstraints:
  1726. return n
  1727. for son in n:
  1728. let n = son.findUnresolvedStatic
  1729. if n != nil: return n
  1730. return nil
  1731. when false:
  1732. proc containsNil*(n: PNode): bool =
  1733. # only for debugging
  1734. if n.isNil: return true
  1735. for i in 0..<n.safeLen:
  1736. if n[i].containsNil: return true
  1737. template hasDestructor*(t: PType): bool = {tfHasAsgn, tfHasOwned} * t.flags != {}
  1738. template incompleteType*(t: PType): bool =
  1739. t.sym != nil and {sfForward, sfNoForward} * t.sym.flags == {sfForward}
  1740. template typeCompleted*(s: PSym) =
  1741. incl s.flags, sfNoForward
  1742. template detailedInfo*(sym: PSym): string =
  1743. sym.name.s
  1744. proc isInlineIterator*(typ: PType): bool {.inline.} =
  1745. typ.kind == tyProc and tfIterator in typ.flags and typ.callConv != ccClosure
  1746. proc isIterator*(typ: PType): bool {.inline.} =
  1747. typ.kind == tyProc and tfIterator in typ.flags
  1748. proc isClosureIterator*(typ: PType): bool {.inline.} =
  1749. typ.kind == tyProc and tfIterator in typ.flags and typ.callConv == ccClosure
  1750. proc isClosure*(typ: PType): bool {.inline.} =
  1751. typ.kind == tyProc and typ.callConv == ccClosure
  1752. proc isNimcall*(s: PSym): bool {.inline.} =
  1753. s.typ.callConv == ccNimCall
  1754. proc isExplicitCallConv*(s: PSym): bool {.inline.} =
  1755. tfExplicitCallConv in s.typ.flags
  1756. proc isSinkParam*(s: PSym): bool {.inline.} =
  1757. s.kind == skParam and (s.typ.kind == tySink or tfHasOwned in s.typ.flags)
  1758. proc isSinkType*(t: PType): bool {.inline.} =
  1759. t.kind == tySink or tfHasOwned in t.flags
  1760. proc newProcType*(info: TLineInfo; idgen: IdGenerator; owner: PSym): PType =
  1761. result = newType(tyProc, idgen, owner)
  1762. result.n = newNodeI(nkFormalParams, info)
  1763. rawAddSon(result, nil) # return type
  1764. # result.n[0] used to be `nkType`, but now it's `nkEffectList` because
  1765. # the effects are now stored in there too ... this is a bit hacky, but as
  1766. # usual we desperately try to save memory:
  1767. result.n.add newNodeI(nkEffectList, info)
  1768. proc addParam*(procType: PType; param: PSym) =
  1769. param.position = procType.sons.len-1
  1770. procType.n.add newSymNode(param)
  1771. rawAddSon(procType, param.typ)
  1772. const magicsThatCanRaise = {
  1773. mNone, mSlurp, mStaticExec, mParseExprToAst, mParseStmtToAst, mEcho}
  1774. proc canRaiseConservative*(fn: PNode): bool =
  1775. if fn.kind == nkSym and fn.sym.magic notin magicsThatCanRaise:
  1776. result = false
  1777. else:
  1778. result = true
  1779. proc canRaise*(fn: PNode): bool =
  1780. if fn.kind == nkSym and (fn.sym.magic notin magicsThatCanRaise or
  1781. {sfImportc, sfInfixCall} * fn.sym.flags == {sfImportc} or
  1782. sfGeneratedOp in fn.sym.flags):
  1783. result = false
  1784. elif fn.kind == nkSym and fn.sym.magic == mEcho:
  1785. result = true
  1786. elif fn.typ != nil and fn.typ.kind == tyProc and fn.typ.n != nil:
  1787. # TODO check for n having sons? or just return false for now if not
  1788. if fn.typ.n[0].kind == nkSym:
  1789. result = false
  1790. else:
  1791. result = ((fn.typ.n[0].len < effectListLen) or
  1792. (fn.typ.n[0][exceptionEffects] != nil and
  1793. fn.typ.n[0][exceptionEffects].safeLen > 0))
  1794. else:
  1795. result = false
  1796. proc toHumanStrImpl[T](kind: T, num: static int): string =
  1797. result = $kind
  1798. result = result[num..^1]
  1799. result[0] = result[0].toLowerAscii
  1800. proc toHumanStr*(kind: TSymKind): string =
  1801. ## strips leading `sk`
  1802. result = toHumanStrImpl(kind, 2)
  1803. proc toHumanStr*(kind: TTypeKind): string =
  1804. ## strips leading `tk`
  1805. result = toHumanStrImpl(kind, 2)
  1806. proc skipHiddenAddr*(n: PNode): PNode {.inline.} =
  1807. (if n.kind == nkHiddenAddr: n[0] else: n)
  1808. proc isNewStyleConcept*(n: PNode): bool {.inline.} =
  1809. assert n.kind == nkTypeClassTy
  1810. result = n[0].kind == nkEmpty
  1811. proc isOutParam*(t: PType): bool {.inline.} = tfIsOutParam in t.flags
  1812. const
  1813. nodesToIgnoreSet* = {nkNone..pred(nkSym), succ(nkSym)..nkNilLit,
  1814. nkTypeSection, nkProcDef, nkConverterDef,
  1815. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  1816. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  1817. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState,
  1818. nkTypeOfExpr, nkMixinStmt, nkBindStmt}
  1819. proc isTrue*(n: PNode): bool =
  1820. n.kind == nkSym and n.sym.kind == skEnumField and n.sym.position != 0 or
  1821. n.kind == nkIntLit and n.intVal != 0
  1822. type
  1823. TypeMapping* = Table[ItemId, PType]
  1824. SymMapping* = Table[ItemId, PSym]
  1825. template idTableGet*(tab: typed; key: PSym | PType): untyped = tab.getOrDefault(key.itemId)
  1826. template idTablePut*(tab: typed; key, val: PSym | PType) = tab[key.itemId] = val
  1827. template initSymMapping*(): Table[ItemId, PSym] = initTable[ItemId, PSym]()
  1828. template initTypeMapping*(): Table[ItemId, PType] = initTable[ItemId, PType]()
  1829. template resetIdTable*(tab: Table[ItemId, PSym]) = tab.clear()
  1830. template resetIdTable*(tab: Table[ItemId, PType]) = tab.clear()