options.nim 39 KB

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