ast.nim 72 KB

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