options.nim 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. import
  10. os, strutils, strtabs, sets, lineinfos, platform,
  11. prefixmatches, pathutils, nimpaths, tables
  12. from terminal import isatty
  13. from times import utc, fromUnix, local, getTime, format, DateTime
  14. from std/private/globs import nativeToUnixPath
  15. when defined(nimPreviewSlimSystem):
  16. import std/[syncio, assertions]
  17. const
  18. hasTinyCBackend* = defined(tinyc)
  19. useEffectSystem* = true
  20. useWriteTracking* = false
  21. hasFFI* = defined(nimHasLibFFI)
  22. copyrightYear* = "2023"
  23. nimEnableCovariance* = defined(nimEnableCovariance)
  24. type # please make sure we have under 32 options
  25. # (improves code efficiency a lot!)
  26. TOption* = enum # **keep binary compatible**
  27. optNone, optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck,
  28. optOverflowCheck, optRefCheck,
  29. optNaNCheck, optInfCheck, optStaticBoundsCheck, optStyleCheck,
  30. optAssert, optLineDir, optWarns, optHints,
  31. optOptimizeSpeed, optOptimizeSize,
  32. optStackTrace, # stack tracing support
  33. optStackTraceMsgs, # enable custom runtime msgs via `setFrameMsg`
  34. optLineTrace, # line tracing support (includes stack tracing)
  35. optByRef, # use pass by ref for objects
  36. # (for interfacing with C)
  37. optProfiler, # profiler turned on
  38. optImplicitStatic, # optimization: implicit at compile time
  39. # evaluation
  40. optTrMacros, # en/disable pattern matching
  41. optMemTracker,
  42. optSinkInference # 'sink T' inference
  43. optCursorInference
  44. optImportHidden
  45. optQuirky
  46. TOptions* = set[TOption]
  47. TGlobalOption* = enum
  48. gloptNone, optForceFullMake,
  49. optWasNimscript, # redundant with `cmdNimscript`, could be removed
  50. optListCmd, optCompileOnly, optNoLinking,
  51. optCDebug, # turn on debugging information
  52. optGenDynLib, # generate a dynamic library
  53. optGenStaticLib, # generate a static library
  54. optGenGuiApp, # generate a GUI application
  55. optGenScript, # generate a script file to compile the *.c files
  56. optGenCDeps, # generate a list of *.c files to be read by CMake
  57. optGenMapping, # generate a mapping file
  58. optRun, # run the compiled project
  59. optUseNimcache, # save artifacts (including binary) in $nimcache
  60. optStyleHint, # check that the names adhere to NEP-1
  61. optStyleError, # enforce that the names adhere to NEP-1
  62. optStyleUsages, # only enforce consistent **usages** of the symbol
  63. optSkipSystemConfigFile, # skip the system's cfg/nims config file
  64. optSkipProjConfigFile, # skip the project's cfg/nims config file
  65. optSkipUserConfigFile, # skip the users's cfg/nims config file
  66. optSkipParentConfigFiles, # skip parent dir's cfg/nims config files
  67. optNoMain, # do not generate a "main" proc
  68. optUseColors, # use colors for hints, warnings, and errors
  69. optThreads, # support for multi-threading
  70. optStdout, # output to stdout
  71. optThreadAnalysis, # thread analysis pass
  72. optTlsEmulation, # thread var emulation turned on
  73. optGenIndex # generate index file for documentation;
  74. optGenIndexOnly # generate only index file for documentation
  75. optNoImportdoc # disable loading external documentation files
  76. optEmbedOrigSrc # embed the original source in the generated code
  77. # also: generate header file
  78. optIdeDebug # idetools: debug mode
  79. optIdeTerse # idetools: use terse descriptions
  80. optExcessiveStackTrace # fully qualified module filenames
  81. optShowAllMismatches # show all overloading resolution candidates
  82. optWholeProject # for 'doc': output any dependency
  83. optDocInternal # generate documentation for non-exported symbols
  84. optMixedMode # true if some module triggered C++ codegen
  85. optDeclaredLocs # show declaration locations in messages
  86. optNoNimblePath
  87. optHotCodeReloading
  88. optDynlibOverrideAll
  89. optSeqDestructors # active if the implementation uses the new
  90. # string/seq implementation based on destructors
  91. optTinyRtti # active if we use the new "tiny RTTI"
  92. # implementation
  93. optOwnedRefs # active if the Nim compiler knows about 'owned'.
  94. optMultiMethods
  95. optBenchmarkVM # Enables cpuTime() in the VM
  96. optProduceAsm # produce assembler code
  97. optPanics # turn panics (sysFatal) into a process termination
  98. optSourcemap
  99. optProfileVM # enable VM profiler
  100. optEnableDeepCopy # ORC specific: enable 'deepcopy' for all types.
  101. optShowNonExportedFields # for documentation: show fields that are not exported
  102. optJsBigInt64 # use bigints for 64-bit integers in JS
  103. TGlobalOptions* = set[TGlobalOption]
  104. const
  105. harmlessOptions* = {optForceFullMake, optNoLinking, optRun, optUseColors, optStdout}
  106. genSubDir* = RelativeDir"nimcache"
  107. NimExt* = "nim"
  108. RodExt* = "rod"
  109. HtmlExt* = "html"
  110. JsonExt* = "json"
  111. TagsExt* = "tags"
  112. TexExt* = "tex"
  113. IniExt* = "ini"
  114. DefaultConfig* = RelativeFile"nim.cfg"
  115. DefaultConfigNims* = RelativeFile"config.nims"
  116. DocConfig* = RelativeFile"nimdoc.cfg"
  117. DocTexConfig* = RelativeFile"nimdoc.tex.cfg"
  118. htmldocsDir* = htmldocsDirname.RelativeDir
  119. docRootDefault* = "@default" # using `@` instead of `$` to avoid shell quoting complications
  120. oKeepVariableNames* = true
  121. spellSuggestSecretSauce* = -1
  122. type
  123. TBackend* = enum
  124. backendInvalid = "" # for parseEnum
  125. backendC = "c"
  126. backendCpp = "cpp"
  127. backendJs = "js"
  128. backendObjc = "objc"
  129. # backendNimscript = "nimscript" # this could actually work
  130. # backendLlvm = "llvm" # probably not well supported; was cmdCompileToLLVM
  131. Command* = enum ## Nim's commands
  132. cmdNone # not yet processed command
  133. cmdUnknown # command unmapped
  134. cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToJS
  135. cmdCrun # compile and run in nimache
  136. cmdTcc # run the project via TCC backend
  137. cmdCheck # semantic checking for whole project
  138. cmdParse # parse a single file (for debugging)
  139. cmdRod # .rod to some text representation (for debugging)
  140. cmdIdeTools # ide tools (e.g. nimsuggest)
  141. cmdNimscript # evaluate nimscript
  142. cmdDoc0
  143. cmdDoc # convert .nim doc comments to HTML
  144. cmdDoc2tex # convert .nim doc comments to LaTeX
  145. cmdRst2html # convert a reStructuredText file to HTML
  146. cmdRst2tex # convert a reStructuredText file to TeX
  147. cmdMd2html # convert a Markdown file to HTML
  148. cmdMd2tex # convert a Markdown file to TeX
  149. cmdJsondoc0
  150. cmdJsondoc
  151. cmdCtags
  152. cmdBuildindex
  153. cmdGendepend
  154. cmdDump
  155. cmdInteractive # start interactive session
  156. cmdNop
  157. cmdJsonscript # compile a .json build file
  158. # old unused: cmdInterpret, cmdDef: def feature (find definition for IDEs)
  159. const
  160. cmdBackends* = {cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToJS, cmdCrun}
  161. cmdDocLike* = {cmdDoc0, cmdDoc, cmdDoc2tex, cmdJsondoc0, cmdJsondoc,
  162. cmdCtags, cmdBuildindex}
  163. type
  164. NimVer* = tuple[major: int, minor: int, patch: int]
  165. TStringSeq* = seq[string]
  166. TGCMode* = enum # the selected GC
  167. gcUnselected = "unselected"
  168. gcNone = "none"
  169. gcBoehm = "boehm"
  170. gcRegions = "regions"
  171. gcArc = "arc"
  172. gcOrc = "orc"
  173. gcAtomicArc = "atomicArc"
  174. gcMarkAndSweep = "markAndSweep"
  175. gcHooks = "hooks"
  176. gcRefc = "refc"
  177. gcGo = "go"
  178. # gcRefc and the GCs that follow it use a write barrier,
  179. # as far as usesWriteBarrier() is concerned
  180. IdeCmd* = enum
  181. ideNone, ideSug, ideCon, ideDef, ideUse, ideDus, ideChk, ideChkFile, ideMod,
  182. ideHighlight, ideOutline, ideKnown, ideMsg, ideProject, ideGlobalSymbols,
  183. ideRecompile, ideChanged, ideType, ideDeclaration, ideExpand
  184. Feature* = enum ## experimental features; DO NOT RENAME THESE!
  185. dotOperators,
  186. callOperator,
  187. parallel,
  188. destructor,
  189. notnil,
  190. dynamicBindSym,
  191. forLoopMacros, # not experimental anymore; remains here for backwards compatibility
  192. caseStmtMacros, # ditto
  193. codeReordering,
  194. compiletimeFFI,
  195. ## This requires building nim with `-d:nimHasLibFFI`
  196. ## which itself requires `koch installdeps libffi`, see #10150
  197. ## Note: this feature can't be localized with {.push.}
  198. vmopsDanger,
  199. strictFuncs,
  200. views,
  201. strictNotNil,
  202. overloadableEnums, # deadcode
  203. strictEffects,
  204. unicodeOperators, # deadcode
  205. flexibleOptionalParams,
  206. strictDefs,
  207. strictCaseObjects,
  208. inferGenericTypes
  209. LegacyFeature* = enum
  210. allowSemcheckedAstModification,
  211. ## Allows to modify a NimNode where the type has already been
  212. ## flagged with nfSem. If you actually do this, it will cause
  213. ## bugs.
  214. checkUnsignedConversions
  215. ## Historically and especially in version 1.0.0 of the language
  216. ## conversions to unsigned numbers were checked. In 1.0.4 they
  217. ## are not anymore.
  218. laxEffects
  219. ## Lax effects system prior to Nim 2.0.
  220. verboseTypeMismatch
  221. emitGenerics
  222. ## generics are emitted in the module that contains them.
  223. ## Useful for libraries that rely on local passC
  224. SymbolFilesOption* = enum
  225. disabledSf, writeOnlySf, readOnlySf, v2Sf, stressTest
  226. TSystemCC* = enum
  227. ccNone, ccGcc, ccNintendoSwitch, ccLLVM_Gcc, ccCLang, ccBcc, ccVcc,
  228. ccTcc, ccEnv, ccIcl, ccIcc, ccClangCl
  229. ExceptionSystem* = enum
  230. excNone, # no exception system selected yet
  231. excSetjmp, # setjmp based exception handling
  232. excCpp, # use C++'s native exception handling
  233. excGoto, # exception handling based on goto (should become the new default for C)
  234. excQuirky # quirky exception handling
  235. CfileFlag* {.pure.} = enum
  236. Cached, ## no need to recompile this time
  237. External ## file was introduced via .compile pragma
  238. Cfile* = object
  239. nimname*: string
  240. cname*, obj*: AbsoluteFile
  241. flags*: set[CfileFlag]
  242. customArgs*: string
  243. CfileList* = seq[Cfile]
  244. Suggest* = ref object
  245. section*: IdeCmd
  246. qualifiedPath*: seq[string]
  247. name*: ptr string # not used beyond sorting purposes; name is also
  248. # part of 'qualifiedPath'
  249. filePath*: string
  250. line*: int # Starts at 1
  251. column*: int # Starts at 0
  252. doc*: string # Not escaped (yet)
  253. forth*: string # type
  254. quality*: range[0..100] # matching quality
  255. isGlobal*: bool # is a global variable
  256. contextFits*: bool # type/non-type context matches
  257. prefix*: PrefixMatch
  258. symkind*: byte
  259. scope*, localUsages*, globalUsages*: int # more usages is better
  260. tokenLen*: int
  261. version*: int
  262. endLine*: uint16
  263. endCol*: int
  264. Suggestions* = seq[Suggest]
  265. ProfileInfo* = object
  266. time*: float
  267. count*: int
  268. ProfileData* = ref object
  269. data*: TableRef[TLineInfo, ProfileInfo]
  270. StdOrrKind* = enum
  271. stdOrrStdout
  272. stdOrrStderr
  273. FilenameOption* = enum
  274. foAbs # absolute path, e.g.: /pathto/bar/foo.nim
  275. foRelProject # relative to project path, e.g.: ../foo.nim
  276. foCanonical # canonical module name
  277. foLegacyRelProj # legacy, shortest of (foAbs, foRelProject)
  278. foName # lastPathPart, e.g.: foo.nim
  279. foStacktrace # if optExcessiveStackTrace: foAbs else: foName
  280. ConfigRef* {.acyclic.} = ref object ## every global configuration
  281. ## fields marked with '*' are subject to
  282. ## the incremental compilation mechanisms
  283. ## (+) means "part of the dependency"
  284. backend*: TBackend # set via `nim x` or `nim --backend:x`
  285. target*: Target # (+)
  286. linesCompiled*: int # all lines that have been compiled
  287. options*: TOptions # (+)
  288. globalOptions*: TGlobalOptions # (+)
  289. macrosToExpand*: StringTableRef
  290. arcToExpand*: StringTableRef
  291. m*: MsgConfig
  292. filenameOption*: FilenameOption # how to render paths in compiler messages
  293. unitSep*: string
  294. evalTemplateCounter*: int
  295. evalMacroCounter*: int
  296. exitcode*: int8
  297. cmd*: Command # raw command parsed as enum
  298. cmdInput*: string # input command
  299. projectIsCmd*: bool # whether we're compiling from a command input
  300. implicitCmd*: bool # whether some flag triggered an implicit `command`
  301. selectedGC*: TGCMode # the selected GC (+)
  302. exc*: ExceptionSystem
  303. hintProcessingDots*: bool # true for dots, false for filenames
  304. verbosity*: int # how verbose the compiler is
  305. numberOfProcessors*: int # number of processors
  306. lastCmdTime*: float # when caas is enabled, we measure each command
  307. symbolFiles*: SymbolFilesOption
  308. spellSuggestMax*: int # max number of spelling suggestions for typos
  309. cppDefines*: HashSet[string] # (*)
  310. headerFile*: string
  311. nimbasePattern*: string # pattern to find nimbase.h
  312. features*: set[Feature]
  313. legacyFeatures*: set[LegacyFeature]
  314. arguments*: string ## the arguments to be passed to the program that
  315. ## should be run
  316. ideCmd*: IdeCmd
  317. oldNewlines*: bool
  318. cCompiler*: TSystemCC # the used compiler
  319. modifiedyNotes*: TNoteKinds # notes that have been set/unset from either cmdline/configs
  320. cmdlineNotes*: TNoteKinds # notes that have been set/unset from cmdline
  321. foreignPackageNotes*: TNoteKinds
  322. notes*: TNoteKinds # notes after resolving all logic(defaults, verbosity)/cmdline/configs
  323. warningAsErrors*: TNoteKinds
  324. mainPackageNotes*: TNoteKinds
  325. mainPackageId*: int
  326. errorCounter*: int
  327. hintCounter*: int
  328. warnCounter*: int
  329. errorMax*: int
  330. maxLoopIterationsVM*: int ## VM: max iterations of all loops
  331. isVmTrace*: bool
  332. configVars*: StringTableRef
  333. symbols*: StringTableRef ## We need to use a StringTableRef here as defined
  334. ## symbols are always guaranteed to be style
  335. ## insensitive. Otherwise hell would break lose.
  336. packageCache*: StringTableRef
  337. nimblePaths*: seq[AbsoluteDir]
  338. searchPaths*: seq[AbsoluteDir]
  339. lazyPaths*: seq[AbsoluteDir]
  340. outFile*: RelativeFile
  341. outDir*: AbsoluteDir
  342. jsonBuildFile*: AbsoluteFile
  343. prefixDir*, libpath*, nimcacheDir*: AbsoluteDir
  344. nimStdlibVersion*: NimVer
  345. dllOverrides, moduleOverrides*, cfileSpecificOptions*: StringTableRef
  346. projectName*: string # holds a name like 'nim'
  347. projectPath*: AbsoluteDir # holds a path like /home/alice/projects/nim/compiler/
  348. projectFull*: AbsoluteFile # projectPath/projectName
  349. projectIsStdin*: bool # whether we're compiling from stdin
  350. lastMsgWasDot*: set[StdOrrKind] # the last compiler message was a single '.'
  351. projectMainIdx*: FileIndex # the canonical path id of the main module
  352. projectMainIdx2*: FileIndex # consider merging with projectMainIdx
  353. command*: string # the main command (e.g. cc, check, scan, etc)
  354. commandArgs*: seq[string] # any arguments after the main command
  355. commandLine*: string
  356. extraCmds*: seq[string] # for writeJsonBuildInstructions
  357. keepComments*: bool # whether the parser needs to keep comments
  358. implicitImports*: seq[string] # modules that are to be implicitly imported
  359. implicitIncludes*: seq[string] # modules that are to be implicitly included
  360. docSeeSrcUrl*: string # if empty, no seeSrc will be generated. \
  361. # The string uses the formatting variables `path` and `line`.
  362. docRoot*: string ## see nim --fullhelp for --docRoot
  363. docCmd*: string ## see nim --fullhelp for --docCmd
  364. configFiles*: seq[AbsoluteFile] # config files (cfg,nims)
  365. cIncludes*: seq[AbsoluteDir] # directories to search for included files
  366. cLibs*: seq[AbsoluteDir] # directories to search for lib files
  367. cLinkedLibs*: seq[string] # libraries to link
  368. externalToLink*: seq[string] # files to link in addition to the file
  369. # we compiled (*)
  370. linkOptionsCmd*: string
  371. compileOptionsCmd*: seq[string]
  372. linkOptions*: string # (*)
  373. compileOptions*: string # (*)
  374. cCompilerPath*: string
  375. toCompile*: CfileList # (*)
  376. suggestionResultHook*: proc (result: Suggest) {.closure.}
  377. suggestVersion*: int
  378. suggestMaxResults*: int
  379. lastLineInfo*: TLineInfo
  380. writelnHook*: proc (output: string) {.closure, gcsafe.}
  381. structuredErrorHook*: proc (config: ConfigRef; info: TLineInfo; msg: string;
  382. severity: Severity) {.closure, gcsafe.}
  383. cppCustomNamespace*: string
  384. nimMainPrefix*: string
  385. vmProfileData*: ProfileData
  386. expandProgress*: bool
  387. expandLevels*: int
  388. expandNodeResult*: string
  389. expandPosition*: TLineInfo
  390. proc parseNimVersion*(a: string): NimVer =
  391. # could be moved somewhere reusable
  392. result = default(NimVer)
  393. if a.len > 0:
  394. let b = a.split(".")
  395. assert b.len == 3, a
  396. template fn(i) = result[i] = b[i].parseInt # could be optimized if needed
  397. fn(0)
  398. fn(1)
  399. fn(2)
  400. proc assignIfDefault*[T](result: var T, val: T, def = default(T)) =
  401. ## if `result` was already assigned to a value (that wasn't `def`), this is a noop.
  402. if result == def: result = val
  403. template setErrorMaxHighMaybe*(conf: ConfigRef) =
  404. ## do not stop after first error (but honor --errorMax if provided)
  405. assignIfDefault(conf.errorMax, high(int))
  406. proc setNoteDefaults*(conf: ConfigRef, note: TNoteKind, enabled = true) =
  407. template fun(op) =
  408. conf.notes.op note
  409. conf.mainPackageNotes.op note
  410. conf.foreignPackageNotes.op note
  411. if enabled: fun(incl) else: fun(excl)
  412. proc setNote*(conf: ConfigRef, note: TNoteKind, enabled = true) =
  413. # see also `prepareConfigNotes` which sets notes
  414. if note notin conf.cmdlineNotes:
  415. if enabled: incl(conf.notes, note) else: excl(conf.notes, note)
  416. proc hasHint*(conf: ConfigRef, note: TNoteKind): bool =
  417. # ternary states instead of binary states would simplify logic
  418. if optHints notin conf.options: false
  419. elif note in {hintConf, hintProcessing}:
  420. # could add here other special notes like hintSource
  421. # these notes apply globally.
  422. note in conf.mainPackageNotes
  423. else: note in conf.notes
  424. proc hasWarn*(conf: ConfigRef, note: TNoteKind): bool {.inline.} =
  425. optWarns in conf.options and note in conf.notes
  426. proc hcrOn*(conf: ConfigRef): bool = return optHotCodeReloading in conf.globalOptions
  427. when false:
  428. template depConfigFields*(fn) {.dirty.} = # deadcode
  429. fn(target)
  430. fn(options)
  431. fn(globalOptions)
  432. fn(selectedGC)
  433. const oldExperimentalFeatures* = {dotOperators, callOperator, parallel}
  434. const
  435. ChecksOptions* = {optObjCheck, optFieldCheck, optRangeCheck,
  436. optOverflowCheck, optBoundsCheck, optAssert, optNaNCheck, optInfCheck,
  437. optStyleCheck}
  438. DefaultOptions* = {optObjCheck, optFieldCheck, optRangeCheck,
  439. optBoundsCheck, optOverflowCheck, optAssert, optWarns, optRefCheck,
  440. optHints, optStackTrace, optLineTrace, # consider adding `optStackTraceMsgs`
  441. optTrMacros, optStyleCheck, optCursorInference}
  442. DefaultGlobalOptions* = {optThreadAnalysis, optExcessiveStackTrace,
  443. optJsBigInt64}
  444. proc getSrcTimestamp(): DateTime =
  445. try:
  446. result = utc(fromUnix(parseInt(getEnv("SOURCE_DATE_EPOCH",
  447. "not a number"))))
  448. except ValueError:
  449. # Environment variable malformed.
  450. # https://reproducible-builds.org/specs/source-date-epoch/: "If the
  451. # value is malformed, the build process SHOULD exit with a non-zero
  452. # error code", which this doesn't do. This uses local time, because
  453. # that maintains compatibility with existing usage.
  454. result = utc getTime()
  455. proc getDateStr*(): string =
  456. result = format(getSrcTimestamp(), "yyyy-MM-dd")
  457. proc getClockStr*(): string =
  458. result = format(getSrcTimestamp(), "HH:mm:ss")
  459. template newPackageCache*(): untyped =
  460. newStringTable(when FileSystemCaseSensitive:
  461. modeCaseInsensitive
  462. else:
  463. modeCaseSensitive)
  464. proc newProfileData(): ProfileData =
  465. ProfileData(data: newTable[TLineInfo, ProfileInfo]())
  466. const foreignPackageNotesDefault* = {
  467. hintProcessing, warnUnknownMagic, hintQuitCalled, hintExecuting, hintUser, warnUser}
  468. proc isDefined*(conf: ConfigRef; symbol: string): bool
  469. when defined(nimDebugUtils):
  470. # this allows inserting debugging utilties in all modules that import `options`
  471. # with a single switch, which is useful when debugging compiler.
  472. import debugutils
  473. export debugutils
  474. proc initConfigRefCommon(conf: ConfigRef) =
  475. conf.selectedGC = gcUnselected
  476. conf.verbosity = 1
  477. conf.hintProcessingDots = true
  478. conf.options = DefaultOptions
  479. conf.globalOptions = DefaultGlobalOptions
  480. conf.filenameOption = foAbs
  481. conf.foreignPackageNotes = foreignPackageNotesDefault
  482. conf.notes = NotesVerbosity[1]
  483. conf.mainPackageNotes = NotesVerbosity[1]
  484. proc newConfigRef*(): ConfigRef =
  485. result = ConfigRef(
  486. cCompiler: ccGcc,
  487. macrosToExpand: newStringTable(modeStyleInsensitive),
  488. arcToExpand: newStringTable(modeStyleInsensitive),
  489. m: initMsgConfig(),
  490. cppDefines: initHashSet[string](),
  491. headerFile: "", features: {}, legacyFeatures: {},
  492. configVars: newStringTable(modeStyleInsensitive),
  493. symbols: newStringTable(modeStyleInsensitive),
  494. packageCache: newPackageCache(),
  495. searchPaths: @[],
  496. lazyPaths: @[],
  497. outFile: RelativeFile"",
  498. outDir: AbsoluteDir"",
  499. prefixDir: AbsoluteDir"",
  500. libpath: AbsoluteDir"", nimcacheDir: AbsoluteDir"",
  501. dllOverrides: newStringTable(modeCaseInsensitive),
  502. moduleOverrides: newStringTable(modeStyleInsensitive),
  503. cfileSpecificOptions: newStringTable(modeCaseSensitive),
  504. projectName: "", # holds a name like 'nim'
  505. projectPath: AbsoluteDir"", # holds a path like /home/alice/projects/nim/compiler/
  506. projectFull: AbsoluteFile"", # projectPath/projectName
  507. projectIsStdin: false, # whether we're compiling from stdin
  508. projectMainIdx: FileIndex(0'i32), # the canonical path id of the main module
  509. command: "", # the main command (e.g. cc, check, scan, etc)
  510. commandArgs: @[], # any arguments after the main command
  511. commandLine: "",
  512. keepComments: true, # whether the parser needs to keep comments
  513. implicitImports: @[], # modules that are to be implicitly imported
  514. implicitIncludes: @[], # modules that are to be implicitly included
  515. docSeeSrcUrl: "",
  516. cIncludes: @[], # directories to search for included files
  517. cLibs: @[], # directories to search for lib files
  518. cLinkedLibs: @[], # libraries to link
  519. backend: backendInvalid,
  520. externalToLink: @[],
  521. linkOptionsCmd: "",
  522. compileOptionsCmd: @[],
  523. linkOptions: "",
  524. compileOptions: "",
  525. ccompilerpath: "",
  526. toCompile: @[],
  527. arguments: "",
  528. suggestMaxResults: 10_000,
  529. maxLoopIterationsVM: 10_000_000,
  530. vmProfileData: newProfileData(),
  531. spellSuggestMax: spellSuggestSecretSauce,
  532. )
  533. initConfigRefCommon(result)
  534. setTargetFromSystem(result.target)
  535. # enable colors by default on terminals
  536. if terminal.isatty(stderr):
  537. incl(result.globalOptions, optUseColors)
  538. when defined(nimDebugUtils):
  539. onNewConfigRef(result)
  540. proc newPartialConfigRef*(): ConfigRef =
  541. ## create a new ConfigRef that is only good enough for error reporting.
  542. when defined(nimDebugUtils):
  543. result = getConfigRef()
  544. else:
  545. result = ConfigRef()
  546. initConfigRefCommon(result)
  547. proc cppDefine*(c: ConfigRef; define: string) =
  548. c.cppDefines.incl define
  549. proc getStdlibVersion*(conf: ConfigRef): NimVer =
  550. if conf.nimStdlibVersion == (0,0,0):
  551. let s = conf.symbols.getOrDefault("nimVersion", "")
  552. conf.nimStdlibVersion = s.parseNimVersion
  553. result = conf.nimStdlibVersion
  554. proc isDefined*(conf: ConfigRef; symbol: string): bool =
  555. if conf.symbols.hasKey(symbol):
  556. result = true
  557. elif cmpIgnoreStyle(symbol, CPU[conf.target.targetCPU].name) == 0:
  558. result = true
  559. elif cmpIgnoreStyle(symbol, platform.OS[conf.target.targetOS].name) == 0:
  560. result = true
  561. else:
  562. case symbol.normalize
  563. of "x86": result = conf.target.targetCPU == cpuI386
  564. of "itanium": result = conf.target.targetCPU == cpuIa64
  565. of "x8664": result = conf.target.targetCPU == cpuAmd64
  566. of "posix", "unix":
  567. result = conf.target.targetOS in {osLinux, osMorphos, osSkyos, osIrix, osPalmos,
  568. osQnx, osAtari, osAix,
  569. osHaiku, osVxWorks, osSolaris, osNetbsd,
  570. osFreebsd, osOpenbsd, osDragonfly, osMacosx, osIos,
  571. osAndroid, osNintendoSwitch, osFreeRTOS, osCrossos, osZephyr, osNuttX}
  572. of "linux":
  573. result = conf.target.targetOS in {osLinux, osAndroid}
  574. of "bsd":
  575. result = conf.target.targetOS in {osNetbsd, osFreebsd, osOpenbsd, osDragonfly, osCrossos}
  576. of "freebsd":
  577. result = conf.target.targetOS in {osFreebsd, osCrossos}
  578. of "emulatedthreadvars":
  579. result = platform.OS[conf.target.targetOS].props.contains(ospLacksThreadVars)
  580. of "msdos": result = conf.target.targetOS == osDos
  581. of "mswindows", "win32": result = conf.target.targetOS == osWindows
  582. of "macintosh":
  583. result = conf.target.targetOS in {osMacos, osMacosx, osIos}
  584. of "osx", "macosx":
  585. result = conf.target.targetOS in {osMacosx, osIos}
  586. of "sunos": result = conf.target.targetOS == osSolaris
  587. of "nintendoswitch":
  588. result = conf.target.targetOS == osNintendoSwitch
  589. of "freertos", "lwip":
  590. result = conf.target.targetOS == osFreeRTOS
  591. of "zephyr":
  592. result = conf.target.targetOS == osZephyr
  593. of "nuttx":
  594. result = conf.target.targetOS == osNuttX
  595. of "littleendian": result = CPU[conf.target.targetCPU].endian == littleEndian
  596. of "bigendian": result = CPU[conf.target.targetCPU].endian == bigEndian
  597. of "cpu8": result = CPU[conf.target.targetCPU].bit == 8
  598. of "cpu16": result = CPU[conf.target.targetCPU].bit == 16
  599. of "cpu32": result = CPU[conf.target.targetCPU].bit == 32
  600. of "cpu64": result = CPU[conf.target.targetCPU].bit == 64
  601. of "nimrawsetjmp":
  602. result = conf.target.targetOS in {osSolaris, osNetbsd, osFreebsd, osOpenbsd,
  603. osDragonfly, osMacosx}
  604. else: result = false
  605. template quitOrRaise*(conf: ConfigRef, msg = "") =
  606. # xxx in future work, consider whether to also intercept `msgQuit` calls
  607. if conf.isDefined("nimDebug"):
  608. raiseAssert msg
  609. else:
  610. quit(msg) # quits with QuitFailure
  611. proc importantComments*(conf: ConfigRef): bool {.inline.} = conf.cmd in cmdDocLike + {cmdIdeTools}
  612. proc usesWriteBarrier*(conf: ConfigRef): bool {.inline.} = conf.selectedGC >= gcRefc
  613. template compilationCachePresent*(conf: ConfigRef): untyped =
  614. false
  615. # conf.symbolFiles in {v2Sf, writeOnlySf}
  616. template optPreserveOrigSource*(conf: ConfigRef): untyped =
  617. optEmbedOrigSrc in conf.globalOptions
  618. proc mainCommandArg*(conf: ConfigRef): string =
  619. ## This is intended for commands like check or parse
  620. ## which will work on the main project file unless
  621. ## explicitly given a specific file argument
  622. if conf.commandArgs.len > 0:
  623. result = conf.commandArgs[0]
  624. else:
  625. result = conf.projectName
  626. proc existsConfigVar*(conf: ConfigRef; key: string): bool =
  627. result = hasKey(conf.configVars, key)
  628. proc getConfigVar*(conf: ConfigRef; key: string, default = ""): string =
  629. result = conf.configVars.getOrDefault(key, default)
  630. proc setConfigVar*(conf: ConfigRef; key, val: string) =
  631. conf.configVars[key] = val
  632. proc getOutFile*(conf: ConfigRef; filename: RelativeFile, ext: string): AbsoluteFile =
  633. # explains regression https://github.com/nim-lang/Nim/issues/6583#issuecomment-625711125
  634. # Yet another reason why "" should not mean "."; `""/something` should raise
  635. # instead of implying "" == "." as it's bug prone.
  636. doAssert conf.outDir.string.len > 0
  637. result = conf.outDir / changeFileExt(filename, ext)
  638. proc absOutFile*(conf: ConfigRef): AbsoluteFile =
  639. doAssert not conf.outDir.isEmpty
  640. doAssert not conf.outFile.isEmpty
  641. result = conf.outDir / conf.outFile
  642. when defined(posix):
  643. if dirExists(result.string): result.string.add ".out"
  644. proc prepareToWriteOutput*(conf: ConfigRef): AbsoluteFile =
  645. ## Create the output directory and returns a full path to the output file
  646. result = conf.absOutFile
  647. createDir result.string.parentDir
  648. proc getPrefixDir*(conf: ConfigRef): AbsoluteDir =
  649. ## Gets the prefix dir, usually the parent directory where the binary resides.
  650. ##
  651. ## This is overridden by some tools (namely nimsuggest) via the ``conf.prefixDir``
  652. ## field.
  653. ## This should resolve to root of nim sources, whether running nim from a local
  654. ## clone or using installed nim, so that these exist: `result/doc/advopt.txt`
  655. ## and `result/lib/system.nim`
  656. if not conf.prefixDir.isEmpty: result = conf.prefixDir
  657. else:
  658. let binParent = AbsoluteDir splitPath(getAppDir()).head
  659. when defined(posix):
  660. if binParent == AbsoluteDir"/usr":
  661. result = AbsoluteDir"/usr/lib/nim"
  662. elif binParent == AbsoluteDir"/usr/local":
  663. result = AbsoluteDir"/usr/local/lib/nim"
  664. else:
  665. result = binParent
  666. else:
  667. result = binParent
  668. proc setDefaultLibpath*(conf: ConfigRef) =
  669. # set default value (can be overwritten):
  670. if conf.libpath.isEmpty:
  671. # choose default libpath:
  672. var prefix = getPrefixDir(conf)
  673. conf.libpath = prefix / RelativeDir"lib"
  674. # Special rule to support other tools (nimble) which import the compiler
  675. # modules and make use of them.
  676. let realNimPath = findExe("nim")
  677. # Find out if $nim/../../lib/system.nim exists.
  678. let parentNimLibPath = realNimPath.parentDir.parentDir / "lib"
  679. if not fileExists(conf.libpath.string / "system.nim") and
  680. fileExists(parentNimLibPath / "system.nim"):
  681. conf.libpath = AbsoluteDir parentNimLibPath
  682. proc canonicalizePath*(conf: ConfigRef; path: AbsoluteFile): AbsoluteFile =
  683. result = AbsoluteFile path.string.expandFilename
  684. proc setFromProjectName*(conf: ConfigRef; projectName: string) =
  685. try:
  686. conf.projectFull = canonicalizePath(conf, AbsoluteFile projectName)
  687. except OSError:
  688. conf.projectFull = AbsoluteFile projectName
  689. let p = splitFile(conf.projectFull)
  690. let dir = if p.dir.isEmpty: AbsoluteDir getCurrentDir() else: p.dir
  691. conf.projectPath = AbsoluteDir canonicalizePath(conf, AbsoluteFile dir)
  692. conf.projectName = p.name
  693. proc removeTrailingDirSep*(path: string): string =
  694. if (path.len > 0) and (path[^1] == DirSep):
  695. result = substr(path, 0, path.len - 2)
  696. else:
  697. result = path
  698. proc disableNimblePath*(conf: ConfigRef) =
  699. incl conf.globalOptions, optNoNimblePath
  700. conf.lazyPaths.setLen(0)
  701. conf.nimblePaths.setLen(0)
  702. proc clearNimblePath*(conf: ConfigRef) =
  703. conf.lazyPaths.setLen(0)
  704. conf.nimblePaths.setLen(0)
  705. include packagehandling
  706. proc getOsCacheDir(): string =
  707. when defined(posix):
  708. result = getEnv("XDG_CACHE_HOME", getHomeDir() / ".cache") / "nim"
  709. else:
  710. result = getHomeDir() / genSubDir.string
  711. proc getNimcacheDir*(conf: ConfigRef): AbsoluteDir =
  712. proc nimcacheSuffix(conf: ConfigRef): string =
  713. if conf.cmd == cmdCheck: "_check"
  714. elif isDefined(conf, "release") or isDefined(conf, "danger"): "_r"
  715. else: "_d"
  716. # XXX projectName should always be without a file extension!
  717. result = if not conf.nimcacheDir.isEmpty:
  718. conf.nimcacheDir
  719. elif conf.backend == backendJs:
  720. if conf.outDir.isEmpty:
  721. conf.projectPath / genSubDir
  722. else:
  723. conf.outDir / genSubDir
  724. else:
  725. AbsoluteDir(getOsCacheDir() / splitFile(conf.projectName).name &
  726. nimcacheSuffix(conf))
  727. proc pathSubs*(conf: ConfigRef; p, config: string): string =
  728. let home = removeTrailingDirSep(os.getHomeDir())
  729. result = unixToNativePath(p % [
  730. "nim", getPrefixDir(conf).string,
  731. "lib", conf.libpath.string,
  732. "home", home,
  733. "config", config,
  734. "projectname", conf.projectName,
  735. "projectpath", conf.projectPath.string,
  736. "projectdir", conf.projectPath.string,
  737. "nimcache", getNimcacheDir(conf).string]).expandTilde
  738. iterator nimbleSubs*(conf: ConfigRef; p: string): string =
  739. let pl = p.toLowerAscii
  740. if "$nimblepath" in pl or "$nimbledir" in pl:
  741. for i in countdown(conf.nimblePaths.len-1, 0):
  742. let nimblePath = removeTrailingDirSep(conf.nimblePaths[i].string)
  743. yield p % ["nimblepath", nimblePath, "nimbledir", nimblePath]
  744. else:
  745. yield p
  746. proc toGeneratedFile*(conf: ConfigRef; path: AbsoluteFile,
  747. ext: string): AbsoluteFile =
  748. ## converts "/home/a/mymodule.nim", "rod" to "/home/a/nimcache/mymodule.rod"
  749. result = getNimcacheDir(conf) / RelativeFile path.string.splitPath.tail.changeFileExt(ext)
  750. proc completeGeneratedFilePath*(conf: ConfigRef; f: AbsoluteFile,
  751. createSubDir: bool = true): AbsoluteFile =
  752. ## Return an absolute path of a generated intermediary file.
  753. ## Optionally creates the cache directory if `createSubDir` is `true`.
  754. let subdir = getNimcacheDir(conf)
  755. if createSubDir:
  756. try:
  757. createDir(subdir.string)
  758. except OSError:
  759. conf.quitOrRaise "cannot create directory: " & subdir.string
  760. result = subdir / RelativeFile f.string.splitPath.tail
  761. proc rawFindFile(conf: ConfigRef; f: RelativeFile; suppressStdlib: bool): AbsoluteFile =
  762. for it in conf.searchPaths:
  763. if suppressStdlib and it.string.startsWith(conf.libpath.string):
  764. continue
  765. result = it / f
  766. if fileExists(result):
  767. return canonicalizePath(conf, result)
  768. result = AbsoluteFile""
  769. proc rawFindFile2(conf: ConfigRef; f: RelativeFile): AbsoluteFile =
  770. for i, it in conf.lazyPaths:
  771. result = it / f
  772. if fileExists(result):
  773. # bring to front
  774. for j in countdown(i, 1):
  775. swap(conf.lazyPaths[j], conf.lazyPaths[j-1])
  776. return canonicalizePath(conf, result)
  777. result = AbsoluteFile""
  778. template patchModule(conf: ConfigRef) {.dirty.} =
  779. if not result.isEmpty and conf.moduleOverrides.len > 0:
  780. let key = getPackageName(conf, result.string) & "_" & splitFile(result).name
  781. if conf.moduleOverrides.hasKey(key):
  782. let ov = conf.moduleOverrides[key]
  783. if ov.len > 0: result = AbsoluteFile(ov)
  784. const stdlibDirs* = [
  785. "pure", "core", "arch",
  786. "pure/collections",
  787. "pure/concurrency",
  788. "pure/unidecode", "impure",
  789. "wrappers", "wrappers/linenoise",
  790. "windows", "posix", "js",
  791. "deprecated/pure"]
  792. const
  793. pkgPrefix = "pkg/"
  794. stdPrefix = "std/"
  795. proc getRelativePathFromConfigPath*(conf: ConfigRef; f: AbsoluteFile, isTitle = false): RelativeFile =
  796. result = RelativeFile("")
  797. let f = $f
  798. if isTitle:
  799. for dir in stdlibDirs:
  800. let path = conf.libpath.string / dir / f.lastPathPart
  801. if path.cmpPaths(f) == 0:
  802. return RelativeFile(stdPrefix & f.splitFile.name)
  803. template search(paths) =
  804. for it in paths:
  805. let it = $it
  806. if f.isRelativeTo(it):
  807. return relativePath(f, it).RelativeFile
  808. search(conf.searchPaths)
  809. search(conf.lazyPaths)
  810. proc findFile*(conf: ConfigRef; f: string; suppressStdlib = false): AbsoluteFile =
  811. if f.isAbsolute:
  812. result = if f.fileExists: AbsoluteFile(f) else: AbsoluteFile""
  813. else:
  814. result = rawFindFile(conf, RelativeFile f, suppressStdlib)
  815. if result.isEmpty:
  816. result = rawFindFile(conf, RelativeFile f.toLowerAscii, suppressStdlib)
  817. if result.isEmpty:
  818. result = rawFindFile2(conf, RelativeFile f)
  819. if result.isEmpty:
  820. result = rawFindFile2(conf, RelativeFile f.toLowerAscii)
  821. patchModule(conf)
  822. proc findModule*(conf: ConfigRef; modulename, currentModule: string): AbsoluteFile =
  823. # returns path to module
  824. var m = addFileExt(modulename, NimExt)
  825. var hasRelativeDot = false
  826. if m.startsWith(pkgPrefix):
  827. result = findFile(conf, m.substr(pkgPrefix.len), suppressStdlib = true)
  828. else:
  829. if m.startsWith(stdPrefix):
  830. result = AbsoluteFile("")
  831. let stripped = m.substr(stdPrefix.len)
  832. for candidate in stdlibDirs:
  833. let path = (conf.libpath.string / candidate / stripped)
  834. if fileExists(path):
  835. result = AbsoluteFile path
  836. break
  837. else: # If prefixed with std/ why would we add the current module path!
  838. let currentPath = currentModule.splitFile.dir
  839. result = AbsoluteFile currentPath / m
  840. if m.startsWith('.') and not fileExists(result):
  841. result = AbsoluteFile ""
  842. hasRelativeDot = true
  843. if not fileExists(result) and not hasRelativeDot:
  844. result = findFile(conf, m)
  845. patchModule(conf)
  846. proc findProjectNimFile*(conf: ConfigRef; pkg: string): string =
  847. const extensions = [".nims", ".cfg", ".nimcfg", ".nimble"]
  848. var
  849. candidates: seq[string] = @[]
  850. dir = pkg
  851. prev = dir
  852. nimblepkg = ""
  853. let pkgname = pkg.lastPathPart()
  854. while true:
  855. for k, f in os.walkDir(dir, relative = true):
  856. if k == pcFile and f != "config.nims":
  857. let (_, name, ext) = splitFile(f)
  858. if ext in extensions:
  859. let x = changeFileExt(dir / name, ".nim")
  860. if fileExists(x):
  861. candidates.add x
  862. if ext == ".nimble":
  863. if nimblepkg.len == 0:
  864. nimblepkg = name
  865. # Since nimble packages can have their source in a subfolder,
  866. # check the last folder we were in for a possible match.
  867. if dir != prev:
  868. let x = prev / x.extractFilename()
  869. if fileExists(x):
  870. candidates.add x
  871. else:
  872. # If we found more than one nimble file, chances are that we
  873. # missed the real project file, or this is an invalid nimble
  874. # package. Either way, bailing is the better choice.
  875. return ""
  876. let pkgname = if nimblepkg.len > 0: nimblepkg else: pkgname
  877. for c in candidates:
  878. if pkgname in c.extractFilename(): return c
  879. if candidates.len > 0:
  880. return candidates[0]
  881. prev = dir
  882. dir = parentDir(dir)
  883. if dir == "": break
  884. return ""
  885. proc canonicalImportAux*(conf: ConfigRef, file: AbsoluteFile): string =
  886. ##[
  887. Shows the canonical module import, e.g.:
  888. system, std/tables, fusion/pointers, system/assertions, std/private/asciitables
  889. ]##
  890. var ret = getRelativePathFromConfigPath(conf, file, isTitle = true)
  891. let dir = getNimbleFile(conf, $file).parentDir.AbsoluteDir
  892. if not dir.isEmpty:
  893. let relPath = relativeTo(file, dir)
  894. if not relPath.isEmpty and (ret.isEmpty or relPath.string.len < ret.string.len):
  895. ret = relPath
  896. if ret.isEmpty:
  897. ret = relativeTo(file, conf.projectPath)
  898. result = ret.string
  899. proc canonicalImport*(conf: ConfigRef, file: AbsoluteFile): string =
  900. let ret = canonicalImportAux(conf, file)
  901. result = ret.nativeToUnixPath.changeFileExt("")
  902. proc canonDynlibName(s: string): string =
  903. let start = if s.startsWith("lib"): 3 else: 0
  904. let ende = strutils.find(s, {'(', ')', '.'})
  905. if ende >= 0:
  906. result = s.substr(start, ende-1)
  907. else:
  908. result = s.substr(start)
  909. proc inclDynlibOverride*(conf: ConfigRef; lib: string) =
  910. conf.dllOverrides[lib.canonDynlibName] = "true"
  911. proc isDynlibOverride*(conf: ConfigRef; lib: string): bool =
  912. result = optDynlibOverrideAll in conf.globalOptions or
  913. conf.dllOverrides.hasKey(lib.canonDynlibName)
  914. proc showNonExportedFields*(conf: ConfigRef) =
  915. incl(conf.globalOptions, optShowNonExportedFields)
  916. proc expandDone*(conf: ConfigRef): bool =
  917. result = conf.ideCmd == ideExpand and conf.expandLevels == 0 and conf.expandProgress
  918. proc parseIdeCmd*(s: string): IdeCmd =
  919. case s:
  920. of "sug": ideSug
  921. of "con": ideCon
  922. of "def": ideDef
  923. of "use": ideUse
  924. of "dus": ideDus
  925. of "chk": ideChk
  926. of "chkFile": ideChkFile
  927. of "mod": ideMod
  928. of "highlight": ideHighlight
  929. of "outline": ideOutline
  930. of "known": ideKnown
  931. of "msg": ideMsg
  932. of "project": ideProject
  933. of "globalSymbols": ideGlobalSymbols
  934. of "recompile": ideRecompile
  935. of "changed": ideChanged
  936. of "type": ideType
  937. else: ideNone
  938. proc `$`*(c: IdeCmd): string =
  939. case c:
  940. of ideSug: "sug"
  941. of ideCon: "con"
  942. of ideDef: "def"
  943. of ideUse: "use"
  944. of ideDus: "dus"
  945. of ideChk: "chk"
  946. of ideChkFile: "chkFile"
  947. of ideMod: "mod"
  948. of ideNone: "none"
  949. of ideHighlight: "highlight"
  950. of ideOutline: "outline"
  951. of ideKnown: "known"
  952. of ideMsg: "msg"
  953. of ideProject: "project"
  954. of ideGlobalSymbols: "globalSymbols"
  955. of ideDeclaration: "declaration"
  956. of ideExpand: "expand"
  957. of ideRecompile: "recompile"
  958. of ideChanged: "changed"
  959. of ideType: "type"
  960. proc floatInt64Align*(conf: ConfigRef): int16 =
  961. ## Returns either 4 or 8 depending on reasons.
  962. if conf != nil and conf.target.targetCPU == cpuI386:
  963. #on Linux/BSD i386, double are aligned to 4bytes (except with -malign-double)
  964. if conf.target.targetOS != osWindows:
  965. # on i386 for all known POSIX systems, 64bits ints are aligned
  966. # to 4bytes (except with -malign-double)
  967. return 4
  968. return 8