commands.nim 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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. # This module handles the parsing of command line arguments.
  10. # We do this here before the 'import' statement so 'defined' does not get
  11. # confused with 'TGCMode.gcMarkAndSweep' etc.
  12. template bootSwitch(name, expr, userString) =
  13. # Helper to build boot constants, for debugging you can 'echo' the else part.
  14. const name = if expr: " " & userString else: ""
  15. bootSwitch(usedRelease, defined(release), "-d:release")
  16. bootSwitch(usedDanger, defined(danger), "-d:danger")
  17. # `useLinenoise` deprecated in favor of `nimUseLinenoise`, kept for backward compatibility
  18. bootSwitch(useLinenoise, defined(nimUseLinenoise) or defined(useLinenoise), "-d:nimUseLinenoise")
  19. bootSwitch(usedBoehm, defined(boehmgc), "--gc:boehm")
  20. bootSwitch(usedMarkAndSweep, defined(gcmarkandsweep), "--gc:markAndSweep")
  21. bootSwitch(usedGoGC, defined(gogc), "--gc:go")
  22. bootSwitch(usedNoGC, defined(nogc), "--gc:none")
  23. import std/[setutils, os, strutils, parseutils, parseopt, sequtils, strtabs]
  24. import
  25. msgs, options, nversion, condsyms, extccomp, platform,
  26. wordrecg, nimblecmd, lineinfos, pathutils, pathnorm
  27. from ast import setUseIc, eqTypeFlags, tfGcSafe, tfNoSideEffect
  28. when defined(nimPreviewSlimSystem):
  29. import std/assertions
  30. # but some have deps to imported modules. Yay.
  31. bootSwitch(usedTinyC, hasTinyCBackend, "-d:tinyc")
  32. bootSwitch(usedFFI, hasFFI, "-d:nimHasLibFFI")
  33. type
  34. TCmdLinePass* = enum
  35. passCmd1, # first pass over the command line
  36. passCmd2, # second pass over the command line
  37. passPP # preprocessor called processCommand()
  38. const
  39. HelpMessage = "Nim Compiler Version $1 [$2: $3]\n" &
  40. "Compiled at $4\n" &
  41. "Copyright (c) 2006-" & copyrightYear & " by Andreas Rumpf\n"
  42. proc genFeatureDesc[T: enum](t: typedesc[T]): string {.compileTime.} =
  43. result = ""
  44. for f in T:
  45. if result.len > 0: result.add "|"
  46. result.add $f
  47. const
  48. Usage = slurp"../doc/basicopt.txt".replace(" //", " ")
  49. AdvancedUsage = slurp"../doc/advopt.txt".replace(" //", " ") % [genFeatureDesc(Feature), genFeatureDesc(LegacyFeature)]
  50. proc getCommandLineDesc(conf: ConfigRef): string =
  51. result = (HelpMessage % [VersionAsString, platform.OS[conf.target.hostOS].name,
  52. CPU[conf.target.hostCPU].name, CompileDate]) &
  53. Usage
  54. proc helpOnError(conf: ConfigRef; pass: TCmdLinePass) =
  55. if pass == passCmd1:
  56. msgWriteln(conf, getCommandLineDesc(conf), {msgStdout})
  57. msgQuit(0)
  58. proc writeAdvancedUsage(conf: ConfigRef; pass: TCmdLinePass) =
  59. if pass == passCmd1:
  60. msgWriteln(conf, (HelpMessage % [VersionAsString,
  61. platform.OS[conf.target.hostOS].name,
  62. CPU[conf.target.hostCPU].name, CompileDate]) &
  63. AdvancedUsage,
  64. {msgStdout})
  65. msgQuit(0)
  66. proc writeFullhelp(conf: ConfigRef; pass: TCmdLinePass) =
  67. if pass == passCmd1:
  68. msgWriteln(conf, `%`(HelpMessage, [VersionAsString,
  69. platform.OS[conf.target.hostOS].name,
  70. CPU[conf.target.hostCPU].name, CompileDate]) &
  71. Usage & AdvancedUsage,
  72. {msgStdout})
  73. msgQuit(0)
  74. proc writeVersionInfo(conf: ConfigRef; pass: TCmdLinePass) =
  75. if pass == passCmd1:
  76. msgWriteln(conf, `%`(HelpMessage, [VersionAsString,
  77. platform.OS[conf.target.hostOS].name,
  78. CPU[conf.target.hostCPU].name, CompileDate]),
  79. {msgStdout})
  80. const gitHash {.strdefine.} = gorge("git log -n 1 --format=%H").strip
  81. # xxx move this logic to std/private/gitutils
  82. when gitHash.len == 40:
  83. msgWriteln(conf, "git hash: " & gitHash, {msgStdout})
  84. msgWriteln(conf, "active boot switches:" & usedRelease & usedDanger &
  85. usedTinyC & useLinenoise &
  86. usedFFI & usedBoehm & usedMarkAndSweep & usedGoGC & usedNoGC,
  87. {msgStdout})
  88. msgQuit(0)
  89. proc writeCommandLineUsage*(conf: ConfigRef) =
  90. msgWriteln(conf, getCommandLineDesc(conf), {msgStdout})
  91. proc addPrefix(switch: string): string =
  92. if switch.len <= 1: result = "-" & switch
  93. else: result = "--" & switch
  94. const
  95. errInvalidCmdLineOption = "invalid command line option: '$1'"
  96. errOnOrOffExpectedButXFound = "'on' or 'off' expected, but '$1' found"
  97. errOnOffOrListExpectedButXFound = "'on', 'off' or 'list' expected, but '$1' found"
  98. errOffHintsError = "'off', 'hint', 'error' or 'usages' expected, but '$1' found"
  99. proc invalidCmdLineOption(conf: ConfigRef; pass: TCmdLinePass, switch: string, info: TLineInfo) =
  100. if switch == " ": localError(conf, info, errInvalidCmdLineOption % "-")
  101. else: localError(conf, info, errInvalidCmdLineOption % addPrefix(switch))
  102. proc splitSwitch(conf: ConfigRef; switch: string, cmd, arg: var string, pass: TCmdLinePass,
  103. info: TLineInfo) =
  104. cmd = ""
  105. var i = 0
  106. if i < switch.len and switch[i] == '-': inc(i)
  107. if i < switch.len and switch[i] == '-': inc(i)
  108. while i < switch.len:
  109. case switch[i]
  110. of 'a'..'z', 'A'..'Z', '0'..'9', '_', '.': cmd.add(switch[i])
  111. else: break
  112. inc(i)
  113. if i >= switch.len: arg = ""
  114. # cmd:arg => (cmd,arg)
  115. elif switch[i] in {':', '='}: arg = substr(switch, i + 1)
  116. # cmd[sub]:rest => (cmd,[sub]:rest)
  117. elif switch[i] == '[': arg = substr(switch, i)
  118. else: invalidCmdLineOption(conf, pass, switch, info)
  119. template switchOn(arg: string): bool =
  120. # xxx use `switchOn` wherever appropriate
  121. case arg.normalize
  122. of "", "on": true
  123. of "off": false
  124. else:
  125. localError(conf, info, errOnOrOffExpectedButXFound % arg)
  126. false
  127. proc processOnOffSwitch(conf: ConfigRef; op: TOptions, arg: string, pass: TCmdLinePass,
  128. info: TLineInfo) =
  129. case arg.normalize
  130. of "", "on": conf.options.incl op
  131. of "off": conf.options.excl op
  132. else: localError(conf, info, errOnOrOffExpectedButXFound % arg)
  133. proc processOnOffSwitchOrList(conf: ConfigRef; op: TOptions, arg: string, pass: TCmdLinePass,
  134. info: TLineInfo): bool =
  135. result = false
  136. case arg.normalize
  137. of "on": conf.options.incl op
  138. of "off": conf.options.excl op
  139. of "list": result = true
  140. else: localError(conf, info, errOnOffOrListExpectedButXFound % arg)
  141. proc processOnOffSwitchG(conf: ConfigRef; op: TGlobalOptions, arg: string, pass: TCmdLinePass,
  142. info: TLineInfo) =
  143. case arg.normalize
  144. of "", "on": conf.globalOptions.incl op
  145. of "off": conf.globalOptions.excl op
  146. else: localError(conf, info, errOnOrOffExpectedButXFound % arg)
  147. proc expectArg(conf: ConfigRef; switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
  148. if arg == "":
  149. localError(conf, info, "argument for command line option expected: '$1'" % addPrefix(switch))
  150. proc expectNoArg(conf: ConfigRef; switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
  151. if arg != "":
  152. localError(conf, info, "invalid argument for command line option: '$1'" % addPrefix(switch))
  153. proc processSpecificNote*(arg: string, state: TSpecialWord, pass: TCmdLinePass,
  154. info: TLineInfo; orig: string; conf: ConfigRef) =
  155. var id = "" # arg = key or [key] or key:val or [key]:val; with val=on|off
  156. var i = 0
  157. var notes: set[TMsgKind]
  158. var isBracket = false
  159. if i < arg.len and arg[i] == '[':
  160. isBracket = true
  161. inc(i)
  162. while i < arg.len and (arg[i] notin {':', '=', ']'}):
  163. id.add(arg[i])
  164. inc(i)
  165. if isBracket:
  166. if i < arg.len and arg[i] == ']': inc(i)
  167. else: invalidCmdLineOption(conf, pass, orig, info)
  168. if i == arg.len: discard
  169. elif i < arg.len and (arg[i] in {':', '='}): inc(i)
  170. else: invalidCmdLineOption(conf, pass, orig, info)
  171. let isSomeHint = state in {wHint, wHintAsError}
  172. template findNote(noteMin, noteMax, name) =
  173. # unfortunately, hintUser and warningUser clash, otherwise implementation would simplify a bit
  174. let x = findStr(noteMin, noteMax, id, errUnknown)
  175. if x != errUnknown: notes = {TNoteKind(x)}
  176. else: localError(conf, info, "unknown $#: $#" % [name, id])
  177. case id.normalize
  178. of "all": # other note groups would be easy to support via additional cases
  179. notes = if isSomeHint: {hintMin..hintMax} else: {warnMin..warnMax}
  180. elif isSomeHint: findNote(hintMin, hintMax, "hint")
  181. else: findNote(warnMin, warnMax, "warning")
  182. var val = substr(arg, i).normalize
  183. if val == "": val = "on"
  184. if val notin ["on", "off"]:
  185. # xxx in future work we should also allow users to have control over `foreignPackageNotes`
  186. # so that they can enable `hints|warnings|warningAsErrors` for all the code they depend on.
  187. localError(conf, info, errOnOrOffExpectedButXFound % arg)
  188. else:
  189. let isOn = val == "on"
  190. if isOn and id.normalize == "all":
  191. localError(conf, info, "only 'all:off' is supported")
  192. for n in notes:
  193. if n notin conf.cmdlineNotes or pass == passCmd1:
  194. if pass == passCmd1: incl(conf.cmdlineNotes, n)
  195. incl(conf.modifiedyNotes, n)
  196. if state in {wWarningAsError, wHintAsError}:
  197. conf.warningAsErrors[n] = isOn # xxx rename warningAsErrors to noteAsErrors
  198. else:
  199. conf.notes[n] = isOn
  200. conf.mainPackageNotes[n] = isOn
  201. if not isOn: excl(conf.foreignPackageNotes, n)
  202. proc processCompile(conf: ConfigRef; filename: string) =
  203. var found = findFile(conf, filename)
  204. if found.isEmpty: found = AbsoluteFile filename
  205. extccomp.addExternalFileToCompile(conf, found)
  206. const
  207. errNoneBoehmRefcExpectedButXFound = "'arc', 'orc', 'markAndSweep', 'boehm', 'go', 'none', 'regions', or 'refc' expected, but '$1' found"
  208. errNoneSpeedOrSizeExpectedButXFound = "'none', 'speed' or 'size' expected, but '$1' found"
  209. errGuiConsoleOrLibExpectedButXFound = "'gui', 'console' or 'lib' expected, but '$1' found"
  210. errInvalidExceptionSystem = "'goto', 'setjmp', 'cpp' or 'quirky' expected, but '$1' found"
  211. template warningOptionNoop(switch: string) =
  212. warningDeprecated(conf, info, "'$#' is deprecated, now a noop" % switch)
  213. template deprecatedAlias(oldName, newName: string) =
  214. warningDeprecated(conf, info, "'$#' is a deprecated alias for '$#'" % [oldName, newName])
  215. proc testCompileOptionArg*(conf: ConfigRef; switch, arg: string, info: TLineInfo): bool =
  216. case switch.normalize
  217. of "gc", "mm":
  218. case arg.normalize
  219. of "boehm": result = conf.selectedGC == gcBoehm
  220. of "refc": result = conf.selectedGC == gcRefc
  221. of "markandsweep": result = conf.selectedGC == gcMarkAndSweep
  222. of "destructors", "arc": result = conf.selectedGC == gcArc
  223. of "orc": result = conf.selectedGC == gcOrc
  224. of "hooks": result = conf.selectedGC == gcHooks
  225. of "go": result = conf.selectedGC == gcGo
  226. of "none": result = conf.selectedGC == gcNone
  227. of "stack", "regions": result = conf.selectedGC == gcRegions
  228. else: localError(conf, info, errNoneBoehmRefcExpectedButXFound % arg)
  229. of "opt":
  230. case arg.normalize
  231. of "speed": result = contains(conf.options, optOptimizeSpeed)
  232. of "size": result = contains(conf.options, optOptimizeSize)
  233. of "none": result = conf.options * {optOptimizeSpeed, optOptimizeSize} == {}
  234. else: localError(conf, info, errNoneSpeedOrSizeExpectedButXFound % arg)
  235. of "verbosity": result = $conf.verbosity == arg
  236. of "app":
  237. case arg.normalize
  238. of "gui": result = contains(conf.globalOptions, optGenGuiApp)
  239. of "console": result = not contains(conf.globalOptions, optGenGuiApp)
  240. of "lib": result = contains(conf.globalOptions, optGenDynLib) and
  241. not contains(conf.globalOptions, optGenGuiApp)
  242. of "staticlib": result = contains(conf.globalOptions, optGenStaticLib) and
  243. not contains(conf.globalOptions, optGenGuiApp)
  244. else: localError(conf, info, errGuiConsoleOrLibExpectedButXFound % arg)
  245. of "dynliboverride":
  246. result = isDynlibOverride(conf, arg)
  247. of "exceptions":
  248. case arg.normalize
  249. of "cpp": result = conf.exc == excCpp
  250. of "setjmp": result = conf.exc == excSetjmp
  251. of "quirky": result = conf.exc == excQuirky
  252. of "goto": result = conf.exc == excGoto
  253. else: localError(conf, info, errInvalidExceptionSystem % arg)
  254. else: invalidCmdLineOption(conf, passCmd1, switch, info)
  255. proc testCompileOption*(conf: ConfigRef; switch: string, info: TLineInfo): bool =
  256. case switch.normalize
  257. of "debuginfo": result = contains(conf.globalOptions, optCDebug)
  258. of "compileonly", "c": result = contains(conf.globalOptions, optCompileOnly)
  259. of "nolinking": result = contains(conf.globalOptions, optNoLinking)
  260. of "nomain": result = contains(conf.globalOptions, optNoMain)
  261. of "forcebuild", "f": result = contains(conf.globalOptions, optForceFullMake)
  262. of "warnings", "w": result = contains(conf.options, optWarns)
  263. of "hints": result = contains(conf.options, optHints)
  264. of "threadanalysis": result = contains(conf.globalOptions, optThreadAnalysis)
  265. of "stacktrace": result = contains(conf.options, optStackTrace)
  266. of "stacktracemsgs": result = contains(conf.options, optStackTraceMsgs)
  267. of "linetrace": result = contains(conf.options, optLineTrace)
  268. of "debugger": result = contains(conf.globalOptions, optCDebug)
  269. of "profiler": result = contains(conf.options, optProfiler)
  270. of "memtracker": result = contains(conf.options, optMemTracker)
  271. of "checks", "x": result = conf.options * ChecksOptions == ChecksOptions
  272. of "floatchecks":
  273. result = conf.options * {optNaNCheck, optInfCheck} == {optNaNCheck, optInfCheck}
  274. of "infchecks": result = contains(conf.options, optInfCheck)
  275. of "nanchecks": result = contains(conf.options, optNaNCheck)
  276. of "objchecks": result = contains(conf.options, optObjCheck)
  277. of "fieldchecks": result = contains(conf.options, optFieldCheck)
  278. of "rangechecks": result = contains(conf.options, optRangeCheck)
  279. of "boundchecks": result = contains(conf.options, optBoundsCheck)
  280. of "refchecks":
  281. warningDeprecated(conf, info, "refchecks is deprecated!")
  282. result = contains(conf.options, optRefCheck)
  283. of "overflowchecks": result = contains(conf.options, optOverflowCheck)
  284. of "staticboundchecks": result = contains(conf.options, optStaticBoundsCheck)
  285. of "stylechecks": result = contains(conf.options, optStyleCheck)
  286. of "linedir": result = contains(conf.options, optLineDir)
  287. of "assertions", "a": result = contains(conf.options, optAssert)
  288. of "run", "r": result = contains(conf.globalOptions, optRun)
  289. of "symbolfiles": result = conf.symbolFiles != disabledSf
  290. of "genscript": result = contains(conf.globalOptions, optGenScript)
  291. of "threads": result = contains(conf.globalOptions, optThreads)
  292. of "tlsemulation": result = contains(conf.globalOptions, optTlsEmulation)
  293. of "implicitstatic": result = contains(conf.options, optImplicitStatic)
  294. of "patterns", "trmacros":
  295. if switch.normalize == "patterns": deprecatedAlias(switch, "trmacros")
  296. result = contains(conf.options, optTrMacros)
  297. of "excessivestacktrace": result = contains(conf.globalOptions, optExcessiveStackTrace)
  298. of "nilseqs", "nilchecks", "taintmode": warningOptionNoop(switch)
  299. of "panics": result = contains(conf.globalOptions, optPanics)
  300. else: invalidCmdLineOption(conf, passCmd1, switch, info)
  301. proc processPath(conf: ConfigRef; path: string, info: TLineInfo,
  302. notRelativeToProj = false): AbsoluteDir =
  303. let p = if os.isAbsolute(path) or '$' in path:
  304. path
  305. elif notRelativeToProj:
  306. getCurrentDir() / path
  307. else:
  308. conf.projectPath.string / path
  309. try:
  310. result = AbsoluteDir pathSubs(conf, p, toFullPath(conf, info).splitFile().dir)
  311. except ValueError:
  312. localError(conf, info, "invalid path: " & p)
  313. result = AbsoluteDir p
  314. proc processCfgPath(conf: ConfigRef; path: string, info: TLineInfo): AbsoluteDir =
  315. let path = if path.len > 0 and path[0] == '"': strutils.unescape(path)
  316. else: path
  317. let basedir = toFullPath(conf, info).splitFile().dir
  318. let p = if os.isAbsolute(path) or '$' in path:
  319. path
  320. else:
  321. basedir / path
  322. try:
  323. result = AbsoluteDir pathSubs(conf, p, basedir)
  324. except ValueError:
  325. localError(conf, info, "invalid path: " & p)
  326. result = AbsoluteDir p
  327. const
  328. errInvalidNumber = "$1 is not a valid number"
  329. proc makeAbsolute(s: string): AbsoluteFile =
  330. if isAbsolute(s):
  331. AbsoluteFile pathnorm.normalizePath(s)
  332. else:
  333. AbsoluteFile pathnorm.normalizePath(os.getCurrentDir() / s)
  334. proc setTrackingInfo(conf: ConfigRef; dirty, file, line, column: string,
  335. info: TLineInfo) =
  336. ## set tracking info, common code for track, trackDirty, & ideTrack
  337. var ln, col: int
  338. if parseUtils.parseInt(line, ln) <= 0:
  339. localError(conf, info, errInvalidNumber % line)
  340. if parseUtils.parseInt(column, col) <= 0:
  341. localError(conf, info, errInvalidNumber % column)
  342. let a = makeAbsolute(file)
  343. if dirty == "":
  344. conf.m.trackPos = newLineInfo(conf, a, ln, col)
  345. else:
  346. let dirtyOriginalIdx = fileInfoIdx(conf, a)
  347. if dirtyOriginalIdx.int32 >= 0:
  348. msgs.setDirtyFile(conf, dirtyOriginalIdx, makeAbsolute(dirty))
  349. conf.m.trackPos = newLineInfo(dirtyOriginalIdx, ln, col)
  350. proc trackDirty(conf: ConfigRef; arg: string, info: TLineInfo) =
  351. var a = arg.split(',')
  352. if a.len != 4: localError(conf, info,
  353. "DIRTY_BUFFER,ORIGINAL_FILE,LINE,COLUMN expected")
  354. setTrackingInfo(conf, a[0], a[1], a[2], a[3], info)
  355. proc track(conf: ConfigRef; arg: string, info: TLineInfo) =
  356. var a = arg.split(',')
  357. if a.len != 3: localError(conf, info, "FILE,LINE,COLUMN expected")
  358. setTrackingInfo(conf, "", a[0], a[1], a[2], info)
  359. proc trackIde(conf: ConfigRef; cmd: IdeCmd, arg: string, info: TLineInfo) =
  360. ## set the tracking info related to an ide cmd, supports optional dirty file
  361. var a = arg.split(',')
  362. case a.len
  363. of 4:
  364. setTrackingInfo(conf, a[0], a[1], a[2], a[3], info)
  365. of 3:
  366. setTrackingInfo(conf, "", a[0], a[1], a[2], info)
  367. else:
  368. localError(conf, info, "[DIRTY_BUFFER,]ORIGINAL_FILE,LINE,COLUMN expected")
  369. conf.ideCmd = cmd
  370. proc dynlibOverride(conf: ConfigRef; switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
  371. if pass in {passCmd2, passPP}:
  372. expectArg(conf, switch, arg, pass, info)
  373. options.inclDynlibOverride(conf, arg)
  374. template handleStdinOrCmdInput =
  375. conf.projectFull = conf.projectName.AbsoluteFile
  376. conf.projectPath = AbsoluteDir getCurrentDir()
  377. if conf.outDir.isEmpty:
  378. conf.outDir = getNimcacheDir(conf)
  379. proc handleStdinInput*(conf: ConfigRef) =
  380. conf.projectName = "stdinfile"
  381. conf.projectIsStdin = true
  382. handleStdinOrCmdInput()
  383. proc handleCmdInput*(conf: ConfigRef) =
  384. conf.projectName = "cmdfile"
  385. handleStdinOrCmdInput()
  386. proc parseCommand*(command: string): Command =
  387. case command.normalize
  388. of "c", "cc", "compile", "compiletoc": cmdCompileToC
  389. of "cpp", "compiletocpp": cmdCompileToCpp
  390. of "objc", "compiletooc": cmdCompileToOC
  391. of "js", "compiletojs": cmdCompileToJS
  392. of "r": cmdCrun
  393. of "run": cmdTcc
  394. of "check": cmdCheck
  395. of "e": cmdNimscript
  396. of "doc0": cmdDoc0
  397. of "doc2", "doc": cmdDoc
  398. of "doc2tex": cmdDoc2tex
  399. of "rst2html": cmdRst2html
  400. of "md2tex": cmdMd2tex
  401. of "md2html": cmdMd2html
  402. of "rst2tex": cmdRst2tex
  403. of "jsondoc0": cmdJsondoc0
  404. of "jsondoc2", "jsondoc": cmdJsondoc
  405. of "ctags": cmdCtags
  406. of "buildindex": cmdBuildindex
  407. of "gendepend": cmdGendepend
  408. of "dump": cmdDump
  409. of "parse": cmdParse
  410. of "rod": cmdRod
  411. of "secret": cmdInteractive
  412. of "nop", "help": cmdNop
  413. of "jsonscript": cmdJsonscript
  414. else: cmdUnknown
  415. proc setCmd*(conf: ConfigRef, cmd: Command) =
  416. ## sets cmd, backend so subsequent flags can query it (e.g. so --gc:arc can be ignored for backendJs)
  417. # Note that `--backend` can override the backend, so the logic here must remain reversible.
  418. conf.cmd = cmd
  419. case cmd
  420. of cmdCompileToC, cmdCrun, cmdTcc: conf.backend = backendC
  421. of cmdCompileToCpp: conf.backend = backendCpp
  422. of cmdCompileToOC: conf.backend = backendObjc
  423. of cmdCompileToJS: conf.backend = backendJs
  424. else: discard
  425. proc setCommandEarly*(conf: ConfigRef, command: string) =
  426. conf.command = command
  427. setCmd(conf, command.parseCommand)
  428. # command early customizations
  429. # must be handled here to honor subsequent `--hint:x:on|off`
  430. case conf.cmd
  431. of cmdRst2html, cmdRst2tex, cmdMd2html, cmdMd2tex:
  432. # xxx see whether to add others: cmdGendepend, etc.
  433. conf.foreignPackageNotes = {hintSuccessX}
  434. else:
  435. conf.foreignPackageNotes = foreignPackageNotesDefault
  436. proc specialDefine(conf: ConfigRef, key: string; pass: TCmdLinePass) =
  437. # Keep this syncronized with the default config/nim.cfg!
  438. if cmpIgnoreStyle(key, "nimQuirky") == 0:
  439. conf.exc = excQuirky
  440. elif cmpIgnoreStyle(key, "release") == 0 or cmpIgnoreStyle(key, "danger") == 0:
  441. if pass in {passCmd1, passPP}:
  442. conf.options.excl {optStackTrace, optLineTrace, optLineDir, optOptimizeSize}
  443. conf.globalOptions.excl {optExcessiveStackTrace, optCDebug}
  444. conf.options.incl optOptimizeSpeed
  445. if cmpIgnoreStyle(key, "danger") == 0 or cmpIgnoreStyle(key, "quick") == 0:
  446. if pass in {passCmd1, passPP}:
  447. conf.options.excl {optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck,
  448. optOverflowCheck, optAssert, optStackTrace, optLineTrace, optLineDir}
  449. conf.globalOptions.excl {optCDebug}
  450. proc initOrcDefines*(conf: ConfigRef) =
  451. conf.selectedGC = gcOrc
  452. defineSymbol(conf.symbols, "gcorc")
  453. defineSymbol(conf.symbols, "gcdestructors")
  454. incl conf.globalOptions, optSeqDestructors
  455. incl conf.globalOptions, optTinyRtti
  456. defineSymbol(conf.symbols, "nimSeqsV2")
  457. defineSymbol(conf.symbols, "nimV2")
  458. if conf.exc == excNone and conf.backend != backendCpp:
  459. conf.exc = excGoto
  460. proc registerArcOrc(pass: TCmdLinePass, conf: ConfigRef, isOrc: bool) =
  461. if isOrc:
  462. conf.selectedGC = gcOrc
  463. defineSymbol(conf.symbols, "gcorc")
  464. else:
  465. conf.selectedGC = gcArc
  466. defineSymbol(conf.symbols, "gcarc")
  467. defineSymbol(conf.symbols, "gcdestructors")
  468. incl conf.globalOptions, optSeqDestructors
  469. incl conf.globalOptions, optTinyRtti
  470. if pass in {passCmd2, passPP}:
  471. defineSymbol(conf.symbols, "nimSeqsV2")
  472. defineSymbol(conf.symbols, "nimV2")
  473. if conf.exc == excNone and conf.backend != backendCpp:
  474. conf.exc = excGoto
  475. proc unregisterArcOrc(conf: ConfigRef) =
  476. undefSymbol(conf.symbols, "gcdestructors")
  477. undefSymbol(conf.symbols, "gcarc")
  478. undefSymbol(conf.symbols, "gcorc")
  479. undefSymbol(conf.symbols, "nimSeqsV2")
  480. undefSymbol(conf.symbols, "nimV2")
  481. excl conf.globalOptions, optSeqDestructors
  482. excl conf.globalOptions, optTinyRtti
  483. proc processMemoryManagementOption(switch, arg: string, pass: TCmdLinePass,
  484. info: TLineInfo; conf: ConfigRef) =
  485. if conf.backend == backendJs: return # for: bug #16033
  486. expectArg(conf, switch, arg, pass, info)
  487. if pass in {passCmd2, passPP}:
  488. case arg.normalize
  489. of "boehm":
  490. unregisterArcOrc(conf)
  491. conf.selectedGC = gcBoehm
  492. defineSymbol(conf.symbols, "boehmgc")
  493. incl conf.globalOptions, optTlsEmulation # Boehm GC doesn't scan the real TLS
  494. of "refc":
  495. unregisterArcOrc(conf)
  496. defineSymbol(conf.symbols, "gcrefc")
  497. conf.selectedGC = gcRefc
  498. of "markandsweep":
  499. unregisterArcOrc(conf)
  500. conf.selectedGC = gcMarkAndSweep
  501. defineSymbol(conf.symbols, "gcmarkandsweep")
  502. of "destructors", "arc":
  503. registerArcOrc(pass, conf, false)
  504. of "orc":
  505. registerArcOrc(pass, conf, true)
  506. of "hooks":
  507. conf.selectedGC = gcHooks
  508. defineSymbol(conf.symbols, "gchooks")
  509. incl conf.globalOptions, optSeqDestructors
  510. processOnOffSwitchG(conf, {optSeqDestructors}, arg, pass, info)
  511. if pass in {passCmd2, passPP}:
  512. defineSymbol(conf.symbols, "nimSeqsV2")
  513. of "go":
  514. unregisterArcOrc(conf)
  515. conf.selectedGC = gcGo
  516. defineSymbol(conf.symbols, "gogc")
  517. of "none":
  518. unregisterArcOrc(conf)
  519. conf.selectedGC = gcNone
  520. defineSymbol(conf.symbols, "nogc")
  521. of "stack", "regions":
  522. unregisterArcOrc(conf)
  523. conf.selectedGC = gcRegions
  524. defineSymbol(conf.symbols, "gcregions")
  525. else: localError(conf, info, errNoneBoehmRefcExpectedButXFound % arg)
  526. proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
  527. conf: ConfigRef) =
  528. var
  529. key, val: string
  530. case switch.normalize
  531. of "eval":
  532. expectArg(conf, switch, arg, pass, info)
  533. conf.projectIsCmd = true
  534. conf.cmdInput = arg # can be empty (a nim file with empty content is valid too)
  535. if conf.cmd == cmdNone:
  536. conf.command = "e"
  537. conf.setCmd cmdNimscript # better than `cmdCrun` as a default
  538. conf.implicitCmd = true
  539. of "path", "p":
  540. expectArg(conf, switch, arg, pass, info)
  541. for path in nimbleSubs(conf, arg):
  542. addPath(conf, if pass == passPP: processCfgPath(conf, path, info)
  543. else: processPath(conf, path, info), info)
  544. of "nimblepath", "babelpath":
  545. if switch.normalize == "babelpath": deprecatedAlias(switch, "nimblepath")
  546. if pass in {passCmd2, passPP} and optNoNimblePath notin conf.globalOptions:
  547. expectArg(conf, switch, arg, pass, info)
  548. var path = processPath(conf, arg, info, notRelativeToProj=true)
  549. let nimbleDir = AbsoluteDir getEnv("NIMBLE_DIR")
  550. if not nimbleDir.isEmpty and pass == passPP:
  551. path = nimbleDir / RelativeDir"pkgs"
  552. nimblePath(conf, path, info)
  553. of "nonimblepath", "nobabelpath":
  554. if switch.normalize == "nobabelpath": deprecatedAlias(switch, "nonimblepath")
  555. expectNoArg(conf, switch, arg, pass, info)
  556. disableNimblePath(conf)
  557. of "clearnimblepath":
  558. expectNoArg(conf, switch, arg, pass, info)
  559. clearNimblePath(conf)
  560. of "excludepath":
  561. expectArg(conf, switch, arg, pass, info)
  562. let path = processPath(conf, arg, info)
  563. conf.searchPaths.keepItIf(it != path)
  564. conf.lazyPaths.keepItIf(it != path)
  565. of "nimcache":
  566. expectArg(conf, switch, arg, pass, info)
  567. var arg = arg
  568. # refs bug #18674, otherwise `--os:windows` messes up with `--nimcache` set
  569. # in config nims files, e.g. via: `import os; switch("nimcache", "/tmp/somedir")`
  570. if conf.target.targetOS == osWindows and DirSep == '/': arg = arg.replace('\\', '/')
  571. conf.nimcacheDir = processPath(conf, arg, info, notRelativeToProj=true)
  572. of "out", "o":
  573. expectArg(conf, switch, arg, pass, info)
  574. let f = splitFile(processPath(conf, arg, info, notRelativeToProj=true).string)
  575. conf.outFile = RelativeFile f.name & f.ext
  576. conf.outDir = toAbsoluteDir f.dir
  577. of "outdir":
  578. expectArg(conf, switch, arg, pass, info)
  579. conf.outDir = processPath(conf, arg, info, notRelativeToProj=true)
  580. of "usenimcache":
  581. processOnOffSwitchG(conf, {optUseNimcache}, arg, pass, info)
  582. of "docseesrcurl":
  583. expectArg(conf, switch, arg, pass, info)
  584. conf.docSeeSrcUrl = arg
  585. of "docroot":
  586. conf.docRoot = if arg.len == 0: docRootDefault else: arg
  587. of "backend", "b":
  588. let backend = parseEnum(arg.normalize, TBackend.default)
  589. if backend == TBackend.default: localError(conf, info, "invalid backend: '$1'" % arg)
  590. conf.backend = backend
  591. of "doccmd": conf.docCmd = arg
  592. of "define", "d":
  593. expectArg(conf, switch, arg, pass, info)
  594. if {':', '='} in arg:
  595. splitSwitch(conf, arg, key, val, pass, info)
  596. specialDefine(conf, key, pass)
  597. defineSymbol(conf.symbols, key, val)
  598. else:
  599. specialDefine(conf, arg, pass)
  600. defineSymbol(conf.symbols, arg)
  601. of "undef", "u":
  602. expectArg(conf, switch, arg, pass, info)
  603. undefSymbol(conf.symbols, arg)
  604. of "compile":
  605. expectArg(conf, switch, arg, pass, info)
  606. if pass in {passCmd2, passPP}: processCompile(conf, arg)
  607. of "link":
  608. expectArg(conf, switch, arg, pass, info)
  609. if pass in {passCmd2, passPP}:
  610. addExternalFileToLink(conf, AbsoluteFile arg)
  611. of "debuginfo":
  612. processOnOffSwitchG(conf, {optCDebug}, arg, pass, info)
  613. of "embedsrc":
  614. processOnOffSwitchG(conf, {optEmbedOrigSrc}, arg, pass, info)
  615. of "compileonly", "c":
  616. processOnOffSwitchG(conf, {optCompileOnly}, arg, pass, info)
  617. of "nolinking":
  618. processOnOffSwitchG(conf, {optNoLinking}, arg, pass, info)
  619. of "nomain":
  620. processOnOffSwitchG(conf, {optNoMain}, arg, pass, info)
  621. of "forcebuild", "f":
  622. processOnOffSwitchG(conf, {optForceFullMake}, arg, pass, info)
  623. of "project":
  624. processOnOffSwitchG(conf, {optWholeProject, optGenIndex}, arg, pass, info)
  625. of "gc":
  626. warningDeprecated(conf, info, "`gc:option` is deprecated; use `mm:option` instead")
  627. processMemoryManagementOption(switch, arg, pass, info, conf)
  628. of "mm":
  629. processMemoryManagementOption(switch, arg, pass, info, conf)
  630. of "warnings", "w":
  631. if processOnOffSwitchOrList(conf, {optWarns}, arg, pass, info): listWarnings(conf)
  632. of "warning": processSpecificNote(arg, wWarning, pass, info, switch, conf)
  633. of "hint": processSpecificNote(arg, wHint, pass, info, switch, conf)
  634. of "warningaserror": processSpecificNote(arg, wWarningAsError, pass, info, switch, conf)
  635. of "hintaserror": processSpecificNote(arg, wHintAsError, pass, info, switch, conf)
  636. of "hints":
  637. if processOnOffSwitchOrList(conf, {optHints}, arg, pass, info): listHints(conf)
  638. of "threadanalysis":
  639. if conf.backend == backendJs: discard
  640. else: processOnOffSwitchG(conf, {optThreadAnalysis}, arg, pass, info)
  641. of "stacktrace": processOnOffSwitch(conf, {optStackTrace}, arg, pass, info)
  642. of "stacktracemsgs": processOnOffSwitch(conf, {optStackTraceMsgs}, arg, pass, info)
  643. of "excessivestacktrace": processOnOffSwitchG(conf, {optExcessiveStackTrace}, arg, pass, info)
  644. of "linetrace": processOnOffSwitch(conf, {optLineTrace}, arg, pass, info)
  645. of "debugger":
  646. case arg.normalize
  647. of "on", "native", "gdb":
  648. conf.globalOptions.incl optCDebug
  649. conf.options.incl optLineDir
  650. #defineSymbol(conf.symbols, "nimTypeNames") # type names are used in gdb pretty printing
  651. of "off":
  652. conf.globalOptions.excl optCDebug
  653. else:
  654. localError(conf, info, "expected native|gdb|on|off but found " & arg)
  655. of "g": # alias for --debugger:native
  656. conf.globalOptions.incl optCDebug
  657. conf.options.incl optLineDir
  658. #defineSymbol(conf.symbols, "nimTypeNames") # type names are used in gdb pretty printing
  659. of "profiler":
  660. processOnOffSwitch(conf, {optProfiler}, arg, pass, info)
  661. if optProfiler in conf.options: defineSymbol(conf.symbols, "profiler")
  662. else: undefSymbol(conf.symbols, "profiler")
  663. of "memtracker":
  664. processOnOffSwitch(conf, {optMemTracker}, arg, pass, info)
  665. if optMemTracker in conf.options: defineSymbol(conf.symbols, "memtracker")
  666. else: undefSymbol(conf.symbols, "memtracker")
  667. of "hotcodereloading":
  668. processOnOffSwitchG(conf, {optHotCodeReloading}, arg, pass, info)
  669. if conf.hcrOn:
  670. defineSymbol(conf.symbols, "hotcodereloading")
  671. defineSymbol(conf.symbols, "useNimRtl")
  672. # hardcoded linking with dynamic runtime for MSVC for smaller binaries
  673. # should do the same for all compilers (wherever applicable)
  674. if isVSCompatible(conf):
  675. extccomp.addCompileOptionCmd(conf, "/MD")
  676. else:
  677. undefSymbol(conf.symbols, "hotcodereloading")
  678. undefSymbol(conf.symbols, "useNimRtl")
  679. of "checks", "x": processOnOffSwitch(conf, ChecksOptions, arg, pass, info)
  680. of "floatchecks":
  681. processOnOffSwitch(conf, {optNaNCheck, optInfCheck}, arg, pass, info)
  682. of "infchecks": processOnOffSwitch(conf, {optInfCheck}, arg, pass, info)
  683. of "nanchecks": processOnOffSwitch(conf, {optNaNCheck}, arg, pass, info)
  684. of "objchecks": processOnOffSwitch(conf, {optObjCheck}, arg, pass, info)
  685. of "fieldchecks": processOnOffSwitch(conf, {optFieldCheck}, arg, pass, info)
  686. of "rangechecks": processOnOffSwitch(conf, {optRangeCheck}, arg, pass, info)
  687. of "boundchecks": processOnOffSwitch(conf, {optBoundsCheck}, arg, pass, info)
  688. of "refchecks":
  689. warningDeprecated(conf, info, "refchecks is deprecated!")
  690. processOnOffSwitch(conf, {optRefCheck}, arg, pass, info)
  691. of "overflowchecks": processOnOffSwitch(conf, {optOverflowCheck}, arg, pass, info)
  692. of "staticboundchecks": processOnOffSwitch(conf, {optStaticBoundsCheck}, arg, pass, info)
  693. of "stylechecks": processOnOffSwitch(conf, {optStyleCheck}, arg, pass, info)
  694. of "linedir": processOnOffSwitch(conf, {optLineDir}, arg, pass, info)
  695. of "assertions", "a": processOnOffSwitch(conf, {optAssert}, arg, pass, info)
  696. of "threads":
  697. if conf.backend == backendJs or conf.cmd == cmdNimscript: discard
  698. else: processOnOffSwitchG(conf, {optThreads}, arg, pass, info)
  699. #if optThreads in conf.globalOptions: conf.setNote(warnGcUnsafe)
  700. of "tlsemulation": processOnOffSwitchG(conf, {optTlsEmulation}, arg, pass, info)
  701. of "implicitstatic":
  702. processOnOffSwitch(conf, {optImplicitStatic}, arg, pass, info)
  703. of "patterns", "trmacros":
  704. if switch.normalize == "patterns": deprecatedAlias(switch, "trmacros")
  705. processOnOffSwitch(conf, {optTrMacros}, arg, pass, info)
  706. of "opt":
  707. expectArg(conf, switch, arg, pass, info)
  708. case arg.normalize
  709. of "speed":
  710. incl(conf.options, optOptimizeSpeed)
  711. excl(conf.options, optOptimizeSize)
  712. of "size":
  713. excl(conf.options, optOptimizeSpeed)
  714. incl(conf.options, optOptimizeSize)
  715. of "none":
  716. excl(conf.options, optOptimizeSpeed)
  717. excl(conf.options, optOptimizeSize)
  718. else: localError(conf, info, errNoneSpeedOrSizeExpectedButXFound % arg)
  719. of "app":
  720. expectArg(conf, switch, arg, pass, info)
  721. case arg.normalize
  722. of "gui":
  723. incl(conf.globalOptions, optGenGuiApp)
  724. defineSymbol(conf.symbols, "executable")
  725. defineSymbol(conf.symbols, "guiapp")
  726. of "console":
  727. excl(conf.globalOptions, optGenGuiApp)
  728. defineSymbol(conf.symbols, "executable")
  729. defineSymbol(conf.symbols, "consoleapp")
  730. of "lib":
  731. incl(conf.globalOptions, optGenDynLib)
  732. excl(conf.globalOptions, optGenGuiApp)
  733. defineSymbol(conf.symbols, "library")
  734. defineSymbol(conf.symbols, "dll")
  735. of "staticlib":
  736. incl(conf.globalOptions, optGenStaticLib)
  737. excl(conf.globalOptions, optGenGuiApp)
  738. defineSymbol(conf.symbols, "library")
  739. defineSymbol(conf.symbols, "staticlib")
  740. else: localError(conf, info, errGuiConsoleOrLibExpectedButXFound % arg)
  741. of "passc", "t":
  742. expectArg(conf, switch, arg, pass, info)
  743. if pass in {passCmd2, passPP}: extccomp.addCompileOptionCmd(conf, arg)
  744. of "passl", "l":
  745. expectArg(conf, switch, arg, pass, info)
  746. if pass in {passCmd2, passPP}: extccomp.addLinkOptionCmd(conf, arg)
  747. of "cincludes":
  748. expectArg(conf, switch, arg, pass, info)
  749. if pass in {passCmd2, passPP}: conf.cIncludes.add processPath(conf, arg, info)
  750. of "clibdir":
  751. expectArg(conf, switch, arg, pass, info)
  752. if pass in {passCmd2, passPP}: conf.cLibs.add processPath(conf, arg, info)
  753. of "clib":
  754. expectArg(conf, switch, arg, pass, info)
  755. if pass in {passCmd2, passPP}:
  756. conf.cLinkedLibs.add arg
  757. of "header":
  758. if conf != nil: conf.headerFile = arg
  759. incl(conf.globalOptions, optGenIndex)
  760. of "index":
  761. processOnOffSwitchG(conf, {optGenIndex}, arg, pass, info)
  762. of "import":
  763. expectArg(conf, switch, arg, pass, info)
  764. if pass in {passCmd2, passPP}:
  765. conf.implicitImports.add findModule(conf, arg, toFullPath(conf, info)).string
  766. of "include":
  767. expectArg(conf, switch, arg, pass, info)
  768. if pass in {passCmd2, passPP}:
  769. conf.implicitIncludes.add findModule(conf, arg, toFullPath(conf, info)).string
  770. of "listcmd":
  771. processOnOffSwitchG(conf, {optListCmd}, arg, pass, info)
  772. of "asm":
  773. processOnOffSwitchG(conf, {optProduceAsm}, arg, pass, info)
  774. of "genmapping":
  775. processOnOffSwitchG(conf, {optGenMapping}, arg, pass, info)
  776. of "os":
  777. expectArg(conf, switch, arg, pass, info)
  778. let theOS = platform.nameToOS(arg)
  779. if theOS == osNone:
  780. let osList = platform.listOSnames().join(", ")
  781. localError(conf, info, "unknown OS: '$1'. Available options are: $2" % [arg, $osList])
  782. else:
  783. setTarget(conf.target, theOS, conf.target.targetCPU)
  784. of "cpu":
  785. expectArg(conf, switch, arg, pass, info)
  786. let cpu = platform.nameToCPU(arg)
  787. if cpu == cpuNone:
  788. let cpuList = platform.listCPUnames().join(", ")
  789. localError(conf, info, "unknown CPU: '$1'. Available options are: $2" % [ arg, cpuList])
  790. else:
  791. setTarget(conf.target, conf.target.targetOS, cpu)
  792. of "run", "r":
  793. processOnOffSwitchG(conf, {optRun}, arg, pass, info)
  794. of "maxloopiterationsvm":
  795. expectArg(conf, switch, arg, pass, info)
  796. conf.maxLoopIterationsVM = parseInt(arg)
  797. of "errormax":
  798. expectArg(conf, switch, arg, pass, info)
  799. # Note: `nim check` (etc) can overwrite this.
  800. # `0` is meaningless, give it a useful meaning as in clang's -ferror-limit
  801. # If user doesn't set this flag and the code doesn't either, it'd
  802. # have the same effect as errorMax = 1
  803. let ret = parseInt(arg)
  804. conf.errorMax = if ret == 0: high(int) else: ret
  805. of "verbosity":
  806. expectArg(conf, switch, arg, pass, info)
  807. let verbosity = parseInt(arg)
  808. if verbosity notin {0..3}:
  809. localError(conf, info, "invalid verbosity level: '$1'" % arg)
  810. conf.verbosity = verbosity
  811. var verb = NotesVerbosity[conf.verbosity]
  812. ## We override the default `verb` by explicitly modified (set/unset) notes.
  813. conf.notes = (conf.modifiedyNotes * conf.notes + verb) -
  814. (conf.modifiedyNotes * verb - conf.notes)
  815. conf.mainPackageNotes = conf.notes
  816. of "parallelbuild":
  817. expectArg(conf, switch, arg, pass, info)
  818. conf.numberOfProcessors = parseInt(arg)
  819. of "version", "v":
  820. expectNoArg(conf, switch, arg, pass, info)
  821. writeVersionInfo(conf, pass)
  822. of "advanced":
  823. expectNoArg(conf, switch, arg, pass, info)
  824. writeAdvancedUsage(conf, pass)
  825. of "fullhelp":
  826. expectNoArg(conf, switch, arg, pass, info)
  827. writeFullhelp(conf, pass)
  828. of "help", "h":
  829. expectNoArg(conf, switch, arg, pass, info)
  830. helpOnError(conf, pass)
  831. of "symbolfiles", "incremental", "ic":
  832. if switch.normalize == "symbolfiles": deprecatedAlias(switch, "incremental")
  833. # xxx maybe also ic, since not in help?
  834. if pass in {passCmd2, passPP}:
  835. case arg.normalize
  836. of "on": conf.symbolFiles = v2Sf
  837. of "off": conf.symbolFiles = disabledSf
  838. of "writeonly": conf.symbolFiles = writeOnlySf
  839. of "readonly": conf.symbolFiles = readOnlySf
  840. of "v2": conf.symbolFiles = v2Sf
  841. of "stress": conf.symbolFiles = stressTest
  842. else: localError(conf, info, "invalid option for --incremental: " & arg)
  843. setUseIc(conf.symbolFiles != disabledSf)
  844. of "skipcfg":
  845. processOnOffSwitchG(conf, {optSkipSystemConfigFile}, arg, pass, info)
  846. of "skipprojcfg":
  847. processOnOffSwitchG(conf, {optSkipProjConfigFile}, arg, pass, info)
  848. of "skipusercfg":
  849. processOnOffSwitchG(conf, {optSkipUserConfigFile}, arg, pass, info)
  850. of "skipparentcfg":
  851. processOnOffSwitchG(conf, {optSkipParentConfigFiles}, arg, pass, info)
  852. of "genscript", "gendeps":
  853. if switch.normalize == "gendeps": deprecatedAlias(switch, "genscript")
  854. processOnOffSwitchG(conf, {optGenScript}, arg, pass, info)
  855. processOnOffSwitchG(conf, {optCompileOnly}, arg, pass, info)
  856. of "colors": processOnOffSwitchG(conf, {optUseColors}, arg, pass, info)
  857. of "lib":
  858. expectArg(conf, switch, arg, pass, info)
  859. conf.libpath = processPath(conf, arg, info, notRelativeToProj=true)
  860. of "putenv":
  861. expectArg(conf, switch, arg, pass, info)
  862. splitSwitch(conf, arg, key, val, pass, info)
  863. os.putEnv(key, val)
  864. of "cc":
  865. if conf.backend != backendJs: # bug #19330
  866. expectArg(conf, switch, arg, pass, info)
  867. setCC(conf, arg, info)
  868. of "track":
  869. expectArg(conf, switch, arg, pass, info)
  870. track(conf, arg, info)
  871. of "trackdirty":
  872. expectArg(conf, switch, arg, pass, info)
  873. trackDirty(conf, arg, info)
  874. of "suggest":
  875. expectNoArg(conf, switch, arg, pass, info)
  876. conf.ideCmd = ideSug
  877. of "def":
  878. expectArg(conf, switch, arg, pass, info)
  879. trackIde(conf, ideDef, arg, info)
  880. of "context":
  881. expectNoArg(conf, switch, arg, pass, info)
  882. conf.ideCmd = ideCon
  883. of "usages":
  884. expectArg(conf, switch, arg, pass, info)
  885. trackIde(conf, ideUse, arg, info)
  886. of "defusages":
  887. expectArg(conf, switch, arg, pass, info)
  888. trackIde(conf, ideDus, arg, info)
  889. of "stdout":
  890. processOnOffSwitchG(conf, {optStdout}, arg, pass, info)
  891. of "filenames":
  892. case arg.normalize
  893. of "abs": conf.filenameOption = foAbs
  894. of "canonical": conf.filenameOption = foCanonical
  895. of "legacyrelproj": conf.filenameOption = foLegacyRelProj
  896. else: localError(conf, info, "expected: abs|canonical|legacyRelProj, got: $1" % arg)
  897. of "processing":
  898. incl(conf.notes, hintProcessing)
  899. incl(conf.mainPackageNotes, hintProcessing)
  900. case arg.normalize
  901. of "dots": conf.hintProcessingDots = true
  902. of "filenames": conf.hintProcessingDots = false
  903. of "off":
  904. excl(conf.notes, hintProcessing)
  905. excl(conf.mainPackageNotes, hintProcessing)
  906. else: localError(conf, info, "expected: dots|filenames|off, got: $1" % arg)
  907. of "unitsep":
  908. conf.unitSep = if switchOn(arg): "\31" else: ""
  909. of "listfullpaths":
  910. # xxx in future work, use `warningDeprecated`
  911. conf.filenameOption = if switchOn(arg): foAbs else: foCanonical
  912. of "spellsuggest":
  913. if arg.len == 0: conf.spellSuggestMax = spellSuggestSecretSauce
  914. elif arg == "auto": conf.spellSuggestMax = spellSuggestSecretSauce
  915. else: conf.spellSuggestMax = parseInt(arg)
  916. of "declaredlocs":
  917. processOnOffSwitchG(conf, {optDeclaredLocs}, arg, pass, info)
  918. of "dynliboverride":
  919. dynlibOverride(conf, switch, arg, pass, info)
  920. of "dynliboverrideall":
  921. processOnOffSwitchG(conf, {optDynlibOverrideAll}, arg, pass, info)
  922. of "experimental":
  923. if arg.len == 0:
  924. conf.features.incl oldExperimentalFeatures
  925. else:
  926. try:
  927. conf.features.incl parseEnum[Feature](arg)
  928. except ValueError:
  929. localError(conf, info, "unknown experimental feature")
  930. of "legacy":
  931. try:
  932. conf.legacyFeatures.incl parseEnum[LegacyFeature](arg)
  933. except ValueError:
  934. localError(conf, info, "unknown obsolete feature")
  935. of "nocppexceptions":
  936. expectNoArg(conf, switch, arg, pass, info)
  937. conf.exc = low(ExceptionSystem)
  938. defineSymbol(conf.symbols, "noCppExceptions")
  939. of "exceptions":
  940. case arg.normalize
  941. of "cpp": conf.exc = excCpp
  942. of "setjmp": conf.exc = excSetjmp
  943. of "quirky": conf.exc = excQuirky
  944. of "goto": conf.exc = excGoto
  945. else: localError(conf, info, errInvalidExceptionSystem % arg)
  946. of "cppdefine":
  947. expectArg(conf, switch, arg, pass, info)
  948. if conf != nil:
  949. conf.cppDefine(arg)
  950. of "newruntime":
  951. warningDeprecated(conf, info, "newruntime is deprecated, use arc/orc instead!")
  952. expectNoArg(conf, switch, arg, pass, info)
  953. if pass in {passCmd2, passPP}:
  954. doAssert(conf != nil)
  955. incl(conf.features, destructor)
  956. incl(conf.globalOptions, optTinyRtti)
  957. incl(conf.globalOptions, optOwnedRefs)
  958. incl(conf.globalOptions, optSeqDestructors)
  959. defineSymbol(conf.symbols, "nimV2")
  960. conf.selectedGC = gcHooks
  961. defineSymbol(conf.symbols, "gchooks")
  962. defineSymbol(conf.symbols, "nimSeqsV2")
  963. defineSymbol(conf.symbols, "nimOwnedEnabled")
  964. of "seqsv2":
  965. processOnOffSwitchG(conf, {optSeqDestructors}, arg, pass, info)
  966. if pass in {passCmd2, passPP}:
  967. defineSymbol(conf.symbols, "nimSeqsV2")
  968. of "stylecheck":
  969. case arg.normalize
  970. of "off": conf.globalOptions = conf.globalOptions - {optStyleHint, optStyleError}
  971. of "hint": conf.globalOptions = conf.globalOptions + {optStyleHint} - {optStyleError}
  972. of "error": conf.globalOptions = conf.globalOptions + {optStyleError}
  973. of "usages": conf.globalOptions.incl optStyleUsages
  974. else: localError(conf, info, errOffHintsError % arg)
  975. of "showallmismatches":
  976. processOnOffSwitchG(conf, {optShowAllMismatches}, arg, pass, info)
  977. of "cppcompiletonamespace":
  978. if arg.len > 0:
  979. conf.cppCustomNamespace = arg
  980. else:
  981. conf.cppCustomNamespace = "Nim"
  982. defineSymbol(conf.symbols, "cppCompileToNamespace", conf.cppCustomNamespace)
  983. of "docinternal":
  984. processOnOffSwitchG(conf, {optDocInternal}, arg, pass, info)
  985. of "multimethods":
  986. processOnOffSwitchG(conf, {optMultiMethods}, arg, pass, info)
  987. of "expandmacro":
  988. expectArg(conf, switch, arg, pass, info)
  989. conf.macrosToExpand[arg] = "T"
  990. of "expandarc":
  991. expectArg(conf, switch, arg, pass, info)
  992. conf.arcToExpand[arg] = "T"
  993. of "useversion":
  994. expectArg(conf, switch, arg, pass, info)
  995. case arg
  996. of "1.0":
  997. defineSymbol(conf.symbols, "NimMajor", "1")
  998. defineSymbol(conf.symbols, "NimMinor", "0")
  999. # old behaviors go here:
  1000. defineSymbol(conf.symbols, "nimOldRelativePathBehavior")
  1001. undefSymbol(conf.symbols, "nimDoesntTrackDefects")
  1002. ast.eqTypeFlags.excl {tfGcSafe, tfNoSideEffect}
  1003. conf.globalOptions.incl optNimV1Emulation
  1004. of "1.2":
  1005. defineSymbol(conf.symbols, "NimMajor", "1")
  1006. defineSymbol(conf.symbols, "NimMinor", "2")
  1007. conf.globalOptions.incl optNimV12Emulation
  1008. of "1.6":
  1009. defineSymbol(conf.symbols, "NimMajor", "1")
  1010. defineSymbol(conf.symbols, "NimMinor", "6")
  1011. conf.globalOptions.incl optNimV16Emulation
  1012. else:
  1013. localError(conf, info, "unknown Nim version; currently supported values are: `1.0`, `1.2`")
  1014. # always be compatible with 1.x.100:
  1015. defineSymbol(conf.symbols, "NimPatch", "100")
  1016. of "benchmarkvm":
  1017. processOnOffSwitchG(conf, {optBenchmarkVM}, arg, pass, info)
  1018. of "profilevm":
  1019. processOnOffSwitchG(conf, {optProfileVM}, arg, pass, info)
  1020. of "sinkinference":
  1021. processOnOffSwitch(conf, {optSinkInference}, arg, pass, info)
  1022. of "cursorinference":
  1023. # undocumented, for debugging purposes only:
  1024. processOnOffSwitch(conf, {optCursorInference}, arg, pass, info)
  1025. of "panics":
  1026. processOnOffSwitchG(conf, {optPanics}, arg, pass, info)
  1027. if optPanics in conf.globalOptions:
  1028. defineSymbol(conf.symbols, "nimPanics")
  1029. of "sourcemap": # xxx document in --fullhelp
  1030. conf.globalOptions.incl optSourcemap
  1031. conf.options.incl optLineDir
  1032. of "deepcopy":
  1033. processOnOffSwitchG(conf, {optEnableDeepCopy}, arg, pass, info)
  1034. of "": # comes from "-" in for example: `nim c -r -` (gets stripped from -)
  1035. handleStdinInput(conf)
  1036. of "nilseqs", "nilchecks", "symbol", "taintmode", "cs", "deadcodeelim": warningOptionNoop(switch)
  1037. of "nimmainprefix": conf.nimMainPrefix = arg
  1038. else:
  1039. if strutils.find(switch, '.') >= 0: options.setConfigVar(conf, switch, arg)
  1040. else: invalidCmdLineOption(conf, pass, switch, info)
  1041. proc processCommand*(switch: string, pass: TCmdLinePass; config: ConfigRef) =
  1042. var cmd, arg: string
  1043. splitSwitch(config, switch, cmd, arg, pass, gCmdLineInfo)
  1044. processSwitch(cmd, arg, pass, gCmdLineInfo, config)
  1045. proc processSwitch*(pass: TCmdLinePass; p: OptParser; config: ConfigRef) =
  1046. # hint[X]:off is parsed as (p.key = "hint[X]", p.val = "off")
  1047. # we transform it to (key = hint, val = [X]:off)
  1048. var bracketLe = strutils.find(p.key, '[')
  1049. if bracketLe >= 0:
  1050. var key = substr(p.key, 0, bracketLe - 1)
  1051. var val = substr(p.key, bracketLe) & ':' & p.val
  1052. processSwitch(key, val, pass, gCmdLineInfo, config)
  1053. else:
  1054. processSwitch(p.key, p.val, pass, gCmdLineInfo, config)
  1055. proc processArgument*(pass: TCmdLinePass; p: OptParser;
  1056. argsCount: var int; config: ConfigRef): bool =
  1057. if argsCount == 0 and config.implicitCmd:
  1058. argsCount.inc
  1059. if argsCount == 0:
  1060. # nim filename.nims is the same as "nim e filename.nims":
  1061. if p.key.endsWith(".nims"):
  1062. config.setCmd cmdNimscript
  1063. incl(config.globalOptions, optWasNimscript)
  1064. config.projectName = unixToNativePath(p.key)
  1065. config.arguments = cmdLineRest(p)
  1066. result = true
  1067. elif pass != passCmd2: setCommandEarly(config, p.key)
  1068. else:
  1069. if pass == passCmd1: config.commandArgs.add p.key
  1070. if argsCount == 1:
  1071. if p.key.endsWith(".nims"):
  1072. incl(config.globalOptions, optWasNimscript)
  1073. # support UNIX style filenames everywhere for portable build scripts:
  1074. if config.projectName.len == 0:
  1075. config.projectName = unixToNativePath(p.key)
  1076. config.arguments = cmdLineRest(p)
  1077. result = true
  1078. inc argsCount