options.nim 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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. noforwardDecl
  210. LegacyFeature* = enum
  211. allowSemcheckedAstModification,
  212. ## Allows to modify a NimNode where the type has already been
  213. ## flagged with nfSem. If you actually do this, it will cause
  214. ## bugs.
  215. checkUnsignedConversions
  216. ## Historically and especially in version 1.0.0 of the language
  217. ## conversions to unsigned numbers were checked. In 1.0.4 they
  218. ## are not anymore.
  219. laxEffects
  220. ## Lax effects system prior to Nim 2.0.
  221. verboseTypeMismatch
  222. SymbolFilesOption* = enum
  223. disabledSf, writeOnlySf, readOnlySf, v2Sf, stressTest
  224. TSystemCC* = enum
  225. ccNone, ccGcc, ccNintendoSwitch, ccLLVM_Gcc, ccCLang, ccBcc, ccVcc,
  226. ccTcc, ccEnv, ccIcl, ccIcc, ccClangCl
  227. ExceptionSystem* = enum
  228. excNone, # no exception system selected yet
  229. excSetjmp, # setjmp based exception handling
  230. excCpp, # use C++'s native exception handling
  231. excGoto, # exception handling based on goto (should become the new default for C)
  232. excQuirky # quirky exception handling
  233. CfileFlag* {.pure.} = enum
  234. Cached, ## no need to recompile this time
  235. External ## file was introduced via .compile pragma
  236. Cfile* = object
  237. nimname*: string
  238. cname*, obj*: AbsoluteFile
  239. flags*: set[CfileFlag]
  240. customArgs*: string
  241. CfileList* = seq[Cfile]
  242. Suggest* = ref object
  243. section*: IdeCmd
  244. qualifiedPath*: seq[string]
  245. name*: ptr string # not used beyond sorting purposes; name is also
  246. # part of 'qualifiedPath'
  247. filePath*: string
  248. line*: int # Starts at 1
  249. column*: int # Starts at 0
  250. doc*: string # Not escaped (yet)
  251. forth*: string # type
  252. quality*: range[0..100] # matching quality
  253. isGlobal*: bool # is a global variable
  254. contextFits*: bool # type/non-type context matches
  255. prefix*: PrefixMatch
  256. symkind*: byte
  257. scope*, localUsages*, globalUsages*: int # more usages is better
  258. tokenLen*: int
  259. version*: int
  260. endLine*: uint16
  261. endCol*: int
  262. Suggestions* = seq[Suggest]
  263. ProfileInfo* = object
  264. time*: float
  265. count*: int
  266. ProfileData* = ref object
  267. data*: TableRef[TLineInfo, ProfileInfo]
  268. StdOrrKind* = enum
  269. stdOrrStdout
  270. stdOrrStderr
  271. FilenameOption* = enum
  272. foAbs # absolute path, e.g.: /pathto/bar/foo.nim
  273. foRelProject # relative to project path, e.g.: ../foo.nim
  274. foCanonical # canonical module name
  275. foLegacyRelProj # legacy, shortest of (foAbs, foRelProject)
  276. foName # lastPathPart, e.g.: foo.nim
  277. foStacktrace # if optExcessiveStackTrace: foAbs else: foName
  278. ConfigRef* {.acyclic.} = ref object ## every global configuration
  279. ## fields marked with '*' are subject to
  280. ## the incremental compilation mechanisms
  281. ## (+) means "part of the dependency"
  282. backend*: TBackend # set via `nim x` or `nim --backend:x`
  283. target*: Target # (+)
  284. linesCompiled*: int # all lines that have been compiled
  285. options*: TOptions # (+)
  286. globalOptions*: TGlobalOptions # (+)
  287. macrosToExpand*: StringTableRef
  288. arcToExpand*: StringTableRef
  289. m*: MsgConfig
  290. filenameOption*: FilenameOption # how to render paths in compiler messages
  291. unitSep*: string
  292. evalTemplateCounter*: int
  293. evalMacroCounter*: int
  294. exitcode*: int8
  295. cmd*: Command # raw command parsed as enum
  296. cmdInput*: string # input command
  297. projectIsCmd*: bool # whether we're compiling from a command input
  298. implicitCmd*: bool # whether some flag triggered an implicit `command`
  299. selectedGC*: TGCMode # the selected GC (+)
  300. exc*: ExceptionSystem
  301. hintProcessingDots*: bool # true for dots, false for filenames
  302. verbosity*: int # how verbose the compiler is
  303. numberOfProcessors*: int # number of processors
  304. lastCmdTime*: float # when caas is enabled, we measure each command
  305. symbolFiles*: SymbolFilesOption
  306. spellSuggestMax*: int # max number of spelling suggestions for typos
  307. cppDefines*: HashSet[string] # (*)
  308. headerFile*: string
  309. nimbasePattern*: string # pattern to find nimbase.h
  310. features*: set[Feature]
  311. legacyFeatures*: set[LegacyFeature]
  312. arguments*: string ## the arguments to be passed to the program that
  313. ## should be run
  314. ideCmd*: IdeCmd
  315. oldNewlines*: bool
  316. cCompiler*: TSystemCC # the used compiler
  317. modifiedyNotes*: TNoteKinds # notes that have been set/unset from either cmdline/configs
  318. cmdlineNotes*: TNoteKinds # notes that have been set/unset from cmdline
  319. foreignPackageNotes*: TNoteKinds
  320. notes*: TNoteKinds # notes after resolving all logic(defaults, verbosity)/cmdline/configs
  321. warningAsErrors*: TNoteKinds
  322. mainPackageNotes*: TNoteKinds
  323. mainPackageId*: int
  324. errorCounter*: int
  325. hintCounter*: int
  326. warnCounter*: int
  327. errorMax*: int
  328. maxLoopIterationsVM*: int ## VM: max iterations of all loops
  329. isVmTrace*: bool
  330. configVars*: StringTableRef
  331. symbols*: StringTableRef ## We need to use a StringTableRef here as defined
  332. ## symbols are always guaranteed to be style
  333. ## insensitive. Otherwise hell would break lose.
  334. packageCache*: StringTableRef
  335. nimblePaths*: seq[AbsoluteDir]
  336. searchPaths*: seq[AbsoluteDir]
  337. lazyPaths*: seq[AbsoluteDir]
  338. outFile*: RelativeFile
  339. outDir*: AbsoluteDir
  340. jsonBuildFile*: AbsoluteFile
  341. prefixDir*, libpath*, nimcacheDir*: AbsoluteDir
  342. nimStdlibVersion*: NimVer
  343. dllOverrides, moduleOverrides*, cfileSpecificOptions*: StringTableRef
  344. projectName*: string # holds a name like 'nim'
  345. projectPath*: AbsoluteDir # holds a path like /home/alice/projects/nim/compiler/
  346. projectFull*: AbsoluteFile # projectPath/projectName
  347. projectIsStdin*: bool # whether we're compiling from stdin
  348. lastMsgWasDot*: set[StdOrrKind] # the last compiler message was a single '.'
  349. projectMainIdx*: FileIndex # the canonical path id of the main module
  350. projectMainIdx2*: FileIndex # consider merging with projectMainIdx
  351. command*: string # the main command (e.g. cc, check, scan, etc)
  352. commandArgs*: seq[string] # any arguments after the main command
  353. commandLine*: string
  354. extraCmds*: seq[string] # for writeJsonBuildInstructions
  355. keepComments*: bool # whether the parser needs to keep comments
  356. implicitImports*: seq[string] # modules that are to be implicitly imported
  357. implicitIncludes*: seq[string] # modules that are to be implicitly included
  358. docSeeSrcUrl*: string # if empty, no seeSrc will be generated. \
  359. # The string uses the formatting variables `path` and `line`.
  360. docRoot*: string ## see nim --fullhelp for --docRoot
  361. docCmd*: string ## see nim --fullhelp for --docCmd
  362. configFiles*: seq[AbsoluteFile] # config files (cfg,nims)
  363. cIncludes*: seq[AbsoluteDir] # directories to search for included files
  364. cLibs*: seq[AbsoluteDir] # directories to search for lib files
  365. cLinkedLibs*: seq[string] # libraries to link
  366. externalToLink*: seq[string] # files to link in addition to the file
  367. # we compiled (*)
  368. linkOptionsCmd*: string
  369. compileOptionsCmd*: seq[string]
  370. linkOptions*: string # (*)
  371. compileOptions*: string # (*)
  372. cCompilerPath*: string
  373. toCompile*: CfileList # (*)
  374. suggestionResultHook*: proc (result: Suggest) {.closure.}
  375. suggestVersion*: int
  376. suggestMaxResults*: int
  377. lastLineInfo*: TLineInfo
  378. writelnHook*: proc (output: string) {.closure, gcsafe.}
  379. structuredErrorHook*: proc (config: ConfigRef; info: TLineInfo; msg: string;
  380. severity: Severity) {.closure, gcsafe.}
  381. cppCustomNamespace*: string
  382. nimMainPrefix*: string
  383. vmProfileData*: ProfileData
  384. expandProgress*: bool
  385. expandLevels*: int
  386. expandNodeResult*: string
  387. expandPosition*: TLineInfo
  388. proc parseNimVersion*(a: string): NimVer =
  389. # could be moved somewhere reusable
  390. result = default(NimVer)
  391. if a.len > 0:
  392. let b = a.split(".")
  393. assert b.len == 3, a
  394. template fn(i) = result[i] = b[i].parseInt # could be optimized if needed
  395. fn(0)
  396. fn(1)
  397. fn(2)
  398. proc assignIfDefault*[T](result: var T, val: T, def = default(T)) =
  399. ## if `result` was already assigned to a value (that wasn't `def`), this is a noop.
  400. if result == def: result = val
  401. template setErrorMaxHighMaybe*(conf: ConfigRef) =
  402. ## do not stop after first error (but honor --errorMax if provided)
  403. assignIfDefault(conf.errorMax, high(int))
  404. proc setNoteDefaults*(conf: ConfigRef, note: TNoteKind, enabled = true) =
  405. template fun(op) =
  406. conf.notes.op note
  407. conf.mainPackageNotes.op note
  408. conf.foreignPackageNotes.op note
  409. if enabled: fun(incl) else: fun(excl)
  410. proc setNote*(conf: ConfigRef, note: TNoteKind, enabled = true) =
  411. # see also `prepareConfigNotes` which sets notes
  412. if note notin conf.cmdlineNotes:
  413. if enabled: incl(conf.notes, note) else: excl(conf.notes, note)
  414. proc hasHint*(conf: ConfigRef, note: TNoteKind): bool =
  415. # ternary states instead of binary states would simplify logic
  416. if optHints notin conf.options: false
  417. elif note in {hintConf, hintProcessing}:
  418. # could add here other special notes like hintSource
  419. # these notes apply globally.
  420. note in conf.mainPackageNotes
  421. else: note in conf.notes
  422. proc hasWarn*(conf: ConfigRef, note: TNoteKind): bool {.inline.} =
  423. optWarns in conf.options and note in conf.notes
  424. proc hcrOn*(conf: ConfigRef): bool = return optHotCodeReloading in conf.globalOptions
  425. when false:
  426. template depConfigFields*(fn) {.dirty.} = # deadcode
  427. fn(target)
  428. fn(options)
  429. fn(globalOptions)
  430. fn(selectedGC)
  431. const oldExperimentalFeatures* = {dotOperators, callOperator, parallel}
  432. const
  433. ChecksOptions* = {optObjCheck, optFieldCheck, optRangeCheck,
  434. optOverflowCheck, optBoundsCheck, optAssert, optNaNCheck, optInfCheck,
  435. optStyleCheck}
  436. DefaultOptions* = {optObjCheck, optFieldCheck, optRangeCheck,
  437. optBoundsCheck, optOverflowCheck, optAssert, optWarns, optRefCheck,
  438. optHints, optStackTrace, optLineTrace, # consider adding `optStackTraceMsgs`
  439. optTrMacros, optStyleCheck, optCursorInference}
  440. DefaultGlobalOptions* = {optThreadAnalysis, optExcessiveStackTrace,
  441. optJsBigInt64}
  442. proc getSrcTimestamp(): DateTime =
  443. try:
  444. result = utc(fromUnix(parseInt(getEnv("SOURCE_DATE_EPOCH",
  445. "not a number"))))
  446. except ValueError:
  447. # Environment variable malformed.
  448. # https://reproducible-builds.org/specs/source-date-epoch/: "If the
  449. # value is malformed, the build process SHOULD exit with a non-zero
  450. # error code", which this doesn't do. This uses local time, because
  451. # that maintains compatibility with existing usage.
  452. result = utc getTime()
  453. proc getDateStr*(): string =
  454. result = format(getSrcTimestamp(), "yyyy-MM-dd")
  455. proc getClockStr*(): string =
  456. result = format(getSrcTimestamp(), "HH:mm:ss")
  457. template newPackageCache*(): untyped =
  458. newStringTable(when FileSystemCaseSensitive:
  459. modeCaseInsensitive
  460. else:
  461. modeCaseSensitive)
  462. proc newProfileData(): ProfileData =
  463. ProfileData(data: newTable[TLineInfo, ProfileInfo]())
  464. const foreignPackageNotesDefault* = {
  465. hintProcessing, warnUnknownMagic, hintQuitCalled, hintExecuting, hintUser, warnUser}
  466. proc isDefined*(conf: ConfigRef; symbol: string): bool
  467. when defined(nimDebugUtils):
  468. # this allows inserting debugging utilties in all modules that import `options`
  469. # with a single switch, which is useful when debugging compiler.
  470. import debugutils
  471. export debugutils
  472. proc initConfigRefCommon(conf: ConfigRef) =
  473. conf.selectedGC = gcUnselected
  474. conf.verbosity = 1
  475. conf.hintProcessingDots = true
  476. conf.options = DefaultOptions
  477. conf.globalOptions = DefaultGlobalOptions
  478. conf.filenameOption = foAbs
  479. conf.foreignPackageNotes = foreignPackageNotesDefault
  480. conf.notes = NotesVerbosity[1]
  481. conf.mainPackageNotes = NotesVerbosity[1]
  482. proc newConfigRef*(): ConfigRef =
  483. result = ConfigRef(
  484. cCompiler: ccGcc,
  485. macrosToExpand: newStringTable(modeStyleInsensitive),
  486. arcToExpand: newStringTable(modeStyleInsensitive),
  487. m: initMsgConfig(),
  488. cppDefines: initHashSet[string](),
  489. headerFile: "", features: {}, legacyFeatures: {},
  490. configVars: newStringTable(modeStyleInsensitive),
  491. symbols: newStringTable(modeStyleInsensitive),
  492. packageCache: newPackageCache(),
  493. searchPaths: @[],
  494. lazyPaths: @[],
  495. outFile: RelativeFile"",
  496. outDir: AbsoluteDir"",
  497. prefixDir: AbsoluteDir"",
  498. libpath: AbsoluteDir"", nimcacheDir: AbsoluteDir"",
  499. dllOverrides: newStringTable(modeCaseInsensitive),
  500. moduleOverrides: newStringTable(modeStyleInsensitive),
  501. cfileSpecificOptions: newStringTable(modeCaseSensitive),
  502. projectName: "", # holds a name like 'nim'
  503. projectPath: AbsoluteDir"", # holds a path like /home/alice/projects/nim/compiler/
  504. projectFull: AbsoluteFile"", # projectPath/projectName
  505. projectIsStdin: false, # whether we're compiling from stdin
  506. projectMainIdx: FileIndex(0'i32), # the canonical path id of the main module
  507. command: "", # the main command (e.g. cc, check, scan, etc)
  508. commandArgs: @[], # any arguments after the main command
  509. commandLine: "",
  510. keepComments: true, # whether the parser needs to keep comments
  511. implicitImports: @[], # modules that are to be implicitly imported
  512. implicitIncludes: @[], # modules that are to be implicitly included
  513. docSeeSrcUrl: "",
  514. cIncludes: @[], # directories to search for included files
  515. cLibs: @[], # directories to search for lib files
  516. cLinkedLibs: @[], # libraries to link
  517. backend: backendInvalid,
  518. externalToLink: @[],
  519. linkOptionsCmd: "",
  520. compileOptionsCmd: @[],
  521. linkOptions: "",
  522. compileOptions: "",
  523. ccompilerpath: "",
  524. toCompile: @[],
  525. arguments: "",
  526. suggestMaxResults: 10_000,
  527. maxLoopIterationsVM: 10_000_000,
  528. vmProfileData: newProfileData(),
  529. spellSuggestMax: spellSuggestSecretSauce,
  530. )
  531. initConfigRefCommon(result)
  532. setTargetFromSystem(result.target)
  533. # enable colors by default on terminals
  534. if terminal.isatty(stderr):
  535. incl(result.globalOptions, optUseColors)
  536. when defined(nimDebugUtils):
  537. onNewConfigRef(result)
  538. proc newPartialConfigRef*(): ConfigRef =
  539. ## create a new ConfigRef that is only good enough for error reporting.
  540. when defined(nimDebugUtils):
  541. result = getConfigRef()
  542. else:
  543. result = ConfigRef()
  544. initConfigRefCommon(result)
  545. proc cppDefine*(c: ConfigRef; define: string) =
  546. c.cppDefines.incl define
  547. proc getStdlibVersion*(conf: ConfigRef): NimVer =
  548. if conf.nimStdlibVersion == (0,0,0):
  549. let s = conf.symbols.getOrDefault("nimVersion", "")
  550. conf.nimStdlibVersion = s.parseNimVersion
  551. result = conf.nimStdlibVersion
  552. proc isDefined*(conf: ConfigRef; symbol: string): bool =
  553. if conf.symbols.hasKey(symbol):
  554. result = true
  555. elif cmpIgnoreStyle(symbol, CPU[conf.target.targetCPU].name) == 0:
  556. result = true
  557. elif cmpIgnoreStyle(symbol, platform.OS[conf.target.targetOS].name) == 0:
  558. result = true
  559. else:
  560. case symbol.normalize
  561. of "x86": result = conf.target.targetCPU == cpuI386
  562. of "itanium": result = conf.target.targetCPU == cpuIa64
  563. of "x8664": result = conf.target.targetCPU == cpuAmd64
  564. of "posix", "unix":
  565. result = conf.target.targetOS in {osLinux, osMorphos, osSkyos, osIrix, osPalmos,
  566. osQnx, osAtari, osAix,
  567. osHaiku, osVxWorks, osSolaris, osNetbsd,
  568. osFreebsd, osOpenbsd, osDragonfly, osMacosx, osIos,
  569. osAndroid, osNintendoSwitch, osFreeRTOS, osCrossos, osZephyr, osNuttX}
  570. of "linux":
  571. result = conf.target.targetOS in {osLinux, osAndroid}
  572. of "bsd":
  573. result = conf.target.targetOS in {osNetbsd, osFreebsd, osOpenbsd, osDragonfly, osCrossos}
  574. of "freebsd":
  575. result = conf.target.targetOS in {osFreebsd, osCrossos}
  576. of "emulatedthreadvars":
  577. result = platform.OS[conf.target.targetOS].props.contains(ospLacksThreadVars)
  578. of "msdos": result = conf.target.targetOS == osDos
  579. of "mswindows", "win32": result = conf.target.targetOS == osWindows
  580. of "macintosh":
  581. result = conf.target.targetOS in {osMacos, osMacosx, osIos}
  582. of "osx", "macosx":
  583. result = conf.target.targetOS in {osMacosx, osIos}
  584. of "sunos": result = conf.target.targetOS == osSolaris
  585. of "nintendoswitch":
  586. result = conf.target.targetOS == osNintendoSwitch
  587. of "freertos", "lwip":
  588. result = conf.target.targetOS == osFreeRTOS
  589. of "zephyr":
  590. result = conf.target.targetOS == osZephyr
  591. of "nuttx":
  592. result = conf.target.targetOS == osNuttX
  593. of "littleendian": result = CPU[conf.target.targetCPU].endian == littleEndian
  594. of "bigendian": result = CPU[conf.target.targetCPU].endian == bigEndian
  595. of "cpu8": result = CPU[conf.target.targetCPU].bit == 8
  596. of "cpu16": result = CPU[conf.target.targetCPU].bit == 16
  597. of "cpu32": result = CPU[conf.target.targetCPU].bit == 32
  598. of "cpu64": result = CPU[conf.target.targetCPU].bit == 64
  599. of "nimrawsetjmp":
  600. result = conf.target.targetOS in {osSolaris, osNetbsd, osFreebsd, osOpenbsd,
  601. osDragonfly, osMacosx}
  602. else: result = false
  603. template quitOrRaise*(conf: ConfigRef, msg = "") =
  604. # xxx in future work, consider whether to also intercept `msgQuit` calls
  605. if conf.isDefined("nimDebug"):
  606. raiseAssert msg
  607. else:
  608. quit(msg) # quits with QuitFailure
  609. proc importantComments*(conf: ConfigRef): bool {.inline.} = conf.cmd in cmdDocLike + {cmdIdeTools}
  610. proc usesWriteBarrier*(conf: ConfigRef): bool {.inline.} = conf.selectedGC >= gcRefc
  611. template compilationCachePresent*(conf: ConfigRef): untyped =
  612. false
  613. # conf.symbolFiles in {v2Sf, writeOnlySf}
  614. template optPreserveOrigSource*(conf: ConfigRef): untyped =
  615. optEmbedOrigSrc in conf.globalOptions
  616. proc mainCommandArg*(conf: ConfigRef): string =
  617. ## This is intended for commands like check or parse
  618. ## which will work on the main project file unless
  619. ## explicitly given a specific file argument
  620. if conf.commandArgs.len > 0:
  621. result = conf.commandArgs[0]
  622. else:
  623. result = conf.projectName
  624. proc existsConfigVar*(conf: ConfigRef; key: string): bool =
  625. result = hasKey(conf.configVars, key)
  626. proc getConfigVar*(conf: ConfigRef; key: string, default = ""): string =
  627. result = conf.configVars.getOrDefault(key, default)
  628. proc setConfigVar*(conf: ConfigRef; key, val: string) =
  629. conf.configVars[key] = val
  630. proc getOutFile*(conf: ConfigRef; filename: RelativeFile, ext: string): AbsoluteFile =
  631. # explains regression https://github.com/nim-lang/Nim/issues/6583#issuecomment-625711125
  632. # Yet another reason why "" should not mean "."; `""/something` should raise
  633. # instead of implying "" == "." as it's bug prone.
  634. doAssert conf.outDir.string.len > 0
  635. result = conf.outDir / changeFileExt(filename, ext)
  636. proc absOutFile*(conf: ConfigRef): AbsoluteFile =
  637. doAssert not conf.outDir.isEmpty
  638. doAssert not conf.outFile.isEmpty
  639. result = conf.outDir / conf.outFile
  640. when defined(posix):
  641. if dirExists(result.string): result.string.add ".out"
  642. proc prepareToWriteOutput*(conf: ConfigRef): AbsoluteFile =
  643. ## Create the output directory and returns a full path to the output file
  644. result = conf.absOutFile
  645. createDir result.string.parentDir
  646. proc getPrefixDir*(conf: ConfigRef): AbsoluteDir =
  647. ## Gets the prefix dir, usually the parent directory where the binary resides.
  648. ##
  649. ## This is overridden by some tools (namely nimsuggest) via the ``conf.prefixDir``
  650. ## field.
  651. ## This should resolve to root of nim sources, whether running nim from a local
  652. ## clone or using installed nim, so that these exist: `result/doc/advopt.txt`
  653. ## and `result/lib/system.nim`
  654. if not conf.prefixDir.isEmpty: result = conf.prefixDir
  655. else:
  656. let binParent = AbsoluteDir splitPath(getAppDir()).head
  657. when defined(posix):
  658. if binParent == AbsoluteDir"/usr":
  659. result = AbsoluteDir"/usr/lib/nim"
  660. elif binParent == AbsoluteDir"/usr/local":
  661. result = AbsoluteDir"/usr/local/lib/nim"
  662. else:
  663. result = binParent
  664. else:
  665. result = binParent
  666. proc setDefaultLibpath*(conf: ConfigRef) =
  667. # set default value (can be overwritten):
  668. if conf.libpath.isEmpty:
  669. # choose default libpath:
  670. var prefix = getPrefixDir(conf)
  671. conf.libpath = prefix / RelativeDir"lib"
  672. # Special rule to support other tools (nimble) which import the compiler
  673. # modules and make use of them.
  674. let realNimPath = findExe("nim")
  675. # Find out if $nim/../../lib/system.nim exists.
  676. let parentNimLibPath = realNimPath.parentDir.parentDir / "lib"
  677. if not fileExists(conf.libpath.string / "system.nim") and
  678. fileExists(parentNimLibPath / "system.nim"):
  679. conf.libpath = AbsoluteDir parentNimLibPath
  680. proc canonicalizePath*(conf: ConfigRef; path: AbsoluteFile): AbsoluteFile =
  681. result = AbsoluteFile path.string.expandFilename
  682. proc setFromProjectName*(conf: ConfigRef; projectName: string) =
  683. try:
  684. conf.projectFull = canonicalizePath(conf, AbsoluteFile projectName)
  685. except OSError:
  686. conf.projectFull = AbsoluteFile projectName
  687. let p = splitFile(conf.projectFull)
  688. let dir = if p.dir.isEmpty: AbsoluteDir getCurrentDir() else: p.dir
  689. conf.projectPath = AbsoluteDir canonicalizePath(conf, AbsoluteFile dir)
  690. conf.projectName = p.name
  691. proc removeTrailingDirSep*(path: string): string =
  692. if (path.len > 0) and (path[^1] == DirSep):
  693. result = substr(path, 0, path.len - 2)
  694. else:
  695. result = path
  696. proc disableNimblePath*(conf: ConfigRef) =
  697. incl conf.globalOptions, optNoNimblePath
  698. conf.lazyPaths.setLen(0)
  699. conf.nimblePaths.setLen(0)
  700. proc clearNimblePath*(conf: ConfigRef) =
  701. conf.lazyPaths.setLen(0)
  702. conf.nimblePaths.setLen(0)
  703. include packagehandling
  704. proc getOsCacheDir(): string =
  705. when defined(posix):
  706. result = getEnv("XDG_CACHE_HOME", getHomeDir() / ".cache") / "nim"
  707. else:
  708. result = getHomeDir() / genSubDir.string
  709. proc getNimcacheDir*(conf: ConfigRef): AbsoluteDir =
  710. proc nimcacheSuffix(conf: ConfigRef): string =
  711. if conf.cmd == cmdCheck: "_check"
  712. elif isDefined(conf, "release") or isDefined(conf, "danger"): "_r"
  713. else: "_d"
  714. # XXX projectName should always be without a file extension!
  715. result = if not conf.nimcacheDir.isEmpty:
  716. conf.nimcacheDir
  717. elif conf.backend == backendJs:
  718. if conf.outDir.isEmpty:
  719. conf.projectPath / genSubDir
  720. else:
  721. conf.outDir / genSubDir
  722. else:
  723. AbsoluteDir(getOsCacheDir() / splitFile(conf.projectName).name &
  724. nimcacheSuffix(conf))
  725. proc pathSubs*(conf: ConfigRef; p, config: string): string =
  726. let home = removeTrailingDirSep(os.getHomeDir())
  727. result = unixToNativePath(p % [
  728. "nim", getPrefixDir(conf).string,
  729. "lib", conf.libpath.string,
  730. "home", home,
  731. "config", config,
  732. "projectname", conf.projectName,
  733. "projectpath", conf.projectPath.string,
  734. "projectdir", conf.projectPath.string,
  735. "nimcache", getNimcacheDir(conf).string]).expandTilde
  736. iterator nimbleSubs*(conf: ConfigRef; p: string): string =
  737. let pl = p.toLowerAscii
  738. if "$nimblepath" in pl or "$nimbledir" in pl:
  739. for i in countdown(conf.nimblePaths.len-1, 0):
  740. let nimblePath = removeTrailingDirSep(conf.nimblePaths[i].string)
  741. yield p % ["nimblepath", nimblePath, "nimbledir", nimblePath]
  742. else:
  743. yield p
  744. proc toGeneratedFile*(conf: ConfigRef; path: AbsoluteFile,
  745. ext: string): AbsoluteFile =
  746. ## converts "/home/a/mymodule.nim", "rod" to "/home/a/nimcache/mymodule.rod"
  747. result = getNimcacheDir(conf) / RelativeFile path.string.splitPath.tail.changeFileExt(ext)
  748. proc completeGeneratedFilePath*(conf: ConfigRef; f: AbsoluteFile,
  749. createSubDir: bool = true): AbsoluteFile =
  750. ## Return an absolute path of a generated intermediary file.
  751. ## Optionally creates the cache directory if `createSubDir` is `true`.
  752. let subdir = getNimcacheDir(conf)
  753. if createSubDir:
  754. try:
  755. createDir(subdir.string)
  756. except OSError:
  757. conf.quitOrRaise "cannot create directory: " & subdir.string
  758. result = subdir / RelativeFile f.string.splitPath.tail
  759. proc rawFindFile(conf: ConfigRef; f: RelativeFile; suppressStdlib: bool): AbsoluteFile =
  760. for it in conf.searchPaths:
  761. if suppressStdlib and it.string.startsWith(conf.libpath.string):
  762. continue
  763. result = it / f
  764. if fileExists(result):
  765. return canonicalizePath(conf, result)
  766. result = AbsoluteFile""
  767. proc rawFindFile2(conf: ConfigRef; f: RelativeFile): AbsoluteFile =
  768. for i, it in conf.lazyPaths:
  769. result = it / f
  770. if fileExists(result):
  771. # bring to front
  772. for j in countdown(i, 1):
  773. swap(conf.lazyPaths[j], conf.lazyPaths[j-1])
  774. return canonicalizePath(conf, result)
  775. result = AbsoluteFile""
  776. template patchModule(conf: ConfigRef) {.dirty.} =
  777. if not result.isEmpty and conf.moduleOverrides.len > 0:
  778. let key = getPackageName(conf, result.string) & "_" & splitFile(result).name
  779. if conf.moduleOverrides.hasKey(key):
  780. let ov = conf.moduleOverrides[key]
  781. if ov.len > 0: result = AbsoluteFile(ov)
  782. const stdlibDirs* = [
  783. "pure", "core", "arch",
  784. "pure/collections",
  785. "pure/concurrency",
  786. "pure/unidecode", "impure",
  787. "wrappers", "wrappers/linenoise",
  788. "windows", "posix", "js",
  789. "deprecated/pure"]
  790. const
  791. pkgPrefix = "pkg/"
  792. stdPrefix = "std/"
  793. proc getRelativePathFromConfigPath*(conf: ConfigRef; f: AbsoluteFile, isTitle = false): RelativeFile =
  794. result = RelativeFile("")
  795. let f = $f
  796. if isTitle:
  797. for dir in stdlibDirs:
  798. let path = conf.libpath.string / dir / f.lastPathPart
  799. if path.cmpPaths(f) == 0:
  800. return RelativeFile(stdPrefix & f.splitFile.name)
  801. template search(paths) =
  802. for it in paths:
  803. let it = $it
  804. if f.isRelativeTo(it):
  805. return relativePath(f, it).RelativeFile
  806. search(conf.searchPaths)
  807. search(conf.lazyPaths)
  808. proc findFile*(conf: ConfigRef; f: string; suppressStdlib = false): AbsoluteFile =
  809. if f.isAbsolute:
  810. result = if f.fileExists: AbsoluteFile(f) else: AbsoluteFile""
  811. else:
  812. result = rawFindFile(conf, RelativeFile f, suppressStdlib)
  813. if result.isEmpty:
  814. result = rawFindFile(conf, RelativeFile f.toLowerAscii, suppressStdlib)
  815. if result.isEmpty:
  816. result = rawFindFile2(conf, RelativeFile f)
  817. if result.isEmpty:
  818. result = rawFindFile2(conf, RelativeFile f.toLowerAscii)
  819. patchModule(conf)
  820. proc findModule*(conf: ConfigRef; modulename, currentModule: string): AbsoluteFile =
  821. # returns path to module
  822. var m = addFileExt(modulename, NimExt)
  823. var hasRelativeDot = false
  824. if m.startsWith(pkgPrefix):
  825. result = findFile(conf, m.substr(pkgPrefix.len), suppressStdlib = true)
  826. else:
  827. if m.startsWith(stdPrefix):
  828. result = AbsoluteFile("")
  829. let stripped = m.substr(stdPrefix.len)
  830. for candidate in stdlibDirs:
  831. let path = (conf.libpath.string / candidate / stripped)
  832. if fileExists(path):
  833. result = AbsoluteFile path
  834. break
  835. else: # If prefixed with std/ why would we add the current module path!
  836. let currentPath = currentModule.splitFile.dir
  837. result = AbsoluteFile currentPath / m
  838. if m.startsWith('.') and not fileExists(result):
  839. result = AbsoluteFile ""
  840. hasRelativeDot = true
  841. if not fileExists(result) and not hasRelativeDot:
  842. result = findFile(conf, m)
  843. patchModule(conf)
  844. proc findProjectNimFile*(conf: ConfigRef; pkg: string): string =
  845. const extensions = [".nims", ".cfg", ".nimcfg", ".nimble"]
  846. var
  847. candidates: seq[string] = @[]
  848. dir = pkg
  849. prev = dir
  850. nimblepkg = ""
  851. let pkgname = pkg.lastPathPart()
  852. while true:
  853. for k, f in os.walkDir(dir, relative = true):
  854. if k == pcFile and f != "config.nims":
  855. let (_, name, ext) = splitFile(f)
  856. if ext in extensions:
  857. let x = changeFileExt(dir / name, ".nim")
  858. if fileExists(x):
  859. candidates.add x
  860. if ext == ".nimble":
  861. if nimblepkg.len == 0:
  862. nimblepkg = name
  863. # Since nimble packages can have their source in a subfolder,
  864. # check the last folder we were in for a possible match.
  865. if dir != prev:
  866. let x = prev / x.extractFilename()
  867. if fileExists(x):
  868. candidates.add x
  869. else:
  870. # If we found more than one nimble file, chances are that we
  871. # missed the real project file, or this is an invalid nimble
  872. # package. Either way, bailing is the better choice.
  873. return ""
  874. let pkgname = if nimblepkg.len > 0: nimblepkg else: pkgname
  875. for c in candidates:
  876. if pkgname in c.extractFilename(): return c
  877. if candidates.len > 0:
  878. return candidates[0]
  879. prev = dir
  880. dir = parentDir(dir)
  881. if dir == "": break
  882. return ""
  883. proc canonicalImportAux*(conf: ConfigRef, file: AbsoluteFile): string =
  884. ##[
  885. Shows the canonical module import, e.g.:
  886. system, std/tables, fusion/pointers, system/assertions, std/private/asciitables
  887. ]##
  888. var ret = getRelativePathFromConfigPath(conf, file, isTitle = true)
  889. let dir = getNimbleFile(conf, $file).parentDir.AbsoluteDir
  890. if not dir.isEmpty:
  891. let relPath = relativeTo(file, dir)
  892. if not relPath.isEmpty and (ret.isEmpty or relPath.string.len < ret.string.len):
  893. ret = relPath
  894. if ret.isEmpty:
  895. ret = relativeTo(file, conf.projectPath)
  896. result = ret.string
  897. proc canonicalImport*(conf: ConfigRef, file: AbsoluteFile): string =
  898. let ret = canonicalImportAux(conf, file)
  899. result = ret.nativeToUnixPath.changeFileExt("")
  900. proc canonDynlibName(s: string): string =
  901. let start = if s.startsWith("lib"): 3 else: 0
  902. let ende = strutils.find(s, {'(', ')', '.'})
  903. if ende >= 0:
  904. result = s.substr(start, ende-1)
  905. else:
  906. result = s.substr(start)
  907. proc inclDynlibOverride*(conf: ConfigRef; lib: string) =
  908. conf.dllOverrides[lib.canonDynlibName] = "true"
  909. proc isDynlibOverride*(conf: ConfigRef; lib: string): bool =
  910. result = optDynlibOverrideAll in conf.globalOptions or
  911. conf.dllOverrides.hasKey(lib.canonDynlibName)
  912. proc showNonExportedFields*(conf: ConfigRef) =
  913. incl(conf.globalOptions, optShowNonExportedFields)
  914. proc expandDone*(conf: ConfigRef): bool =
  915. result = conf.ideCmd == ideExpand and conf.expandLevels == 0 and conf.expandProgress
  916. proc parseIdeCmd*(s: string): IdeCmd =
  917. case s:
  918. of "sug": ideSug
  919. of "con": ideCon
  920. of "def": ideDef
  921. of "use": ideUse
  922. of "dus": ideDus
  923. of "chk": ideChk
  924. of "chkFile": ideChkFile
  925. of "mod": ideMod
  926. of "highlight": ideHighlight
  927. of "outline": ideOutline
  928. of "known": ideKnown
  929. of "msg": ideMsg
  930. of "project": ideProject
  931. of "globalSymbols": ideGlobalSymbols
  932. of "recompile": ideRecompile
  933. of "changed": ideChanged
  934. of "type": ideType
  935. else: ideNone
  936. proc `$`*(c: IdeCmd): string =
  937. case c:
  938. of ideSug: "sug"
  939. of ideCon: "con"
  940. of ideDef: "def"
  941. of ideUse: "use"
  942. of ideDus: "dus"
  943. of ideChk: "chk"
  944. of ideChkFile: "chkFile"
  945. of ideMod: "mod"
  946. of ideNone: "none"
  947. of ideHighlight: "highlight"
  948. of ideOutline: "outline"
  949. of ideKnown: "known"
  950. of ideMsg: "msg"
  951. of ideProject: "project"
  952. of ideGlobalSymbols: "globalSymbols"
  953. of ideDeclaration: "declaration"
  954. of ideExpand: "expand"
  955. of ideRecompile: "recompile"
  956. of ideChanged: "changed"
  957. of ideType: "type"
  958. proc floatInt64Align*(conf: ConfigRef): int16 =
  959. ## Returns either 4 or 8 depending on reasons.
  960. if conf != nil and conf.target.targetCPU == cpuI386:
  961. #on Linux/BSD i386, double are aligned to 4bytes (except with -malign-double)
  962. if conf.target.targetOS != osWindows:
  963. # on i386 for all known POSIX systems, 64bits ints are aligned
  964. # to 4bytes (except with -malign-double)
  965. return 4
  966. return 8