ast.nim 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  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, hashes, nversion, options, strutils, std / sha1, ropes, idents,
  12. intsets, idgen
  13. type
  14. TCallingConvention* = enum
  15. ccDefault, # proc has no explicit calling convention
  16. ccStdCall, # procedure is stdcall
  17. ccCDecl, # cdecl
  18. ccSafeCall, # safecall
  19. ccSysCall, # system call
  20. ccInline, # proc should be inlined
  21. ccNoInline, # proc should not be inlined
  22. ccFastCall, # fastcall (pass parameters in registers)
  23. ccClosure, # proc has a closure
  24. ccNoConvention # needed for generating proper C procs sometimes
  25. const
  26. CallingConvToStr*: array[TCallingConvention, string] = ["", "stdcall",
  27. "cdecl", "safecall", "syscall", "inline", "noinline", "fastcall",
  28. "closure", "noconv"]
  29. type
  30. TNodeKind* = enum # order is extremely important, because ranges are used
  31. # to check whether a node belongs to a certain class
  32. nkNone, # unknown node kind: indicates an error
  33. # Expressions:
  34. # Atoms:
  35. nkEmpty, # the node is empty
  36. nkIdent, # node is an identifier
  37. nkSym, # node is a symbol
  38. nkType, # node is used for its typ field
  39. nkCharLit, # a character literal ''
  40. nkIntLit, # an integer literal
  41. nkInt8Lit,
  42. nkInt16Lit,
  43. nkInt32Lit,
  44. nkInt64Lit,
  45. nkUIntLit, # an unsigned integer literal
  46. nkUInt8Lit,
  47. nkUInt16Lit,
  48. nkUInt32Lit,
  49. nkUInt64Lit,
  50. nkFloatLit, # a floating point literal
  51. nkFloat32Lit,
  52. nkFloat64Lit,
  53. nkFloat128Lit,
  54. nkStrLit, # a string literal ""
  55. nkRStrLit, # a raw string literal r""
  56. nkTripleStrLit, # a triple string literal """
  57. nkNilLit, # the nil literal
  58. # end of atoms
  59. nkComesFrom, # "comes from" template/macro information for
  60. # better stack trace generation
  61. nkDotCall, # used to temporarily flag a nkCall node;
  62. # this is used
  63. # for transforming ``s.len`` to ``len(s)``
  64. nkCommand, # a call like ``p 2, 4`` without parenthesis
  65. nkCall, # a call like p(x, y) or an operation like +(a, b)
  66. nkCallStrLit, # a call with a string literal
  67. # x"abc" has two sons: nkIdent, nkRStrLit
  68. # x"""abc""" has two sons: nkIdent, nkTripleStrLit
  69. nkInfix, # a call like (a + b)
  70. nkPrefix, # a call like !a
  71. nkPostfix, # something like a! (also used for visibility)
  72. nkHiddenCallConv, # an implicit type conversion via a type converter
  73. nkExprEqExpr, # a named parameter with equals: ''expr = expr''
  74. nkExprColonExpr, # a named parameter with colon: ''expr: expr''
  75. nkIdentDefs, # a definition like `a, b: typeDesc = expr`
  76. # either typeDesc or expr may be nil; used in
  77. # formal parameters, var statements, etc.
  78. nkVarTuple, # a ``var (a, b) = expr`` construct
  79. nkPar, # syntactic (); may be a tuple constructor
  80. nkObjConstr, # object constructor: T(a: 1, b: 2)
  81. nkCurly, # syntactic {}
  82. nkCurlyExpr, # an expression like a{i}
  83. nkBracket, # syntactic []
  84. nkBracketExpr, # an expression like a[i..j, k]
  85. nkPragmaExpr, # an expression like a{.pragmas.}
  86. nkRange, # an expression like i..j
  87. nkDotExpr, # a.b
  88. nkCheckedFieldExpr, # a.b, but b is a field that needs to be checked
  89. nkDerefExpr, # a^
  90. nkIfExpr, # if as an expression
  91. nkElifExpr,
  92. nkElseExpr,
  93. nkLambda, # lambda expression
  94. nkDo, # lambda block appering as trailing proc param
  95. nkAccQuoted, # `a` as a node
  96. nkTableConstr, # a table constructor {expr: expr}
  97. nkBind, # ``bind expr`` node
  98. nkClosedSymChoice, # symbol choice node; a list of nkSyms (closed)
  99. nkOpenSymChoice, # symbol choice node; a list of nkSyms (open)
  100. nkHiddenStdConv, # an implicit standard type conversion
  101. nkHiddenSubConv, # an implicit type conversion from a subtype
  102. # to a supertype
  103. nkConv, # a type conversion
  104. nkCast, # a type cast
  105. nkStaticExpr, # a static expr
  106. nkAddr, # a addr expression
  107. nkHiddenAddr, # implicit address operator
  108. nkHiddenDeref, # implicit ^ operator
  109. nkObjDownConv, # down conversion between object types
  110. nkObjUpConv, # up conversion between object types
  111. nkChckRangeF, # range check for floats
  112. nkChckRange64, # range check for 64 bit ints
  113. nkChckRange, # range check for ints
  114. nkStringToCString, # string to cstring
  115. nkCStringToString, # cstring to string
  116. # end of expressions
  117. nkAsgn, # a = b
  118. nkFastAsgn, # internal node for a fast ``a = b``
  119. # (no string copy)
  120. nkGenericParams, # generic parameters
  121. nkFormalParams, # formal parameters
  122. nkOfInherit, # inherited from symbol
  123. nkImportAs, # a 'as' b in an import statement
  124. nkProcDef, # a proc
  125. nkMethodDef, # a method
  126. nkConverterDef, # a converter
  127. nkMacroDef, # a macro
  128. nkTemplateDef, # a template
  129. nkIteratorDef, # an iterator
  130. nkOfBranch, # used inside case statements
  131. # for (cond, action)-pairs
  132. nkElifBranch, # used in if statements
  133. nkExceptBranch, # an except section
  134. nkElse, # an else part
  135. nkAsmStmt, # an assembler block
  136. nkPragma, # a pragma statement
  137. nkPragmaBlock, # a pragma with a block
  138. nkIfStmt, # an if statement
  139. nkWhenStmt, # a when expression or statement
  140. nkForStmt, # a for statement
  141. nkParForStmt, # a parallel for statement
  142. nkWhileStmt, # a while statement
  143. nkCaseStmt, # a case statement
  144. nkTypeSection, # a type section (consists of type definitions)
  145. nkVarSection, # a var section
  146. nkLetSection, # a let section
  147. nkConstSection, # a const section
  148. nkConstDef, # a const definition
  149. nkTypeDef, # a type definition
  150. nkYieldStmt, # the yield statement as a tree
  151. nkDefer, # the 'defer' statement
  152. nkTryStmt, # a try statement
  153. nkFinally, # a finally section
  154. nkRaiseStmt, # a raise statement
  155. nkReturnStmt, # a return statement
  156. nkBreakStmt, # a break statement
  157. nkContinueStmt, # a continue statement
  158. nkBlockStmt, # a block statement
  159. nkStaticStmt, # a static statement
  160. nkDiscardStmt, # a discard statement
  161. nkStmtList, # a list of statements
  162. nkImportStmt, # an import statement
  163. nkImportExceptStmt, # an import x except a statement
  164. nkExportStmt, # an export statement
  165. nkExportExceptStmt, # an 'export except' statement
  166. nkFromStmt, # a from * import statement
  167. nkIncludeStmt, # an include statement
  168. nkBindStmt, # a bind statement
  169. nkMixinStmt, # a mixin statement
  170. nkUsingStmt, # an using statement
  171. nkCommentStmt, # a comment statement
  172. nkStmtListExpr, # a statement list followed by an expr; this is used
  173. # to allow powerful multi-line templates
  174. nkBlockExpr, # a statement block ending in an expr; this is used
  175. # to allowe powerful multi-line templates that open a
  176. # temporary scope
  177. nkStmtListType, # a statement list ending in a type; for macros
  178. nkBlockType, # a statement block ending in a type; for macros
  179. # types as syntactic trees:
  180. nkWith, # distinct with `foo`
  181. nkWithout, # distinct without `foo`
  182. nkTypeOfExpr, # type(1+2)
  183. nkObjectTy, # object body
  184. nkTupleTy, # tuple body
  185. nkTupleClassTy, # tuple type class
  186. nkTypeClassTy, # user-defined type class
  187. nkStaticTy, # ``static[T]``
  188. nkRecList, # list of object parts
  189. nkRecCase, # case section of object
  190. nkRecWhen, # when section of object
  191. nkRefTy, # ``ref T``
  192. nkPtrTy, # ``ptr T``
  193. nkVarTy, # ``var T``
  194. nkConstTy, # ``const T``
  195. nkMutableTy, # ``mutable T``
  196. nkDistinctTy, # distinct type
  197. nkProcTy, # proc type
  198. nkIteratorTy, # iterator type
  199. nkSharedTy, # 'shared T'
  200. # we use 'nkPostFix' for the 'not nil' addition
  201. nkEnumTy, # enum body
  202. nkEnumFieldDef, # `ident = expr` in an enumeration
  203. nkArgList, # argument list
  204. nkPattern, # a special pattern; used for matching
  205. nkReturnToken, # token used for interpretation
  206. nkClosure, # (prc, env)-pair (internally used for code gen)
  207. nkGotoState, # used for the state machine (for iterators)
  208. nkState, # give a label to a code section (for iterators)
  209. nkBreakState, # special break statement for easier code generation
  210. nkFuncDef, # a func
  211. nkTupleConstr # a tuple constructor
  212. TNodeKinds* = set[TNodeKind]
  213. type
  214. TSymFlag* = enum # already 33 flags!
  215. sfUsed, # read access of sym (for warnings) or simply used
  216. sfExported, # symbol is exported from module
  217. sfFromGeneric, # symbol is instantiation of a generic; this is needed
  218. # for symbol file generation; such symbols should always
  219. # be written into the ROD file
  220. sfGlobal, # symbol is at global scope
  221. sfForward, # symbol is forward declared
  222. sfImportc, # symbol is external; imported
  223. sfExportc, # symbol is exported (under a specified name)
  224. sfVolatile, # variable is volatile
  225. sfRegister, # variable should be placed in a register
  226. sfPure, # object is "pure" that means it has no type-information
  227. # enum is "pure", its values need qualified access
  228. # variable is "pure"; it's an explicit "global"
  229. sfNoSideEffect, # proc has no side effects
  230. sfSideEffect, # proc may have side effects; cannot prove it has none
  231. sfMainModule, # module is the main module
  232. sfSystemModule, # module is the system module
  233. sfNoReturn, # proc never returns (an exit proc)
  234. sfAddrTaken, # the variable's address is taken (ex- or implicitly);
  235. # *OR*: a proc is indirectly called (used as first class)
  236. sfCompilerProc, # proc is a compiler proc, that is a C proc that is
  237. # needed for the code generator
  238. sfProcvar, # proc can be passed to a proc var
  239. sfDiscriminant, # field is a discriminant in a record/object
  240. sfDeprecated, # symbol is deprecated
  241. sfExplain, # provide more diagnostics when this symbol is used
  242. sfError, # usage of symbol should trigger a compile-time error
  243. sfShadowed, # a symbol that was shadowed in some inner scope
  244. sfThread, # proc will run as a thread
  245. # variable is a thread variable
  246. sfCompileTime, # proc can be evaluated at compile time
  247. sfConstructor, # proc is a C++ constructor
  248. sfDispatcher, # copied method symbol is the dispatcher
  249. # deprecated and unused, except for the con
  250. sfBorrow, # proc is borrowed
  251. sfInfixCall, # symbol needs infix call syntax in target language;
  252. # for interfacing with C++, JS
  253. sfNamedParamCall, # symbol needs named parameter call syntax in target
  254. # language; for interfacing with Objective C
  255. sfDiscardable, # returned value may be discarded implicitly
  256. sfOverriden, # proc is overriden
  257. sfGenSym # symbol is 'gensym'ed; do not add to symbol table
  258. TSymFlags* = set[TSymFlag]
  259. const
  260. sfNoInit* = sfMainModule # don't generate code to init the variable
  261. sfImmediate* = sfDispatcher
  262. # macro or template is immediately expanded
  263. # without considering any possible overloads
  264. sfAllUntyped* = sfVolatile # macro or template is immediately expanded \
  265. # in a generic context
  266. sfDirty* = sfPure
  267. # template is not hygienic (old styled template)
  268. # module, compiled from a dirty-buffer
  269. sfAnon* = sfDiscardable
  270. # symbol name that was generated by the compiler
  271. # the compiler will avoid printing such names
  272. # in user messages.
  273. sfHoisted* = sfForward
  274. # an expression was hoised to an anonymous variable.
  275. # the flag is applied to the var/let symbol
  276. sfNoForward* = sfRegister
  277. # forward declarations are not required (per module)
  278. sfReorder* = sfForward
  279. # reordering pass is enabled
  280. sfCompileToCpp* = sfInfixCall # compile the module as C++ code
  281. sfCompileToObjc* = sfNamedParamCall # compile the module as Objective-C code
  282. sfExperimental* = sfOverriden # module uses the .experimental switch
  283. sfGoto* = sfOverriden # var is used for 'goto' code generation
  284. sfWrittenTo* = sfBorrow # param is assigned to
  285. sfEscapes* = sfProcvar # param escapes
  286. sfBase* = sfDiscriminant
  287. sfIsSelf* = sfOverriden # param is 'self'
  288. sfCustomPragma* = sfRegister # symbol is custom pragma template
  289. const
  290. # getting ready for the future expr/stmt merge
  291. nkWhen* = nkWhenStmt
  292. nkWhenExpr* = nkWhenStmt
  293. nkEffectList* = nkArgList
  294. # hacks ahead: an nkEffectList is a node with 4 children:
  295. exceptionEffects* = 0 # exceptions at position 0
  296. usesEffects* = 1 # read effects at position 1
  297. writeEffects* = 2 # write effects at position 2
  298. tagEffects* = 3 # user defined tag ('gc', 'time' etc.)
  299. pragmasEffects* = 4 # not an effect, but a slot for pragmas in proc type
  300. effectListLen* = 5 # list of effects list
  301. type
  302. TTypeKind* = enum # order is important!
  303. # Don't forget to change hti.nim if you make a change here
  304. # XXX put this into an include file to avoid this issue!
  305. # several types are no longer used (guess which), but a
  306. # spot in the sequence is kept for backwards compatibility
  307. # (apparently something with bootstrapping)
  308. # if you need to add a type, they can apparently be reused
  309. tyNone, tyBool, tyChar,
  310. tyEmpty, tyAlias, tyNil, tyExpr, tyStmt, tyTypeDesc,
  311. tyGenericInvocation, # ``T[a, b]`` for types to invoke
  312. tyGenericBody, # ``T[a, b, body]`` last parameter is the body
  313. tyGenericInst, # ``T[a, b, realInstance]`` instantiated generic type
  314. # realInstance will be a concrete type like tyObject
  315. # unless this is an instance of a generic alias type.
  316. # then realInstance will be the tyGenericInst of the
  317. # completely (recursively) resolved alias.
  318. tyGenericParam, # ``a`` in the above patterns
  319. tyDistinct,
  320. tyEnum,
  321. tyOrdinal, # integer types (including enums and boolean)
  322. tyArray,
  323. tyObject,
  324. tyTuple,
  325. tySet,
  326. tyRange,
  327. tyPtr, tyRef,
  328. tyVar,
  329. tySequence,
  330. tyProc,
  331. tyPointer, tyOpenArray,
  332. tyString, tyCString, tyForward,
  333. tyInt, tyInt8, tyInt16, tyInt32, tyInt64, # signed integers
  334. tyFloat, tyFloat32, tyFloat64, tyFloat128,
  335. tyUInt, tyUInt8, tyUInt16, tyUInt32, tyUInt64,
  336. tyOptAsRef, tySink, tyLent,
  337. tyVarargs,
  338. tyUncheckedArray
  339. # An array with boundaries [0,+∞]
  340. tyProxy # used as errornous type (for idetools)
  341. tyBuiltInTypeClass
  342. # Type such as the catch-all object, tuple, seq, etc
  343. tyUserTypeClass
  344. # the body of a user-defined type class
  345. tyUserTypeClassInst
  346. # Instance of a parametric user-defined type class.
  347. # Structured similarly to tyGenericInst.
  348. # tyGenericInst represents concrete types, while
  349. # this is still a "generic param" that will bind types
  350. # and resolves them during sigmatch and instantiation.
  351. tyCompositeTypeClass
  352. # Type such as seq[Number]
  353. # The notes for tyUserTypeClassInst apply here as well
  354. # sons[0]: the original expression used by the user.
  355. # sons[1]: fully expanded and instantiated meta type
  356. # (potentially following aliases)
  357. tyInferred
  358. # In the initial state `base` stores a type class constraining
  359. # the types that can be inferred. After a candidate type is
  360. # selected, it's stored in `lastSon`. Between `base` and `lastSon`
  361. # there may be 0, 2 or more types that were also considered as
  362. # possible candidates in the inference process (i.e. lastSon will
  363. # be updated to store a type best conforming to all candidates)
  364. tyAnd, tyOr, tyNot
  365. # boolean type classes such as `string|int`,`not seq`,
  366. # `Sortable and Enumable`, etc
  367. tyAnything
  368. # a type class matching any type
  369. tyStatic
  370. # a value known at compile type (the underlying type is .base)
  371. tyFromExpr
  372. # This is a type representing an expression that depends
  373. # on generic parameters (the expression is stored in t.n)
  374. # It will be converted to a real type only during generic
  375. # instantiation and prior to this it has the potential to
  376. # be any type.
  377. tyOpt
  378. # Builtin optional type
  379. tyVoid
  380. # now different from tyEmpty, hurray!
  381. static:
  382. # remind us when TTypeKind stops to fit in a single 64-bit word
  383. assert TTypeKind.high.ord <= 63
  384. const
  385. tyPureObject* = tyTuple
  386. GcTypeKinds* = {tyRef, tySequence, tyString}
  387. tyError* = tyProxy # as an errornous node should match everything
  388. tyUnknown* = tyFromExpr
  389. tyUnknownTypes* = {tyError, tyFromExpr}
  390. tyTypeClasses* = {tyBuiltInTypeClass, tyCompositeTypeClass,
  391. tyUserTypeClass, tyUserTypeClassInst,
  392. tyAnd, tyOr, tyNot, tyAnything}
  393. tyMetaTypes* = {tyGenericParam, tyTypeDesc, tyExpr} + tyTypeClasses
  394. tyUserTypeClasses* = {tyUserTypeClass, tyUserTypeClassInst}
  395. type
  396. TTypeKinds* = set[TTypeKind]
  397. TNodeFlag* = enum
  398. nfNone,
  399. nfBase2, # nfBase10 is default, so not needed
  400. nfBase8,
  401. nfBase16,
  402. nfAllConst, # used to mark complex expressions constant; easy to get rid of
  403. # but unfortunately it has measurable impact for compilation
  404. # efficiency
  405. nfTransf, # node has been transformed
  406. nfNoRewrite # node should not be transformed anymore
  407. nfSem # node has been checked for semantics
  408. nfLL # node has gone through lambda lifting
  409. nfDotField # the call can use a dot operator
  410. nfDotSetter # the call can use a setter dot operarator
  411. nfExplicitCall # x.y() was used instead of x.y
  412. nfExprCall # this is an attempt to call a regular expression
  413. nfIsRef # this node is a 'ref' node; used for the VM
  414. nfPreventCg # this node should be ignored by the codegen
  415. nfBlockArg # this a stmtlist appearing in a call (e.g. a do block)
  416. nfFromTemplate # a top-level node returned from a template
  417. nfDefaultParam # an automatically inserter default parameter
  418. nfDefaultRefsParam # a default param value references another parameter
  419. # the flag is applied to proc default values and to calls
  420. TNodeFlags* = set[TNodeFlag]
  421. TTypeFlag* = enum # keep below 32 for efficiency reasons (now: beyond that)
  422. tfVarargs, # procedure has C styled varargs
  423. # tyArray type represeting a varargs list
  424. tfNoSideEffect, # procedure type does not allow side effects
  425. tfFinal, # is the object final?
  426. tfInheritable, # is the object inheritable?
  427. tfAcyclic, # type is acyclic (for GC optimization)
  428. tfEnumHasHoles, # enum cannot be mapped into a range
  429. tfShallow, # type can be shallow copied on assignment
  430. tfThread, # proc type is marked as ``thread``; alias for ``gcsafe``
  431. tfFromGeneric, # type is an instantiation of a generic; this is needed
  432. # because for instantiations of objects, structural
  433. # type equality has to be used
  434. tfUnresolved, # marks unresolved typedesc/static params: e.g.
  435. # proc foo(T: typedesc, list: seq[T]): var T
  436. # proc foo(L: static[int]): array[L, int]
  437. # can be attached to ranges to indicate that the range
  438. # can be attached to generic procs with free standing
  439. # type parameters: e.g. proc foo[T]()
  440. # depends on unresolved static params.
  441. tfResolved # marks a user type class, after it has been bound to a
  442. # concrete type (lastSon becomes the concrete type)
  443. tfRetType, # marks return types in proc (used to detect type classes
  444. # used as return types for return type inference)
  445. tfCapturesEnv, # whether proc really captures some environment
  446. tfByCopy, # pass object/tuple by copy (C backend)
  447. tfByRef, # pass object/tuple by reference (C backend)
  448. tfIterator, # type is really an iterator, not a tyProc
  449. tfPartial, # type is declared as 'partial'
  450. tfNotNil, # type cannot be 'nil'
  451. tfNeedsInit, # type constains a "not nil" constraint somewhere or some
  452. # other type so that it requires initialization
  453. tfVarIsPtr, # 'var' type is translated like 'ptr' even in C++ mode
  454. tfHasMeta, # type contains "wildcard" sub-types such as generic params
  455. # or other type classes
  456. tfHasGCedMem, # type contains GC'ed memory
  457. tfPacked
  458. tfHasStatic
  459. tfGenericTypeParam
  460. tfImplicitTypeParam
  461. tfInferrableStatic
  462. tfConceptMatchedTypeSym
  463. tfExplicit # for typedescs, marks types explicitly prefixed with the
  464. # `type` operator (e.g. type int)
  465. tfWildcard # consider a proc like foo[T, I](x: Type[T, I])
  466. # T and I here can bind to both typedesc and static types
  467. # before this is determined, we'll consider them to be a
  468. # wildcard type.
  469. tfHasAsgn # type has overloaded assignment operator
  470. tfBorrowDot # distinct type borrows '.'
  471. tfTriggersCompileTime # uses the NimNode type which make the proc
  472. # implicitly '.compiletime'
  473. tfRefsAnonObj # used for 'ref object' and 'ptr object'
  474. tfCovariant # covariant generic param mimicing a ptr type
  475. tfWeakCovariant # covariant generic param mimicing a seq/array type
  476. tfContravariant # contravariant generic param
  477. TTypeFlags* = set[TTypeFlag]
  478. TSymKind* = enum # the different symbols (start with the prefix sk);
  479. # order is important for the documentation generator!
  480. skUnknown, # unknown symbol: used for parsing assembler blocks
  481. # and first phase symbol lookup in generics
  482. skConditional, # symbol for the preprocessor (may become obsolete)
  483. skDynLib, # symbol represents a dynamic library; this is used
  484. # internally; it does not exist in Nim code
  485. skParam, # a parameter
  486. skGenericParam, # a generic parameter; eq in ``proc x[eq=`==`]()``
  487. skTemp, # a temporary variable (introduced by compiler)
  488. skModule, # module identifier
  489. skType, # a type
  490. skVar, # a variable
  491. skLet, # a 'let' symbol
  492. skConst, # a constant
  493. skResult, # special 'result' variable
  494. skProc, # a proc
  495. skFunc, # a func
  496. skMethod, # a method
  497. skIterator, # an iterator
  498. skConverter, # a type converter
  499. skMacro, # a macro
  500. skTemplate, # a template; currently also misused for user-defined
  501. # pragmas
  502. skField, # a field in a record or object
  503. skEnumField, # an identifier in an enum
  504. skForVar, # a for loop variable
  505. skLabel, # a label (for block statement)
  506. skStub, # symbol is a stub and not yet loaded from the ROD
  507. # file (it is loaded on demand, which may
  508. # mean: never)
  509. skPackage, # symbol is a package (used for canonicalization)
  510. skAlias # an alias (needs to be resolved immediately)
  511. TSymKinds* = set[TSymKind]
  512. const
  513. routineKinds* = {skProc, skFunc, skMethod, skIterator,
  514. skConverter, skMacro, skTemplate}
  515. tfIncompleteStruct* = tfVarargs
  516. tfUncheckedArray* = tfVarargs
  517. tfUnion* = tfNoSideEffect
  518. tfGcSafe* = tfThread
  519. tfObjHasKids* = tfEnumHasHoles
  520. tfOldSchoolExprStmt* = tfVarargs # for now used to distinguish \
  521. # 'varargs[expr]' from 'varargs[untyped]'. Eventually 'expr' will be
  522. # deprecated and this mess can be cleaned up.
  523. tfReturnsNew* = tfInheritable
  524. skError* = skUnknown
  525. # type flags that are essential for type equality:
  526. eqTypeFlags* = {tfIterator, tfNotNil, tfVarIsPtr}
  527. type
  528. TMagic* = enum # symbols that require compiler magic:
  529. mNone,
  530. mDefined, mDefinedInScope, mCompiles, mArrGet, mArrPut, mAsgn,
  531. mLow, mHigh, mSizeOf, mAlignOf, mOffsetOf, mTypeTrait,
  532. mIs, mOf, mAddr, mType, mTypeOf,
  533. mRoof, mPlugin, mEcho, mShallowCopy, mSlurp, mStaticExec, mStatic,
  534. mParseExprToAst, mParseStmtToAst, mExpandToAst, mQuoteAst,
  535. mUnaryLt, mInc, mDec, mOrd,
  536. mNew, mNewFinalize, mNewSeq, mNewSeqOfCap,
  537. mLengthOpenArray, mLengthStr, mLengthArray, mLengthSeq,
  538. mXLenStr, mXLenSeq,
  539. mIncl, mExcl, mCard, mChr,
  540. mGCref, mGCunref,
  541. mAddI, mSubI, mMulI, mDivI, mModI,
  542. mSucc, mPred,
  543. mAddF64, mSubF64, mMulF64, mDivF64,
  544. mShrI, mShlI, mAshrI, mBitandI, mBitorI, mBitxorI,
  545. mMinI, mMaxI,
  546. mMinF64, mMaxF64,
  547. mAddU, mSubU, mMulU, mDivU, mModU,
  548. mEqI, mLeI, mLtI,
  549. mEqF64, mLeF64, mLtF64,
  550. mLeU, mLtU,
  551. mLeU64, mLtU64,
  552. mEqEnum, mLeEnum, mLtEnum,
  553. mEqCh, mLeCh, mLtCh,
  554. mEqB, mLeB, mLtB,
  555. mEqRef, mEqUntracedRef, mLePtr, mLtPtr,
  556. mXor, mEqCString, mEqProc,
  557. mUnaryMinusI, mUnaryMinusI64, mAbsI, mNot,
  558. mUnaryPlusI, mBitnotI,
  559. mUnaryPlusF64, mUnaryMinusF64, mAbsF64,
  560. mZe8ToI, mZe8ToI64,
  561. mZe16ToI, mZe16ToI64,
  562. mZe32ToI64, mZeIToI64,
  563. mToU8, mToU16, mToU32,
  564. mToFloat, mToBiggestFloat,
  565. mToInt, mToBiggestInt,
  566. mCharToStr, mBoolToStr, mIntToStr, mInt64ToStr, mFloatToStr, mCStrToStr,
  567. mStrToStr, mEnumToStr,
  568. mAnd, mOr,
  569. mEqStr, mLeStr, mLtStr,
  570. mEqSet, mLeSet, mLtSet, mMulSet, mPlusSet, mMinusSet, mSymDiffSet,
  571. mConStrStr, mSlice,
  572. mDotDot, # this one is only necessary to give nice compile time warnings
  573. mFields, mFieldPairs, mOmpParFor,
  574. mAppendStrCh, mAppendStrStr, mAppendSeqElem,
  575. mInRange, mInSet, mRepr, mExit,
  576. mSetLengthStr, mSetLengthSeq,
  577. mIsPartOf, mAstToStr, mParallel,
  578. mSwap, mIsNil, mArrToSeq, mCopyStr, mCopyStrLast,
  579. mNewString, mNewStringOfCap, mParseBiggestFloat,
  580. mMove, mWasMoved,
  581. mReset,
  582. mArray, mOpenArray, mRange, mSet, mSeq, mOpt, mVarargs,
  583. mRef, mPtr, mVar, mDistinct, mVoid, mTuple,
  584. mOrdinal,
  585. mInt, mInt8, mInt16, mInt32, mInt64,
  586. mUInt, mUInt8, mUInt16, mUInt32, mUInt64,
  587. mFloat, mFloat32, mFloat64, mFloat128,
  588. mBool, mChar, mString, mCstring,
  589. mPointer, mEmptySet, mIntSetBaseType, mNil, mExpr, mStmt, mTypeDesc,
  590. mVoidType, mPNimrodNode, mShared, mGuarded, mLock, mSpawn, mDeepCopy,
  591. mIsMainModule, mCompileDate, mCompileTime, mProcCall,
  592. mCpuEndian, mHostOS, mHostCPU, mBuildOS, mBuildCPU, mAppType,
  593. mNaN, mInf, mNegInf,
  594. mCompileOption, mCompileOptionArg,
  595. mNLen, mNChild, mNSetChild, mNAdd, mNAddMultiple, mNDel,
  596. mNKind, mNSymKind,
  597. mNccValue, mNccInc, mNcsAdd, mNcsIncl, mNcsLen, mNcsAt,
  598. mNctPut, mNctLen, mNctGet, mNctHasNext, mNctNext,
  599. mNIntVal, mNFloatVal, mNSymbol, mNIdent, mNGetType, mNStrVal, mNSetIntVal,
  600. mNSetFloatVal, mNSetSymbol, mNSetIdent, mNSetType, mNSetStrVal, mNLineInfo,
  601. mNNewNimNode, mNCopyNimNode, mNCopyNimTree, mStrToIdent,
  602. mNBindSym, mLocals, mNCallSite,
  603. mEqIdent, mEqNimrodNode, mSameNodeType, mGetImpl, mNGenSym,
  604. mNHint, mNWarning, mNError,
  605. mInstantiationInfo, mGetTypeInfo,
  606. mNimvm, mIntDefine, mStrDefine, mRunnableExamples,
  607. mException, mBuiltinType, mSymOwner, mUncheckedArray, mGetImplTransf
  608. # things that we can evaluate safely at compile time, even if not asked for it:
  609. const
  610. ctfeWhitelist* = {mNone, mUnaryLt, mSucc,
  611. mPred, mInc, mDec, mOrd, mLengthOpenArray,
  612. mLengthStr, mLengthArray, mLengthSeq, mXLenStr, mXLenSeq,
  613. mArrGet, mArrPut, mAsgn,
  614. mIncl, mExcl, mCard, mChr,
  615. mAddI, mSubI, mMulI, mDivI, mModI,
  616. mAddF64, mSubF64, mMulF64, mDivF64,
  617. mShrI, mShlI, mBitandI, mBitorI, mBitxorI,
  618. mMinI, mMaxI,
  619. mMinF64, mMaxF64,
  620. mAddU, mSubU, mMulU, mDivU, mModU,
  621. mEqI, mLeI, mLtI,
  622. mEqF64, mLeF64, mLtF64,
  623. mLeU, mLtU,
  624. mLeU64, mLtU64,
  625. mEqEnum, mLeEnum, mLtEnum,
  626. mEqCh, mLeCh, mLtCh,
  627. mEqB, mLeB, mLtB,
  628. mEqRef, mEqProc, mEqUntracedRef, mLePtr, mLtPtr, mEqCString, mXor,
  629. mUnaryMinusI, mUnaryMinusI64, mAbsI, mNot, mUnaryPlusI, mBitnotI,
  630. mUnaryPlusF64, mUnaryMinusF64, mAbsF64,
  631. mZe8ToI, mZe8ToI64,
  632. mZe16ToI, mZe16ToI64,
  633. mZe32ToI64, mZeIToI64,
  634. mToU8, mToU16, mToU32,
  635. mToFloat, mToBiggestFloat,
  636. mToInt, mToBiggestInt,
  637. mCharToStr, mBoolToStr, mIntToStr, mInt64ToStr, mFloatToStr, mCStrToStr,
  638. mStrToStr, mEnumToStr,
  639. mAnd, mOr,
  640. mEqStr, mLeStr, mLtStr,
  641. mEqSet, mLeSet, mLtSet, mMulSet, mPlusSet, mMinusSet, mSymDiffSet,
  642. mConStrStr, mAppendStrCh, mAppendStrStr, mAppendSeqElem,
  643. mInRange, mInSet, mRepr,
  644. mCopyStr, mCopyStrLast}
  645. type
  646. PNode* = ref TNode
  647. TNodeSeq* = seq[PNode]
  648. PType* = ref TType
  649. PSym* = ref TSym
  650. TNode*{.final, acyclic.} = object # on a 32bit machine, this takes 32 bytes
  651. when defined(useNodeIds):
  652. id*: int
  653. typ*: PType
  654. info*: TLineInfo
  655. flags*: TNodeFlags
  656. case kind*: TNodeKind
  657. of nkCharLit..nkUInt64Lit:
  658. intVal*: BiggestInt
  659. of nkFloatLit..nkFloat128Lit:
  660. floatVal*: BiggestFloat
  661. of nkStrLit..nkTripleStrLit:
  662. strVal*: string
  663. of nkSym:
  664. sym*: PSym
  665. of nkIdent:
  666. ident*: PIdent
  667. else:
  668. sons*: TNodeSeq
  669. comment*: string
  670. TSymSeq* = seq[PSym]
  671. TStrTable* = object # a table[PIdent] of PSym
  672. counter*: int
  673. data*: TSymSeq
  674. # -------------- backend information -------------------------------
  675. TLocKind* = enum
  676. locNone, # no location
  677. locTemp, # temporary location
  678. locLocalVar, # location is a local variable
  679. locGlobalVar, # location is a global variable
  680. locParam, # location is a parameter
  681. locField, # location is a record field
  682. locExpr, # "location" is really an expression
  683. locProc, # location is a proc (an address of a procedure)
  684. locData, # location is a constant
  685. locCall, # location is a call expression
  686. locOther # location is something other
  687. TLocFlag* = enum
  688. lfIndirect, # backend introduced a pointer
  689. lfFullExternalName, # only used when 'conf.cmd == cmdPretty': Indicates
  690. # that the symbol has been imported via 'importc: "fullname"' and
  691. # no format string.
  692. lfNoDeepCopy, # no need for a deep copy
  693. lfNoDecl, # do not declare it in C
  694. lfDynamicLib, # link symbol to dynamic library
  695. lfExportLib, # export symbol for dynamic library generation
  696. lfHeader, # include header file for symbol
  697. lfImportCompilerProc, # ``importc`` of a compilerproc
  698. lfSingleUse # no location yet and will only be used once
  699. TStorageLoc* = enum
  700. OnUnknown, # location is unknown (stack, heap or static)
  701. OnStatic, # in a static section
  702. OnStack, # location is on hardware stack
  703. OnStackShadowDup, # location is on the stack but also replicated
  704. # on the shadow stack
  705. OnHeap # location is on heap or global
  706. # (reference counting needed)
  707. TLocFlags* = set[TLocFlag]
  708. TLoc* = object
  709. k*: TLocKind # kind of location
  710. storage*: TStorageLoc
  711. flags*: TLocFlags # location's flags
  712. lode*: PNode # Node where the location came from; can be faked
  713. r*: Rope # rope value of location (code generators)
  714. dup*: Rope # duplicated location for precise stack scans
  715. # ---------------- end of backend information ------------------------------
  716. TLibKind* = enum
  717. libHeader, libDynamic
  718. TLib* = object # also misused for headers!
  719. kind*: TLibKind
  720. generated*: bool # needed for the backends:
  721. isOverriden*: bool
  722. name*: Rope
  723. path*: PNode # can be a string literal!
  724. CompilesId* = int ## id that is used for the caching logic within
  725. ## ``system.compiles``. See the seminst module.
  726. TInstantiation* = object
  727. sym*: PSym
  728. concreteTypes*: seq[PType]
  729. compilesId*: CompilesId
  730. PInstantiation* = ref TInstantiation
  731. TScope* = object
  732. depthLevel*: int
  733. symbols*: TStrTable
  734. parent*: PScope
  735. PScope* = ref TScope
  736. PLib* = ref TLib
  737. TSym* {.acyclic.} = object of TIdObj
  738. # proc and type instantiations are cached in the generic symbol
  739. case kind*: TSymKind
  740. of skType, skGenericParam:
  741. typeInstCache*: seq[PType]
  742. of routineKinds:
  743. procInstCache*: seq[PInstantiation]
  744. gcUnsafetyReason*: PSym # for better error messages wrt gcsafe
  745. transformedBody*: PNode # cached body after transf pass
  746. of skModule, skPackage:
  747. # modules keep track of the generic symbols they use from other modules.
  748. # this is because in incremental compilation, when a module is about to
  749. # be replaced with a newer version, we must decrement the usage count
  750. # of all previously used generics.
  751. # For 'import as' we copy the module symbol but shallowCopy the 'tab'
  752. # and set the 'usedGenerics' to ... XXX gah! Better set module.name
  753. # instead? But this doesn't work either. --> We need an skModuleAlias?
  754. # No need, just leave it as skModule but set the owner accordingly and
  755. # check for the owner when touching 'usedGenerics'.
  756. usedGenerics*: seq[PInstantiation]
  757. tab*: TStrTable # interface table for modules
  758. of skLet, skVar, skField, skForVar:
  759. guard*: PSym
  760. bitsize*: int
  761. else: nil
  762. magic*: TMagic
  763. typ*: PType
  764. name*: PIdent
  765. info*: TLineInfo
  766. owner*: PSym
  767. flags*: TSymFlags
  768. ast*: PNode # syntax tree of proc, iterator, etc.:
  769. # the whole proc including header; this is used
  770. # for easy generation of proper error messages
  771. # for variant record fields the discriminant
  772. # expression
  773. # for modules, it's a placeholder for compiler
  774. # generated code that will be appended to the
  775. # module after the sem pass (see appendToModule)
  776. options*: TOptions
  777. position*: int # used for many different things:
  778. # for enum fields its position;
  779. # for fields its offset
  780. # for parameters its position
  781. # for a conditional:
  782. # 1 iff the symbol is defined, else 0
  783. # (or not in symbol table)
  784. # for modules, an unique index corresponding
  785. # to the module's fileIdx
  786. # for variables a slot index for the evaluator
  787. # for routines a superop-ID
  788. offset*: int # offset of record field
  789. loc*: TLoc
  790. annex*: PLib # additional fields (seldom used, so we use a
  791. # reference to another object to safe space)
  792. constraint*: PNode # additional constraints like 'lit|result'; also
  793. # misused for the codegenDecl pragma in the hope
  794. # it won't cause problems
  795. # for skModule the string literal to output for
  796. # deprecated modules.
  797. when defined(nimsuggest):
  798. allUsages*: seq[TLineInfo]
  799. TTypeSeq* = seq[PType]
  800. TLockLevel* = distinct int16
  801. TType* {.acyclic.} = object of TIdObj # \
  802. # types are identical iff they have the
  803. # same id; there may be multiple copies of a type
  804. # in memory!
  805. kind*: TTypeKind # kind of type
  806. callConv*: TCallingConvention # for procs
  807. flags*: TTypeFlags # flags of the type
  808. sons*: TTypeSeq # base types, etc.
  809. n*: PNode # node for types:
  810. # for range types a nkRange node
  811. # for record types a nkRecord node
  812. # for enum types a list of symbols
  813. # for tyInt it can be the int literal
  814. # for procs and tyGenericBody, it's the
  815. # formal param list
  816. # for concepts, the concept body
  817. # else: unused
  818. owner*: PSym # the 'owner' of the type
  819. sym*: PSym # types have the sym associated with them
  820. # it is used for converting types to strings
  821. destructor*: PSym # destructor. warning: nil here may not necessary
  822. # mean that there is no destructor.
  823. # see instantiateDestructor in semdestruct.nim
  824. deepCopy*: PSym # overriden 'deepCopy' operation
  825. assignment*: PSym # overriden '=' operation
  826. sink*: PSym # overriden '=sink' operation
  827. methods*: seq[(int,PSym)] # attached methods
  828. size*: BiggestInt # the size of the type in bytes
  829. # -1 means that the size is unkwown
  830. align*: int16 # the type's alignment requirements
  831. lockLevel*: TLockLevel # lock level as required for deadlock checking
  832. loc*: TLoc
  833. typeInst*: PType # for generic instantiations the tyGenericInst that led to this
  834. # type.
  835. TPair* = object
  836. key*, val*: RootRef
  837. TPairSeq* = seq[TPair]
  838. TIdPair* = object
  839. key*: PIdObj
  840. val*: RootRef
  841. TIdPairSeq* = seq[TIdPair]
  842. TIdTable* = object # the same as table[PIdent] of PObject
  843. counter*: int
  844. data*: TIdPairSeq
  845. TIdNodePair* = object
  846. key*: PIdObj
  847. val*: PNode
  848. TIdNodePairSeq* = seq[TIdNodePair]
  849. TIdNodeTable* = object # the same as table[PIdObj] of PNode
  850. counter*: int
  851. data*: TIdNodePairSeq
  852. TNodePair* = object
  853. h*: Hash # because it is expensive to compute!
  854. key*: PNode
  855. val*: int
  856. TNodePairSeq* = seq[TNodePair]
  857. TNodeTable* = object # the same as table[PNode] of int;
  858. # nodes are compared by structure!
  859. counter*: int
  860. data*: TNodePairSeq
  861. TObjectSeq* = seq[RootRef]
  862. TObjectSet* = object
  863. counter*: int
  864. data*: TObjectSeq
  865. TImplication* = enum
  866. impUnknown, impNo, impYes
  867. # BUGFIX: a module is overloadable so that a proc can have the
  868. # same name as an imported module. This is necessary because of
  869. # the poor naming choices in the standard library.
  870. const
  871. OverloadableSyms* = {skProc, skFunc, skMethod, skIterator,
  872. skConverter, skModule, skTemplate, skMacro}
  873. GenericTypes*: TTypeKinds = {tyGenericInvocation, tyGenericBody,
  874. tyGenericParam}
  875. StructuralEquivTypes*: TTypeKinds = {tyNil, tyTuple, tyArray,
  876. tySet, tyRange, tyPtr, tyRef, tyVar, tyLent, tySequence, tyProc, tyOpenArray,
  877. tyVarargs}
  878. ConcreteTypes*: TTypeKinds = { # types of the expr that may occur in::
  879. # var x = expr
  880. tyBool, tyChar, tyEnum, tyArray, tyObject,
  881. tySet, tyTuple, tyRange, tyPtr, tyRef, tyVar, tyLent, tySequence, tyProc,
  882. tyPointer,
  883. tyOpenArray, tyString, tyCString, tyInt..tyInt64, tyFloat..tyFloat128,
  884. tyUInt..tyUInt64}
  885. IntegralTypes* = {tyBool, tyChar, tyEnum, tyInt..tyInt64,
  886. tyFloat..tyFloat128, tyUInt..tyUInt64}
  887. ConstantDataTypes*: TTypeKinds = {tyArray, tySet,
  888. tyTuple, tySequence}
  889. NilableTypes*: TTypeKinds = {tyPointer, tyCString, tyRef, tyPtr,
  890. tyProc, tyError}
  891. ExportableSymKinds* = {skVar, skConst, skProc, skFunc, skMethod, skType,
  892. skIterator,
  893. skMacro, skTemplate, skConverter, skEnumField, skLet, skStub, skAlias}
  894. PersistentNodeFlags*: TNodeFlags = {nfBase2, nfBase8, nfBase16,
  895. nfDotSetter, nfDotField,
  896. nfIsRef, nfPreventCg, nfLL,
  897. nfFromTemplate, nfDefaultRefsParam}
  898. namePos* = 0
  899. patternPos* = 1 # empty except for term rewriting macros
  900. genericParamsPos* = 2
  901. paramsPos* = 3
  902. pragmasPos* = 4
  903. miscPos* = 5 # used for undocumented and hacky stuff
  904. bodyPos* = 6 # position of body; use rodread.getBody() instead!
  905. resultPos* = 7
  906. dispatcherPos* = 8 # caution: if method has no 'result' it can be position 7!
  907. nkCallKinds* = {nkCall, nkInfix, nkPrefix, nkPostfix,
  908. nkCommand, nkCallStrLit, nkHiddenCallConv}
  909. nkIdentKinds* = {nkIdent, nkSym, nkAccQuoted, nkOpenSymChoice,
  910. nkClosedSymChoice}
  911. nkPragmaCallKinds* = {nkExprColonExpr, nkCall, nkCallStrLit}
  912. nkLiterals* = {nkCharLit..nkTripleStrLit}
  913. nkFloatLiterals* = {nkFloatLit..nkFloat128Lit}
  914. nkLambdaKinds* = {nkLambda, nkDo}
  915. declarativeDefs* = {nkProcDef, nkFuncDef, nkMethodDef, nkIteratorDef, nkConverterDef}
  916. procDefs* = nkLambdaKinds + declarativeDefs
  917. nkSymChoices* = {nkClosedSymChoice, nkOpenSymChoice}
  918. nkStrKinds* = {nkStrLit..nkTripleStrLit}
  919. skLocalVars* = {skVar, skLet, skForVar, skParam, skResult}
  920. skProcKinds* = {skProc, skFunc, skTemplate, skMacro, skIterator,
  921. skMethod, skConverter}
  922. var ggDebug* {.deprecated.}: bool ## convenience switch for trying out things
  923. #var
  924. # gMainPackageId*: int
  925. proc isCallExpr*(n: PNode): bool =
  926. result = n.kind in nkCallKinds
  927. proc discardSons*(father: PNode)
  928. proc len*(n: PNode): int {.inline.} =
  929. when defined(nimNoNilSeqs):
  930. result = len(n.sons)
  931. else:
  932. if isNil(n.sons): result = 0
  933. else: result = len(n.sons)
  934. proc safeLen*(n: PNode): int {.inline.} =
  935. ## works even for leaves.
  936. if n.kind in {nkNone..nkNilLit}: result = 0
  937. else: result = len(n)
  938. proc safeArrLen*(n: PNode): int {.inline.} =
  939. ## works for array-like objects (strings passed as openArray in VM).
  940. if n.kind in {nkStrLit..nkTripleStrLit}:result = len(n.strVal)
  941. elif n.kind in {nkNone..nkFloat128Lit}: result = 0
  942. else: result = len(n)
  943. proc add*(father, son: PNode) =
  944. assert son != nil
  945. when not defined(nimNoNilSeqs):
  946. if isNil(father.sons): father.sons = @[]
  947. add(father.sons, son)
  948. type Indexable = PNode | PType
  949. template `[]`*(n: Indexable, i: int): Indexable = n.sons[i]
  950. template `[]=`*(n: Indexable, i: int; x: Indexable) = n.sons[i] = x
  951. template `[]`*(n: Indexable, i: BackwardsIndex): Indexable = n[n.len - i.int]
  952. template `[]=`*(n: Indexable, i: BackwardsIndex; x: Indexable) = n[n.len - i.int] = x
  953. when defined(useNodeIds):
  954. const nodeIdToDebug* = -1 # 299750 # 300761 #300863 # 300879
  955. var gNodeId: int
  956. proc newNode*(kind: TNodeKind): PNode =
  957. new(result)
  958. result.kind = kind
  959. #result.info = UnknownLineInfo() inlined:
  960. result.info.fileIndex = InvalidFileIdx
  961. result.info.col = int16(-1)
  962. result.info.line = uint16(0)
  963. when defined(useNodeIds):
  964. result.id = gNodeId
  965. if result.id == nodeIdToDebug:
  966. echo "KIND ", result.kind
  967. writeStackTrace()
  968. inc gNodeId
  969. proc newTree*(kind: TNodeKind; children: varargs[PNode]): PNode =
  970. result = newNode(kind)
  971. if children.len > 0:
  972. result.info = children[0].info
  973. result.sons = @children
  974. template previouslyInferred*(t: PType): PType =
  975. if t.sons.len > 1: t.lastSon else: nil
  976. proc newSym*(symKind: TSymKind, name: PIdent, owner: PSym,
  977. info: TLineInfo; options: TOptions = {}): PSym =
  978. # generates a symbol and initializes the hash field too
  979. new(result)
  980. result.name = name
  981. result.kind = symKind
  982. result.flags = {}
  983. result.info = info
  984. result.options = options
  985. result.owner = owner
  986. result.offset = -1
  987. result.id = getID()
  988. when debugIds:
  989. registerId(result)
  990. #if result.id == 77131:
  991. # writeStacktrace()
  992. # echo name.s
  993. proc isMetaType*(t: PType): bool =
  994. return t.kind in tyMetaTypes or
  995. (t.kind == tyStatic and t.n == nil) or
  996. tfHasMeta in t.flags
  997. proc isUnresolvedStatic*(t: PType): bool =
  998. return t.kind == tyStatic and t.n == nil
  999. proc linkTo*(t: PType, s: PSym): PType {.discardable.} =
  1000. t.sym = s
  1001. s.typ = t
  1002. result = t
  1003. proc linkTo*(s: PSym, t: PType): PSym {.discardable.} =
  1004. t.sym = s
  1005. s.typ = t
  1006. result = s
  1007. template fileIdx*(c: PSym): FileIndex =
  1008. # XXX: this should be used only on module symbols
  1009. c.position.FileIndex
  1010. template filename*(c: PSym): string =
  1011. # XXX: this should be used only on module symbols
  1012. c.position.FileIndex.toFilename
  1013. proc appendToModule*(m: PSym, n: PNode) =
  1014. ## The compiler will use this internally to add nodes that will be
  1015. ## appended to the module after the sem pass
  1016. if m.ast == nil:
  1017. m.ast = newNode(nkStmtList)
  1018. m.ast.sons = @[n]
  1019. else:
  1020. assert m.ast.kind == nkStmtList
  1021. m.ast.sons.add(n)
  1022. const # for all kind of hash tables:
  1023. GrowthFactor* = 2 # must be power of 2, > 0
  1024. StartSize* = 8 # must be power of 2, > 0
  1025. proc copyStrTable*(dest: var TStrTable, src: TStrTable) =
  1026. dest.counter = src.counter
  1027. setLen(dest.data, len(src.data))
  1028. for i in countup(0, high(src.data)): dest.data[i] = src.data[i]
  1029. proc copyIdTable*(dest: var TIdTable, src: TIdTable) =
  1030. dest.counter = src.counter
  1031. newSeq(dest.data, len(src.data))
  1032. for i in countup(0, high(src.data)): dest.data[i] = src.data[i]
  1033. proc copyObjectSet*(dest: var TObjectSet, src: TObjectSet) =
  1034. dest.counter = src.counter
  1035. setLen(dest.data, len(src.data))
  1036. for i in countup(0, high(src.data)): dest.data[i] = src.data[i]
  1037. proc discardSons*(father: PNode) =
  1038. when defined(nimNoNilSeqs):
  1039. father.sons = @[]
  1040. else:
  1041. father.sons = nil
  1042. proc withInfo*(n: PNode, info: TLineInfo): PNode =
  1043. n.info = info
  1044. return n
  1045. proc newIdentNode*(ident: PIdent, info: TLineInfo): PNode =
  1046. result = newNode(nkIdent)
  1047. result.ident = ident
  1048. result.info = info
  1049. proc newSymNode*(sym: PSym): PNode =
  1050. result = newNode(nkSym)
  1051. result.sym = sym
  1052. result.typ = sym.typ
  1053. result.info = sym.info
  1054. proc newSymNode*(sym: PSym, info: TLineInfo): PNode =
  1055. result = newNode(nkSym)
  1056. result.sym = sym
  1057. result.typ = sym.typ
  1058. result.info = info
  1059. proc newNodeI*(kind: TNodeKind, info: TLineInfo): PNode =
  1060. new(result)
  1061. result.kind = kind
  1062. result.info = info
  1063. when defined(useNodeIds):
  1064. result.id = gNodeId
  1065. if result.id == nodeIdToDebug:
  1066. echo "KIND ", result.kind
  1067. writeStackTrace()
  1068. inc gNodeId
  1069. proc newNodeI*(kind: TNodeKind, info: TLineInfo, children: int): PNode =
  1070. new(result)
  1071. result.kind = kind
  1072. result.info = info
  1073. if children > 0:
  1074. newSeq(result.sons, children)
  1075. when defined(useNodeIds):
  1076. result.id = gNodeId
  1077. if result.id == nodeIdToDebug:
  1078. echo "KIND ", result.kind
  1079. writeStackTrace()
  1080. inc gNodeId
  1081. proc newNode*(kind: TNodeKind, info: TLineInfo, sons: TNodeSeq = @[],
  1082. typ: PType = nil): PNode =
  1083. new(result)
  1084. result.kind = kind
  1085. result.info = info
  1086. result.typ = typ
  1087. # XXX use shallowCopy here for ownership transfer:
  1088. result.sons = sons
  1089. when defined(useNodeIds):
  1090. result.id = gNodeId
  1091. if result.id == nodeIdToDebug:
  1092. echo "KIND ", result.kind
  1093. writeStackTrace()
  1094. inc gNodeId
  1095. proc newNodeIT*(kind: TNodeKind, info: TLineInfo, typ: PType): PNode =
  1096. result = newNode(kind)
  1097. result.info = info
  1098. result.typ = typ
  1099. proc newIntNode*(kind: TNodeKind, intVal: BiggestInt): PNode =
  1100. result = newNode(kind)
  1101. result.intVal = intVal
  1102. proc newIntTypeNode*(kind: TNodeKind, intVal: BiggestInt, typ: PType): PNode =
  1103. result = newIntNode(kind, intVal)
  1104. result.typ = typ
  1105. proc newFloatNode*(kind: TNodeKind, floatVal: BiggestFloat): PNode =
  1106. result = newNode(kind)
  1107. result.floatVal = floatVal
  1108. proc newStrNode*(kind: TNodeKind, strVal: string): PNode =
  1109. result = newNode(kind)
  1110. result.strVal = strVal
  1111. proc newStrNode*(strVal: string; info: TLineInfo): PNode =
  1112. result = newNodeI(nkStrLit, info)
  1113. result.strVal = strVal
  1114. proc addSon*(father, son: PNode) =
  1115. assert son != nil
  1116. when not defined(nimNoNilSeqs):
  1117. if isNil(father.sons): father.sons = @[]
  1118. add(father.sons, son)
  1119. proc newProcNode*(kind: TNodeKind, info: TLineInfo, body: PNode,
  1120. params,
  1121. name, pattern, genericParams,
  1122. pragmas, exceptions: PNode): PNode =
  1123. result = newNodeI(kind, info)
  1124. result.sons = @[name, pattern, genericParams, params,
  1125. pragmas, exceptions, body]
  1126. const
  1127. UnspecifiedLockLevel* = TLockLevel(-1'i16)
  1128. MaxLockLevel* = 1000'i16
  1129. UnknownLockLevel* = TLockLevel(1001'i16)
  1130. proc `$`*(x: TLockLevel): string =
  1131. if x.ord == UnspecifiedLockLevel.ord: result = "<unspecified>"
  1132. elif x.ord == UnknownLockLevel.ord: result = "<unknown>"
  1133. else: result = $int16(x)
  1134. proc newType*(kind: TTypeKind, owner: PSym): PType =
  1135. new(result)
  1136. result.kind = kind
  1137. result.owner = owner
  1138. result.size = -1
  1139. result.align = -1 # default alignment
  1140. result.id = getID()
  1141. result.lockLevel = UnspecifiedLockLevel
  1142. when debugIds:
  1143. registerId(result)
  1144. when false:
  1145. if result.id == 76426:
  1146. echo "KNID ", kind
  1147. writeStackTrace()
  1148. proc mergeLoc(a: var TLoc, b: TLoc) =
  1149. if a.k == low(a.k): a.k = b.k
  1150. if a.storage == low(a.storage): a.storage = b.storage
  1151. a.flags = a.flags + b.flags
  1152. if a.lode == nil: a.lode = b.lode
  1153. if a.r == nil: a.r = b.r
  1154. proc newSons*(father: PNode, length: int) =
  1155. when defined(nimNoNilSeqs):
  1156. setLen(father.sons, length)
  1157. else:
  1158. if isNil(father.sons):
  1159. newSeq(father.sons, length)
  1160. else:
  1161. setLen(father.sons, length)
  1162. proc newSons*(father: PType, length: int) =
  1163. when defined(nimNoNilSeqs):
  1164. setLen(father.sons, length)
  1165. else:
  1166. if isNil(father.sons):
  1167. newSeq(father.sons, length)
  1168. else:
  1169. setLen(father.sons, length)
  1170. proc sonsLen*(n: PType): int = n.sons.len
  1171. proc len*(n: PType): int = n.sons.len
  1172. proc sonsLen*(n: PNode): int = n.sons.len
  1173. proc lastSon*(n: PNode): PNode = n.sons[^1]
  1174. proc lastSon*(n: PType): PType = n.sons[^1]
  1175. proc assignType*(dest, src: PType) =
  1176. dest.kind = src.kind
  1177. dest.flags = src.flags
  1178. dest.callConv = src.callConv
  1179. dest.n = src.n
  1180. dest.size = src.size
  1181. dest.align = src.align
  1182. dest.destructor = src.destructor
  1183. dest.deepCopy = src.deepCopy
  1184. dest.sink = src.sink
  1185. dest.assignment = src.assignment
  1186. dest.lockLevel = src.lockLevel
  1187. # this fixes 'type TLock = TSysLock':
  1188. if src.sym != nil:
  1189. if dest.sym != nil:
  1190. dest.sym.flags = dest.sym.flags + (src.sym.flags-{sfExported})
  1191. if dest.sym.annex == nil: dest.sym.annex = src.sym.annex
  1192. mergeLoc(dest.sym.loc, src.sym.loc)
  1193. else:
  1194. dest.sym = src.sym
  1195. newSons(dest, sonsLen(src))
  1196. for i in countup(0, sonsLen(src) - 1): dest.sons[i] = src.sons[i]
  1197. proc copyType*(t: PType, owner: PSym, keepId: bool): PType =
  1198. result = newType(t.kind, owner)
  1199. assignType(result, t)
  1200. if keepId:
  1201. result.id = t.id
  1202. else:
  1203. when debugIds: registerId(result)
  1204. result.sym = t.sym # backend-info should not be copied
  1205. proc exactReplica*(t: PType): PType = copyType(t, t.owner, true)
  1206. proc copySym*(s: PSym, keepId: bool = false): PSym =
  1207. result = newSym(s.kind, s.name, s.owner, s.info, s.options)
  1208. #result.ast = nil # BUGFIX; was: s.ast which made problems
  1209. result.typ = s.typ
  1210. if keepId:
  1211. result.id = s.id
  1212. else:
  1213. result.id = getID()
  1214. when debugIds: registerId(result)
  1215. result.flags = s.flags
  1216. result.magic = s.magic
  1217. if s.kind == skModule:
  1218. copyStrTable(result.tab, s.tab)
  1219. result.options = s.options
  1220. result.position = s.position
  1221. result.loc = s.loc
  1222. result.annex = s.annex # BUGFIX
  1223. if result.kind in {skVar, skLet, skField}:
  1224. result.guard = s.guard
  1225. proc createModuleAlias*(s: PSym, newIdent: PIdent, info: TLineInfo;
  1226. options: TOptions): PSym =
  1227. result = newSym(s.kind, newIdent, s.owner, info, options)
  1228. # keep ID!
  1229. result.ast = s.ast
  1230. result.id = s.id
  1231. result.flags = s.flags
  1232. system.shallowCopy(result.tab, s.tab)
  1233. result.options = s.options
  1234. result.position = s.position
  1235. result.loc = s.loc
  1236. result.annex = s.annex
  1237. # XXX once usedGenerics is used, ensure module aliases keep working!
  1238. assert s.usedGenerics.len == 0
  1239. proc initStrTable*(x: var TStrTable) =
  1240. x.counter = 0
  1241. newSeq(x.data, StartSize)
  1242. proc newStrTable*: TStrTable =
  1243. initStrTable(result)
  1244. proc initIdTable*(x: var TIdTable) =
  1245. x.counter = 0
  1246. newSeq(x.data, StartSize)
  1247. proc newIdTable*: TIdTable =
  1248. initIdTable(result)
  1249. proc resetIdTable*(x: var TIdTable) =
  1250. x.counter = 0
  1251. # clear and set to old initial size:
  1252. setLen(x.data, 0)
  1253. setLen(x.data, StartSize)
  1254. proc initObjectSet*(x: var TObjectSet) =
  1255. x.counter = 0
  1256. newSeq(x.data, StartSize)
  1257. proc initIdNodeTable*(x: var TIdNodeTable) =
  1258. x.counter = 0
  1259. newSeq(x.data, StartSize)
  1260. proc initNodeTable*(x: var TNodeTable) =
  1261. x.counter = 0
  1262. newSeq(x.data, StartSize)
  1263. proc skipTypes*(t: PType, kinds: TTypeKinds): PType =
  1264. ## Used throughout the compiler code to test whether a type tree contains or
  1265. ## doesn't contain a specific type/types - it is often the case that only the
  1266. ## last child nodes of a type tree need to be searched. This is a really hot
  1267. ## path within the compiler!
  1268. result = t
  1269. while result.kind in kinds: result = lastSon(result)
  1270. proc skipTypes*(t: PType, kinds: TTypeKinds; maxIters: int): PType =
  1271. result = t
  1272. var i = maxIters
  1273. while result.kind in kinds:
  1274. result = lastSon(result)
  1275. dec i
  1276. if i == 0: return nil
  1277. proc skipTypesOrNil*(t: PType, kinds: TTypeKinds): PType =
  1278. ## same as skipTypes but handles 'nil'
  1279. result = t
  1280. while result != nil and result.kind in kinds:
  1281. if result.len == 0: return nil
  1282. result = lastSon(result)
  1283. proc isGCedMem*(t: PType): bool {.inline.} =
  1284. result = t.kind in {tyString, tyRef, tySequence} or
  1285. t.kind == tyProc and t.callConv == ccClosure
  1286. proc propagateToOwner*(owner, elem: PType) =
  1287. const HaveTheirOwnEmpty = {tySequence, tyOpt, tySet, tyPtr, tyRef, tyProc}
  1288. owner.flags = owner.flags + (elem.flags * {tfHasMeta, tfTriggersCompileTime})
  1289. if tfNotNil in elem.flags:
  1290. if owner.kind in {tyGenericInst, tyGenericBody, tyGenericInvocation}:
  1291. owner.flags.incl tfNotNil
  1292. elif owner.kind notin HaveTheirOwnEmpty:
  1293. owner.flags.incl tfNeedsInit
  1294. if tfNeedsInit in elem.flags:
  1295. if owner.kind in HaveTheirOwnEmpty: discard
  1296. else: owner.flags.incl tfNeedsInit
  1297. if elem.isMetaType:
  1298. owner.flags.incl tfHasMeta
  1299. if tfHasAsgn in elem.flags:
  1300. let o2 = owner.skipTypes({tyGenericInst, tyAlias, tySink})
  1301. if o2.kind in {tyTuple, tyObject, tyArray,
  1302. tySequence, tyOpt, tySet, tyDistinct}:
  1303. o2.flags.incl tfHasAsgn
  1304. owner.flags.incl tfHasAsgn
  1305. if owner.kind notin {tyProc, tyGenericInst, tyGenericBody,
  1306. tyGenericInvocation, tyPtr}:
  1307. let elemB = elem.skipTypes({tyGenericInst, tyAlias, tySink})
  1308. if elemB.isGCedMem or tfHasGCedMem in elemB.flags:
  1309. # for simplicity, we propagate this flag even to generics. We then
  1310. # ensure this doesn't bite us in sempass2.
  1311. owner.flags.incl tfHasGCedMem
  1312. proc rawAddSon*(father, son: PType) =
  1313. when not defined(nimNoNilSeqs):
  1314. if isNil(father.sons): father.sons = @[]
  1315. add(father.sons, son)
  1316. if not son.isNil: propagateToOwner(father, son)
  1317. proc rawAddSonNoPropagationOfTypeFlags*(father, son: PType) =
  1318. when not defined(nimNoNilSeqs):
  1319. if isNil(father.sons): father.sons = @[]
  1320. add(father.sons, son)
  1321. proc addSonNilAllowed*(father, son: PNode) =
  1322. when not defined(nimNoNilSeqs):
  1323. if isNil(father.sons): father.sons = @[]
  1324. add(father.sons, son)
  1325. proc delSon*(father: PNode, idx: int) =
  1326. when defined(nimNoNilSeqs):
  1327. if father.len == 0: return
  1328. else:
  1329. if isNil(father.sons): return
  1330. var length = sonsLen(father)
  1331. for i in countup(idx, length - 2): father.sons[i] = father.sons[i + 1]
  1332. setLen(father.sons, length - 1)
  1333. proc copyNode*(src: PNode): PNode =
  1334. # does not copy its sons!
  1335. if src == nil:
  1336. return nil
  1337. result = newNode(src.kind)
  1338. result.info = src.info
  1339. result.typ = src.typ
  1340. result.flags = src.flags * PersistentNodeFlags
  1341. result.comment = src.comment
  1342. when defined(useNodeIds):
  1343. if result.id == nodeIdToDebug:
  1344. echo "COMES FROM ", src.id
  1345. case src.kind
  1346. of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
  1347. of nkFloatLiterals: result.floatVal = src.floatVal
  1348. of nkSym: result.sym = src.sym
  1349. of nkIdent: result.ident = src.ident
  1350. of nkStrLit..nkTripleStrLit: result.strVal = src.strVal
  1351. else: discard
  1352. proc shallowCopy*(src: PNode): PNode =
  1353. # does not copy its sons, but provides space for them:
  1354. if src == nil: return nil
  1355. result = newNode(src.kind)
  1356. result.info = src.info
  1357. result.typ = src.typ
  1358. result.flags = src.flags * PersistentNodeFlags
  1359. result.comment = src.comment
  1360. when defined(useNodeIds):
  1361. if result.id == nodeIdToDebug:
  1362. echo "COMES FROM ", src.id
  1363. case src.kind
  1364. of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
  1365. of nkFloatLiterals: result.floatVal = src.floatVal
  1366. of nkSym: result.sym = src.sym
  1367. of nkIdent: result.ident = src.ident
  1368. of nkStrLit..nkTripleStrLit: result.strVal = src.strVal
  1369. else: newSeq(result.sons, sonsLen(src))
  1370. proc copyTree*(src: PNode): PNode =
  1371. # copy a whole syntax tree; performs deep copying
  1372. if src == nil:
  1373. return nil
  1374. result = newNode(src.kind)
  1375. result.info = src.info
  1376. result.typ = src.typ
  1377. result.flags = src.flags * PersistentNodeFlags
  1378. result.comment = src.comment
  1379. when defined(useNodeIds):
  1380. if result.id == nodeIdToDebug:
  1381. echo "COMES FROM ", src.id
  1382. case src.kind
  1383. of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
  1384. of nkFloatLiterals: result.floatVal = src.floatVal
  1385. of nkSym: result.sym = src.sym
  1386. of nkIdent: result.ident = src.ident
  1387. of nkStrLit..nkTripleStrLit: result.strVal = src.strVal
  1388. else:
  1389. newSeq(result.sons, sonsLen(src))
  1390. for i in countup(0, sonsLen(src) - 1):
  1391. result.sons[i] = copyTree(src.sons[i])
  1392. proc hasSonWith*(n: PNode, kind: TNodeKind): bool =
  1393. for i in countup(0, sonsLen(n) - 1):
  1394. if n.sons[i].kind == kind:
  1395. return true
  1396. result = false
  1397. proc hasNilSon*(n: PNode): bool =
  1398. for i in countup(0, safeLen(n) - 1):
  1399. if n.sons[i] == nil:
  1400. return true
  1401. elif hasNilSon(n.sons[i]):
  1402. return true
  1403. result = false
  1404. proc containsNode*(n: PNode, kinds: TNodeKinds): bool =
  1405. if n == nil: return
  1406. case n.kind
  1407. of nkEmpty..nkNilLit: result = n.kind in kinds
  1408. else:
  1409. for i in countup(0, sonsLen(n) - 1):
  1410. if n.kind in kinds or containsNode(n.sons[i], kinds): return true
  1411. proc hasSubnodeWith*(n: PNode, kind: TNodeKind): bool =
  1412. case n.kind
  1413. of nkEmpty..nkNilLit: result = n.kind == kind
  1414. else:
  1415. for i in countup(0, sonsLen(n) - 1):
  1416. if (n.sons[i].kind == kind) or hasSubnodeWith(n.sons[i], kind):
  1417. return true
  1418. result = false
  1419. proc getInt*(a: PNode): BiggestInt =
  1420. case a.kind
  1421. of nkCharLit..nkUInt64Lit: result = a.intVal
  1422. else:
  1423. raiseRecoverableError("cannot extract number from invalid AST node")
  1424. #internalError(a.info, "getInt")
  1425. #doAssert false, "getInt"
  1426. #result = 0
  1427. proc getFloat*(a: PNode): BiggestFloat =
  1428. case a.kind
  1429. of nkFloatLiterals: result = a.floatVal
  1430. else:
  1431. raiseRecoverableError("cannot extract number from invalid AST node")
  1432. #doAssert false, "getFloat"
  1433. #internalError(a.info, "getFloat")
  1434. #result = 0.0
  1435. proc getStr*(a: PNode): string =
  1436. case a.kind
  1437. of nkStrLit..nkTripleStrLit: result = a.strVal
  1438. of nkNilLit:
  1439. # let's hope this fixes more problems than it creates:
  1440. when defined(nimNoNilSeqs):
  1441. result = ""
  1442. else:
  1443. result = nil
  1444. else:
  1445. raiseRecoverableError("cannot extract string from invalid AST node")
  1446. #doAssert false, "getStr"
  1447. #internalError(a.info, "getStr")
  1448. #result = ""
  1449. proc getStrOrChar*(a: PNode): string =
  1450. case a.kind
  1451. of nkStrLit..nkTripleStrLit: result = a.strVal
  1452. of nkCharLit..nkUInt64Lit: result = $chr(int(a.intVal))
  1453. else:
  1454. raiseRecoverableError("cannot extract string from invalid AST node")
  1455. #doAssert false, "getStrOrChar"
  1456. #internalError(a.info, "getStrOrChar")
  1457. #result = ""
  1458. proc isGenericRoutine*(s: PSym): bool =
  1459. case s.kind
  1460. of skProcKinds:
  1461. result = sfFromGeneric in s.flags or
  1462. (s.ast != nil and s.ast[genericParamsPos].kind != nkEmpty)
  1463. else: discard
  1464. proc skipGenericOwner*(s: PSym): PSym =
  1465. ## Generic instantiations are owned by their originating generic
  1466. ## symbol. This proc skips such owners and goes straight to the owner
  1467. ## of the generic itself (the module or the enclosing proc).
  1468. result = if s.kind in skProcKinds and sfFromGeneric in s.flags:
  1469. s.owner.owner
  1470. else:
  1471. s.owner
  1472. proc originatingModule*(s: PSym): PSym =
  1473. result = s.owner
  1474. while result.kind != skModule: result = result.owner
  1475. proc isRoutine*(s: PSym): bool {.inline.} =
  1476. result = s.kind in skProcKinds
  1477. proc isCompileTimeProc*(s: PSym): bool {.inline.} =
  1478. result = s.kind == skMacro or
  1479. s.kind == skProc and sfCompileTime in s.flags
  1480. proc isRunnableExamples*(n: PNode): bool =
  1481. # Templates and generics don't perform symbol lookups.
  1482. result = n.kind == nkSym and n.sym.magic == mRunnableExamples or
  1483. n.kind == nkIdent and n.ident.s == "runnableExamples"
  1484. proc requiredParams*(s: PSym): int =
  1485. # Returns the number of required params (without default values)
  1486. # XXX: Perhaps we can store this in the `offset` field of the
  1487. # symbol instead?
  1488. for i in 1 ..< s.typ.len:
  1489. if s.typ.n[i].sym.ast != nil:
  1490. return i - 1
  1491. return s.typ.len - 1
  1492. proc hasPattern*(s: PSym): bool {.inline.} =
  1493. result = isRoutine(s) and s.ast.sons[patternPos].kind != nkEmpty
  1494. iterator items*(n: PNode): PNode =
  1495. for i in 0..<n.safeLen: yield n.sons[i]
  1496. iterator pairs*(n: PNode): tuple[i: int, n: PNode] =
  1497. for i in 0..<n.safeLen: yield (i, n.sons[i])
  1498. proc isAtom*(n: PNode): bool {.inline.} =
  1499. result = n.kind >= nkNone and n.kind <= nkNilLit
  1500. proc isEmptyType*(t: PType): bool {.inline.} =
  1501. ## 'void' and 'stmt' types are often equivalent to 'nil' these days:
  1502. result = t == nil or t.kind in {tyVoid, tyStmt}
  1503. proc makeStmtList*(n: PNode): PNode =
  1504. if n.kind == nkStmtList:
  1505. result = n
  1506. else:
  1507. result = newNodeI(nkStmtList, n.info)
  1508. result.add n
  1509. proc skipStmtList*(n: PNode): PNode =
  1510. if n.kind in {nkStmtList, nkStmtListExpr}:
  1511. for i in 0 .. n.len-2:
  1512. if n[i].kind notin {nkEmpty, nkCommentStmt}: return n
  1513. result = n.lastSon
  1514. else:
  1515. result = n
  1516. proc toVar*(typ: PType): PType =
  1517. ## If ``typ`` is not a tyVar then it is converted into a `var <typ>` and
  1518. ## returned. Otherwise ``typ`` is simply returned as-is.
  1519. result = typ
  1520. if typ.kind != tyVar:
  1521. result = newType(tyVar, typ.owner)
  1522. rawAddSon(result, typ)
  1523. proc toRef*(typ: PType): PType =
  1524. ## If ``typ`` is a tyObject then it is converted into a `ref <typ>` and
  1525. ## returned. Otherwise ``typ`` is simply returned as-is.
  1526. if typ.skipTypes({tyAlias, tyGenericInst}).kind == tyObject:
  1527. result = newType(tyRef, typ.owner)
  1528. rawAddSon(result, typ)
  1529. proc toObject*(typ: PType): PType =
  1530. ## If ``typ`` is a tyRef then its immediate son is returned (which in many
  1531. ## cases should be a ``tyObject``).
  1532. ## Otherwise ``typ`` is simply returned as-is.
  1533. let t = typ.skipTypes({tyAlias, tyGenericInst})
  1534. if t.kind == tyRef: t.lastSon
  1535. else: typ
  1536. proc isException*(t: PType): bool =
  1537. # check if `y` is object type and it inherits from Exception
  1538. assert(t != nil)
  1539. if t.kind notin {tyObject, tyGenericInst}:
  1540. return false
  1541. var base = t
  1542. while base != nil and base.kind in {tyObject, tyGenericInst}:
  1543. if base.sym != nil and base.sym.magic == mException:
  1544. return true
  1545. base = base.lastSon
  1546. return false
  1547. proc isImportedException*(t: PType; conf: ConfigRef): bool =
  1548. assert t != nil
  1549. if optNoCppExceptions in conf.globalOptions:
  1550. return false
  1551. let base = t.skipTypes({tyAlias, tyPtr, tyDistinct, tyGenericInst})
  1552. if base.sym != nil and {sfCompileToCpp, sfImportc} * base.sym.flags != {}:
  1553. result = true
  1554. proc isInfixAs*(n: PNode): bool =
  1555. return n.kind == nkInfix and n[0].kind == nkIdent and n[0].ident.s == "as"
  1556. proc findUnresolvedStatic*(n: PNode): PNode =
  1557. if n.kind == nkSym and n.typ.kind == tyStatic and n.typ.n == nil:
  1558. return n
  1559. for son in n:
  1560. let n = son.findUnresolvedStatic
  1561. if n != nil: return n
  1562. return nil
  1563. when false:
  1564. proc containsNil*(n: PNode): bool =
  1565. # only for debugging
  1566. if n.isNil: return true
  1567. for i in 0 ..< n.safeLen:
  1568. if n[i].containsNil: return true
  1569. template hasDestructor*(t: PType): bool = tfHasAsgn in t.flags
  1570. template incompleteType*(t: PType): bool =
  1571. t.sym != nil and {sfForward, sfNoForward} * t.sym.flags == {sfForward}
  1572. template typeCompleted*(s: PSym) =
  1573. incl s.flags, sfNoForward
  1574. template getBody*(s: PSym): PNode = s.ast[bodyPos]
  1575. template detailedInfo*(sym: PSym): string =
  1576. sym.name.s