commands.nim 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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 "gencdeps": result = contains(conf.globalOptions, optGenCDeps)
  292. of "threads": result = contains(conf.globalOptions, optThreads)
  293. of "tlsemulation": result = contains(conf.globalOptions, optTlsEmulation)
  294. of "implicitstatic": result = contains(conf.options, optImplicitStatic)
  295. of "patterns", "trmacros":
  296. if switch.normalize == "patterns": deprecatedAlias(switch, "trmacros")
  297. result = contains(conf.options, optTrMacros)
  298. of "excessivestacktrace": result = contains(conf.globalOptions, optExcessiveStackTrace)
  299. of "nilseqs", "nilchecks", "taintmode": warningOptionNoop(switch)
  300. of "panics": result = contains(conf.globalOptions, optPanics)
  301. of "jsbigint64": result = contains(conf.globalOptions, optJsBigInt64)
  302. else: invalidCmdLineOption(conf, passCmd1, switch, info)
  303. proc processPath(conf: ConfigRef; path: string, info: TLineInfo,
  304. notRelativeToProj = false): AbsoluteDir =
  305. let p = if os.isAbsolute(path) or '$' in path:
  306. path
  307. elif notRelativeToProj:
  308. getCurrentDir() / path
  309. else:
  310. conf.projectPath.string / path
  311. try:
  312. result = AbsoluteDir pathSubs(conf, p, toFullPath(conf, info).splitFile().dir)
  313. except ValueError:
  314. localError(conf, info, "invalid path: " & p)
  315. result = AbsoluteDir p
  316. proc processCfgPath(conf: ConfigRef; path: string, info: TLineInfo): AbsoluteDir =
  317. let path = if path.len > 0 and path[0] == '"': strutils.unescape(path)
  318. else: path
  319. let basedir = toFullPath(conf, info).splitFile().dir
  320. let p = if os.isAbsolute(path) or '$' in path:
  321. path
  322. else:
  323. basedir / path
  324. try:
  325. result = AbsoluteDir pathSubs(conf, p, basedir)
  326. except ValueError:
  327. localError(conf, info, "invalid path: " & p)
  328. result = AbsoluteDir p
  329. const
  330. errInvalidNumber = "$1 is not a valid number"
  331. proc makeAbsolute(s: string): AbsoluteFile =
  332. if isAbsolute(s):
  333. AbsoluteFile pathnorm.normalizePath(s)
  334. else:
  335. AbsoluteFile pathnorm.normalizePath(os.getCurrentDir() / s)
  336. proc setTrackingInfo(conf: ConfigRef; dirty, file, line, column: string,
  337. info: TLineInfo) =
  338. ## set tracking info, common code for track, trackDirty, & ideTrack
  339. var ln, col: int
  340. if parseUtils.parseInt(line, ln) <= 0:
  341. localError(conf, info, errInvalidNumber % line)
  342. if parseUtils.parseInt(column, col) <= 0:
  343. localError(conf, info, errInvalidNumber % column)
  344. let a = makeAbsolute(file)
  345. if dirty == "":
  346. conf.m.trackPos = newLineInfo(conf, a, ln, col)
  347. else:
  348. let dirtyOriginalIdx = fileInfoIdx(conf, a)
  349. if dirtyOriginalIdx.int32 >= 0:
  350. msgs.setDirtyFile(conf, dirtyOriginalIdx, makeAbsolute(dirty))
  351. conf.m.trackPos = newLineInfo(dirtyOriginalIdx, ln, col)
  352. proc trackDirty(conf: ConfigRef; arg: string, info: TLineInfo) =
  353. var a = arg.split(',')
  354. if a.len != 4: localError(conf, info,
  355. "DIRTY_BUFFER,ORIGINAL_FILE,LINE,COLUMN expected")
  356. setTrackingInfo(conf, a[0], a[1], a[2], a[3], info)
  357. proc track(conf: ConfigRef; arg: string, info: TLineInfo) =
  358. var a = arg.split(',')
  359. if a.len != 3: localError(conf, info, "FILE,LINE,COLUMN expected")
  360. setTrackingInfo(conf, "", a[0], a[1], a[2], info)
  361. proc trackIde(conf: ConfigRef; cmd: IdeCmd, arg: string, info: TLineInfo) =
  362. ## set the tracking info related to an ide cmd, supports optional dirty file
  363. var a = arg.split(',')
  364. case a.len
  365. of 4:
  366. setTrackingInfo(conf, a[0], a[1], a[2], a[3], info)
  367. of 3:
  368. setTrackingInfo(conf, "", a[0], a[1], a[2], info)
  369. else:
  370. localError(conf, info, "[DIRTY_BUFFER,]ORIGINAL_FILE,LINE,COLUMN expected")
  371. conf.ideCmd = cmd
  372. proc dynlibOverride(conf: ConfigRef; switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
  373. if pass in {passCmd2, passPP}:
  374. expectArg(conf, switch, arg, pass, info)
  375. options.inclDynlibOverride(conf, arg)
  376. template handleStdinOrCmdInput =
  377. conf.projectFull = conf.projectName.AbsoluteFile
  378. conf.projectPath = AbsoluteDir getCurrentDir()
  379. if conf.outDir.isEmpty:
  380. conf.outDir = getNimcacheDir(conf)
  381. proc handleStdinInput*(conf: ConfigRef) =
  382. conf.projectName = "stdinfile"
  383. conf.projectIsStdin = true
  384. handleStdinOrCmdInput()
  385. proc handleCmdInput*(conf: ConfigRef) =
  386. conf.projectName = "cmdfile"
  387. handleStdinOrCmdInput()
  388. proc parseCommand*(command: string): Command =
  389. case command.normalize
  390. of "c", "cc", "compile", "compiletoc": cmdCompileToC
  391. of "cpp", "compiletocpp": cmdCompileToCpp
  392. of "objc", "compiletooc": cmdCompileToOC
  393. of "js", "compiletojs": cmdCompileToJS
  394. of "r": cmdCrun
  395. of "run": cmdTcc
  396. of "check": cmdCheck
  397. of "e": cmdNimscript
  398. of "doc0": cmdDoc0
  399. of "doc2", "doc": cmdDoc
  400. of "doc2tex": cmdDoc2tex
  401. of "rst2html": cmdRst2html
  402. of "md2tex": cmdMd2tex
  403. of "md2html": cmdMd2html
  404. of "rst2tex": cmdRst2tex
  405. of "jsondoc0": cmdJsondoc0
  406. of "jsondoc2", "jsondoc": cmdJsondoc
  407. of "ctags": cmdCtags
  408. of "buildindex": cmdBuildindex
  409. of "gendepend": cmdGendepend
  410. of "dump": cmdDump
  411. of "parse": cmdParse
  412. of "rod": cmdRod
  413. of "secret": cmdInteractive
  414. of "nop", "help": cmdNop
  415. of "jsonscript": cmdJsonscript
  416. else: cmdUnknown
  417. proc setCmd*(conf: ConfigRef, cmd: Command) =
  418. ## sets cmd, backend so subsequent flags can query it (e.g. so --gc:arc can be ignored for backendJs)
  419. # Note that `--backend` can override the backend, so the logic here must remain reversible.
  420. conf.cmd = cmd
  421. case cmd
  422. of cmdCompileToC, cmdCrun, cmdTcc: conf.backend = backendC
  423. of cmdCompileToCpp: conf.backend = backendCpp
  424. of cmdCompileToOC: conf.backend = backendObjc
  425. of cmdCompileToJS: conf.backend = backendJs
  426. else: discard
  427. proc setCommandEarly*(conf: ConfigRef, command: string) =
  428. conf.command = command
  429. setCmd(conf, command.parseCommand)
  430. # command early customizations
  431. # must be handled here to honor subsequent `--hint:x:on|off`
  432. case conf.cmd
  433. of cmdRst2html, cmdRst2tex, cmdMd2html, cmdMd2tex:
  434. # xxx see whether to add others: cmdGendepend, etc.
  435. conf.foreignPackageNotes = {hintSuccessX}
  436. else:
  437. conf.foreignPackageNotes = foreignPackageNotesDefault
  438. proc specialDefine(conf: ConfigRef, key: string; pass: TCmdLinePass) =
  439. # Keep this syncronized with the default config/nim.cfg!
  440. if cmpIgnoreStyle(key, "nimQuirky") == 0:
  441. conf.exc = excQuirky
  442. elif cmpIgnoreStyle(key, "release") == 0 or cmpIgnoreStyle(key, "danger") == 0:
  443. if pass in {passCmd1, passPP}:
  444. conf.options.excl {optStackTrace, optLineTrace, optLineDir, optOptimizeSize}
  445. conf.globalOptions.excl {optExcessiveStackTrace, optCDebug}
  446. conf.options.incl optOptimizeSpeed
  447. if cmpIgnoreStyle(key, "danger") == 0 or cmpIgnoreStyle(key, "quick") == 0:
  448. if pass in {passCmd1, passPP}:
  449. conf.options.excl {optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck,
  450. optOverflowCheck, optAssert, optStackTrace, optLineTrace, optLineDir}
  451. conf.globalOptions.excl {optCDebug}
  452. proc initOrcDefines*(conf: ConfigRef) =
  453. conf.selectedGC = gcOrc
  454. defineSymbol(conf.symbols, "gcorc")
  455. defineSymbol(conf.symbols, "gcdestructors")
  456. incl conf.globalOptions, optSeqDestructors
  457. incl conf.globalOptions, optTinyRtti
  458. defineSymbol(conf.symbols, "nimSeqsV2")
  459. defineSymbol(conf.symbols, "nimV2")
  460. if conf.exc == excNone and conf.backend != backendCpp:
  461. conf.exc = excGoto
  462. proc registerArcOrc(pass: TCmdLinePass, conf: ConfigRef, isOrc: bool) =
  463. if isOrc:
  464. conf.selectedGC = gcOrc
  465. defineSymbol(conf.symbols, "gcorc")
  466. else:
  467. conf.selectedGC = gcArc
  468. defineSymbol(conf.symbols, "gcarc")
  469. defineSymbol(conf.symbols, "gcdestructors")
  470. incl conf.globalOptions, optSeqDestructors
  471. incl conf.globalOptions, optTinyRtti
  472. if pass in {passCmd2, passPP}:
  473. defineSymbol(conf.symbols, "nimSeqsV2")
  474. defineSymbol(conf.symbols, "nimV2")
  475. if conf.exc == excNone and conf.backend != backendCpp:
  476. conf.exc = excGoto
  477. proc unregisterArcOrc(conf: ConfigRef) =
  478. undefSymbol(conf.symbols, "gcdestructors")
  479. undefSymbol(conf.symbols, "gcarc")
  480. undefSymbol(conf.symbols, "gcorc")
  481. undefSymbol(conf.symbols, "nimSeqsV2")
  482. undefSymbol(conf.symbols, "nimV2")
  483. excl conf.globalOptions, optSeqDestructors
  484. excl conf.globalOptions, optTinyRtti
  485. proc processMemoryManagementOption(switch, arg: string, pass: TCmdLinePass,
  486. info: TLineInfo; conf: ConfigRef) =
  487. if conf.backend == backendJs: return # for: bug #16033
  488. expectArg(conf, switch, arg, pass, info)
  489. if pass in {passCmd2, passPP}:
  490. case arg.normalize
  491. of "boehm":
  492. unregisterArcOrc(conf)
  493. conf.selectedGC = gcBoehm
  494. defineSymbol(conf.symbols, "boehmgc")
  495. incl conf.globalOptions, optTlsEmulation # Boehm GC doesn't scan the real TLS
  496. of "refc":
  497. unregisterArcOrc(conf)
  498. defineSymbol(conf.symbols, "gcrefc")
  499. conf.selectedGC = gcRefc
  500. of "markandsweep":
  501. unregisterArcOrc(conf)
  502. conf.selectedGC = gcMarkAndSweep
  503. defineSymbol(conf.symbols, "gcmarkandsweep")
  504. of "destructors", "arc":
  505. registerArcOrc(pass, conf, false)
  506. of "orc":
  507. registerArcOrc(pass, conf, true)
  508. of "hooks":
  509. conf.selectedGC = gcHooks
  510. defineSymbol(conf.symbols, "gchooks")
  511. incl conf.globalOptions, optSeqDestructors
  512. processOnOffSwitchG(conf, {optSeqDestructors}, arg, pass, info)
  513. if pass in {passCmd2, passPP}:
  514. defineSymbol(conf.symbols, "nimSeqsV2")
  515. of "go":
  516. unregisterArcOrc(conf)
  517. conf.selectedGC = gcGo
  518. defineSymbol(conf.symbols, "gogc")
  519. of "none":
  520. unregisterArcOrc(conf)
  521. conf.selectedGC = gcNone
  522. defineSymbol(conf.symbols, "nogc")
  523. of "stack", "regions":
  524. unregisterArcOrc(conf)
  525. conf.selectedGC = gcRegions
  526. defineSymbol(conf.symbols, "gcregions")
  527. else: localError(conf, info, errNoneBoehmRefcExpectedButXFound % arg)
  528. proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
  529. conf: ConfigRef) =
  530. var
  531. key, val: string
  532. case switch.normalize
  533. of "eval":
  534. expectArg(conf, switch, arg, pass, info)
  535. conf.projectIsCmd = true
  536. conf.cmdInput = arg # can be empty (a nim file with empty content is valid too)
  537. if conf.cmd == cmdNone:
  538. conf.command = "e"
  539. conf.setCmd cmdNimscript # better than `cmdCrun` as a default
  540. conf.implicitCmd = true
  541. of "path", "p":
  542. expectArg(conf, switch, arg, pass, info)
  543. for path in nimbleSubs(conf, arg):
  544. addPath(conf, if pass == passPP: processCfgPath(conf, path, info)
  545. else: processPath(conf, path, info), info)
  546. of "nimblepath", "babelpath":
  547. if switch.normalize == "babelpath": deprecatedAlias(switch, "nimblepath")
  548. if pass in {passCmd2, passPP} and optNoNimblePath notin conf.globalOptions:
  549. expectArg(conf, switch, arg, pass, info)
  550. var path = processPath(conf, arg, info, notRelativeToProj=true)
  551. let nimbleDir = AbsoluteDir getEnv("NIMBLE_DIR")
  552. if not nimbleDir.isEmpty and pass == passPP:
  553. path = nimbleDir / RelativeDir"pkgs"
  554. nimblePath(conf, path, info)
  555. of "nonimblepath", "nobabelpath":
  556. if switch.normalize == "nobabelpath": deprecatedAlias(switch, "nonimblepath")
  557. expectNoArg(conf, switch, arg, pass, info)
  558. disableNimblePath(conf)
  559. of "clearnimblepath":
  560. expectNoArg(conf, switch, arg, pass, info)
  561. clearNimblePath(conf)
  562. of "excludepath":
  563. expectArg(conf, switch, arg, pass, info)
  564. let path = processPath(conf, arg, info)
  565. conf.searchPaths.keepItIf(it != path)
  566. conf.lazyPaths.keepItIf(it != path)
  567. of "nimcache":
  568. expectArg(conf, switch, arg, pass, info)
  569. var arg = arg
  570. # refs bug #18674, otherwise `--os:windows` messes up with `--nimcache` set
  571. # in config nims files, e.g. via: `import os; switch("nimcache", "/tmp/somedir")`
  572. if conf.target.targetOS == osWindows and DirSep == '/': arg = arg.replace('\\', '/')
  573. conf.nimcacheDir = processPath(conf, arg, info, notRelativeToProj=true)
  574. of "out", "o":
  575. expectArg(conf, switch, arg, pass, info)
  576. let f = splitFile(processPath(conf, arg, info, notRelativeToProj=true).string)
  577. conf.outFile = RelativeFile f.name & f.ext
  578. conf.outDir = toAbsoluteDir f.dir
  579. of "outdir":
  580. expectArg(conf, switch, arg, pass, info)
  581. conf.outDir = processPath(conf, arg, info, notRelativeToProj=true)
  582. of "usenimcache":
  583. processOnOffSwitchG(conf, {optUseNimcache}, arg, pass, info)
  584. of "docseesrcurl":
  585. expectArg(conf, switch, arg, pass, info)
  586. conf.docSeeSrcUrl = arg
  587. of "docroot":
  588. conf.docRoot = if arg.len == 0: docRootDefault else: arg
  589. of "backend", "b":
  590. let backend = parseEnum(arg.normalize, TBackend.default)
  591. if backend == TBackend.default: localError(conf, info, "invalid backend: '$1'" % arg)
  592. if backend == backendJs: # bug #21209
  593. conf.globalOptions.excl {optThreadAnalysis, optThreads}
  594. conf.backend = backend
  595. of "doccmd": conf.docCmd = arg
  596. of "define", "d":
  597. expectArg(conf, switch, arg, pass, info)
  598. if {':', '='} in arg:
  599. splitSwitch(conf, arg, key, val, pass, info)
  600. specialDefine(conf, key, pass)
  601. defineSymbol(conf.symbols, key, val)
  602. else:
  603. specialDefine(conf, arg, pass)
  604. defineSymbol(conf.symbols, arg)
  605. of "undef", "u":
  606. expectArg(conf, switch, arg, pass, info)
  607. undefSymbol(conf.symbols, arg)
  608. of "compile":
  609. expectArg(conf, switch, arg, pass, info)
  610. if pass in {passCmd2, passPP}: processCompile(conf, arg)
  611. of "link":
  612. expectArg(conf, switch, arg, pass, info)
  613. if pass in {passCmd2, passPP}:
  614. addExternalFileToLink(conf, AbsoluteFile arg)
  615. of "debuginfo":
  616. processOnOffSwitchG(conf, {optCDebug}, arg, pass, info)
  617. of "embedsrc":
  618. processOnOffSwitchG(conf, {optEmbedOrigSrc}, arg, pass, info)
  619. of "compileonly", "c":
  620. processOnOffSwitchG(conf, {optCompileOnly}, arg, pass, info)
  621. of "nolinking":
  622. processOnOffSwitchG(conf, {optNoLinking}, arg, pass, info)
  623. of "nomain":
  624. processOnOffSwitchG(conf, {optNoMain}, arg, pass, info)
  625. of "forcebuild", "f":
  626. processOnOffSwitchG(conf, {optForceFullMake}, arg, pass, info)
  627. of "project":
  628. processOnOffSwitchG(conf, {optWholeProject, optGenIndex}, arg, pass, info)
  629. of "gc":
  630. warningDeprecated(conf, info, "`gc:option` is deprecated; use `mm:option` instead")
  631. processMemoryManagementOption(switch, arg, pass, info, conf)
  632. of "mm":
  633. processMemoryManagementOption(switch, arg, pass, info, conf)
  634. of "warnings", "w":
  635. if processOnOffSwitchOrList(conf, {optWarns}, arg, pass, info): listWarnings(conf)
  636. of "warning": processSpecificNote(arg, wWarning, pass, info, switch, conf)
  637. of "hint": processSpecificNote(arg, wHint, pass, info, switch, conf)
  638. of "warningaserror": processSpecificNote(arg, wWarningAsError, pass, info, switch, conf)
  639. of "hintaserror": processSpecificNote(arg, wHintAsError, pass, info, switch, conf)
  640. of "hints":
  641. if processOnOffSwitchOrList(conf, {optHints}, arg, pass, info): listHints(conf)
  642. of "threadanalysis":
  643. if conf.backend == backendJs: discard
  644. else: processOnOffSwitchG(conf, {optThreadAnalysis}, arg, pass, info)
  645. of "stacktrace": processOnOffSwitch(conf, {optStackTrace}, arg, pass, info)
  646. of "stacktracemsgs": processOnOffSwitch(conf, {optStackTraceMsgs}, arg, pass, info)
  647. of "excessivestacktrace": processOnOffSwitchG(conf, {optExcessiveStackTrace}, arg, pass, info)
  648. of "linetrace": processOnOffSwitch(conf, {optLineTrace}, arg, pass, info)
  649. of "debugger":
  650. case arg.normalize
  651. of "on", "native", "gdb":
  652. conf.globalOptions.incl optCDebug
  653. conf.options.incl optLineDir
  654. #defineSymbol(conf.symbols, "nimTypeNames") # type names are used in gdb pretty printing
  655. of "off":
  656. conf.globalOptions.excl optCDebug
  657. else:
  658. localError(conf, info, "expected native|gdb|on|off but found " & arg)
  659. of "g": # alias for --debugger:native
  660. conf.globalOptions.incl optCDebug
  661. conf.options.incl optLineDir
  662. #defineSymbol(conf.symbols, "nimTypeNames") # type names are used in gdb pretty printing
  663. of "profiler":
  664. processOnOffSwitch(conf, {optProfiler}, arg, pass, info)
  665. if optProfiler in conf.options: defineSymbol(conf.symbols, "profiler")
  666. else: undefSymbol(conf.symbols, "profiler")
  667. of "memtracker":
  668. processOnOffSwitch(conf, {optMemTracker}, arg, pass, info)
  669. if optMemTracker in conf.options: defineSymbol(conf.symbols, "memtracker")
  670. else: undefSymbol(conf.symbols, "memtracker")
  671. of "hotcodereloading":
  672. processOnOffSwitchG(conf, {optHotCodeReloading}, arg, pass, info)
  673. if conf.hcrOn:
  674. defineSymbol(conf.symbols, "hotcodereloading")
  675. defineSymbol(conf.symbols, "useNimRtl")
  676. # hardcoded linking with dynamic runtime for MSVC for smaller binaries
  677. # should do the same for all compilers (wherever applicable)
  678. if isVSCompatible(conf):
  679. extccomp.addCompileOptionCmd(conf, "/MD")
  680. else:
  681. undefSymbol(conf.symbols, "hotcodereloading")
  682. undefSymbol(conf.symbols, "useNimRtl")
  683. of "checks", "x": processOnOffSwitch(conf, ChecksOptions, arg, pass, info)
  684. of "floatchecks":
  685. processOnOffSwitch(conf, {optNaNCheck, optInfCheck}, arg, pass, info)
  686. of "infchecks": processOnOffSwitch(conf, {optInfCheck}, arg, pass, info)
  687. of "nanchecks": processOnOffSwitch(conf, {optNaNCheck}, arg, pass, info)
  688. of "objchecks": processOnOffSwitch(conf, {optObjCheck}, arg, pass, info)
  689. of "fieldchecks": processOnOffSwitch(conf, {optFieldCheck}, arg, pass, info)
  690. of "rangechecks": processOnOffSwitch(conf, {optRangeCheck}, arg, pass, info)
  691. of "boundchecks": processOnOffSwitch(conf, {optBoundsCheck}, arg, pass, info)
  692. of "refchecks":
  693. warningDeprecated(conf, info, "refchecks is deprecated!")
  694. processOnOffSwitch(conf, {optRefCheck}, arg, pass, info)
  695. of "overflowchecks": processOnOffSwitch(conf, {optOverflowCheck}, arg, pass, info)
  696. of "staticboundchecks": processOnOffSwitch(conf, {optStaticBoundsCheck}, arg, pass, info)
  697. of "stylechecks": processOnOffSwitch(conf, {optStyleCheck}, arg, pass, info)
  698. of "linedir": processOnOffSwitch(conf, {optLineDir}, arg, pass, info)
  699. of "assertions", "a": processOnOffSwitch(conf, {optAssert}, arg, pass, info)
  700. of "threads":
  701. if conf.backend == backendJs or conf.cmd == cmdNimscript: discard
  702. else: processOnOffSwitchG(conf, {optThreads}, arg, pass, info)
  703. #if optThreads in conf.globalOptions: conf.setNote(warnGcUnsafe)
  704. of "tlsemulation": processOnOffSwitchG(conf, {optTlsEmulation}, arg, pass, info)
  705. of "implicitstatic":
  706. processOnOffSwitch(conf, {optImplicitStatic}, arg, pass, info)
  707. of "patterns", "trmacros":
  708. if switch.normalize == "patterns": deprecatedAlias(switch, "trmacros")
  709. processOnOffSwitch(conf, {optTrMacros}, arg, pass, info)
  710. of "opt":
  711. expectArg(conf, switch, arg, pass, info)
  712. case arg.normalize
  713. of "speed":
  714. incl(conf.options, optOptimizeSpeed)
  715. excl(conf.options, optOptimizeSize)
  716. of "size":
  717. excl(conf.options, optOptimizeSpeed)
  718. incl(conf.options, optOptimizeSize)
  719. of "none":
  720. excl(conf.options, optOptimizeSpeed)
  721. excl(conf.options, optOptimizeSize)
  722. else: localError(conf, info, errNoneSpeedOrSizeExpectedButXFound % arg)
  723. of "app":
  724. expectArg(conf, switch, arg, pass, info)
  725. case arg.normalize
  726. of "gui":
  727. incl(conf.globalOptions, optGenGuiApp)
  728. defineSymbol(conf.symbols, "executable")
  729. defineSymbol(conf.symbols, "guiapp")
  730. of "console":
  731. excl(conf.globalOptions, optGenGuiApp)
  732. defineSymbol(conf.symbols, "executable")
  733. defineSymbol(conf.symbols, "consoleapp")
  734. of "lib":
  735. incl(conf.globalOptions, optGenDynLib)
  736. excl(conf.globalOptions, optGenGuiApp)
  737. defineSymbol(conf.symbols, "library")
  738. defineSymbol(conf.symbols, "dll")
  739. of "staticlib":
  740. incl(conf.globalOptions, optGenStaticLib)
  741. excl(conf.globalOptions, optGenGuiApp)
  742. defineSymbol(conf.symbols, "library")
  743. defineSymbol(conf.symbols, "staticlib")
  744. else: localError(conf, info, errGuiConsoleOrLibExpectedButXFound % arg)
  745. of "passc", "t":
  746. expectArg(conf, switch, arg, pass, info)
  747. if pass in {passCmd2, passPP}: extccomp.addCompileOptionCmd(conf, arg)
  748. of "passl", "l":
  749. expectArg(conf, switch, arg, pass, info)
  750. if pass in {passCmd2, passPP}: extccomp.addLinkOptionCmd(conf, arg)
  751. of "cincludes":
  752. expectArg(conf, switch, arg, pass, info)
  753. if pass in {passCmd2, passPP}: conf.cIncludes.add processPath(conf, arg, info)
  754. of "clibdir":
  755. expectArg(conf, switch, arg, pass, info)
  756. if pass in {passCmd2, passPP}: conf.cLibs.add processPath(conf, arg, info)
  757. of "clib":
  758. expectArg(conf, switch, arg, pass, info)
  759. if pass in {passCmd2, passPP}:
  760. conf.cLinkedLibs.add arg
  761. of "header":
  762. if conf != nil: conf.headerFile = arg
  763. incl(conf.globalOptions, optGenIndex)
  764. of "index":
  765. case arg.normalize
  766. of "", "on": conf.globalOptions.incl {optGenIndex}
  767. of "only": conf.globalOptions.incl {optGenIndexOnly, optGenIndex}
  768. of "off": conf.globalOptions.excl {optGenIndex, optGenIndexOnly}
  769. else: localError(conf, info, errOnOrOffExpectedButXFound % arg)
  770. of "noimportdoc":
  771. processOnOffSwitchG(conf, {optNoImportdoc}, arg, pass, info)
  772. of "import":
  773. expectArg(conf, switch, arg, pass, info)
  774. if pass in {passCmd2, passPP}:
  775. conf.implicitImports.add findModule(conf, arg, toFullPath(conf, info)).string
  776. of "include":
  777. expectArg(conf, switch, arg, pass, info)
  778. if pass in {passCmd2, passPP}:
  779. conf.implicitIncludes.add findModule(conf, arg, toFullPath(conf, info)).string
  780. of "listcmd":
  781. processOnOffSwitchG(conf, {optListCmd}, arg, pass, info)
  782. of "asm":
  783. processOnOffSwitchG(conf, {optProduceAsm}, arg, pass, info)
  784. of "genmapping":
  785. processOnOffSwitchG(conf, {optGenMapping}, arg, pass, info)
  786. of "os":
  787. expectArg(conf, switch, arg, pass, info)
  788. let theOS = platform.nameToOS(arg)
  789. if theOS == osNone:
  790. let osList = platform.listOSnames().join(", ")
  791. localError(conf, info, "unknown OS: '$1'. Available options are: $2" % [arg, $osList])
  792. else:
  793. setTarget(conf.target, theOS, conf.target.targetCPU)
  794. of "cpu":
  795. expectArg(conf, switch, arg, pass, info)
  796. let cpu = platform.nameToCPU(arg)
  797. if cpu == cpuNone:
  798. let cpuList = platform.listCPUnames().join(", ")
  799. localError(conf, info, "unknown CPU: '$1'. Available options are: $2" % [ arg, cpuList])
  800. else:
  801. setTarget(conf.target, conf.target.targetOS, cpu)
  802. of "run", "r":
  803. processOnOffSwitchG(conf, {optRun}, arg, pass, info)
  804. of "maxloopiterationsvm":
  805. expectArg(conf, switch, arg, pass, info)
  806. conf.maxLoopIterationsVM = parseInt(arg)
  807. of "errormax":
  808. expectArg(conf, switch, arg, pass, info)
  809. # Note: `nim check` (etc) can overwrite this.
  810. # `0` is meaningless, give it a useful meaning as in clang's -ferror-limit
  811. # If user doesn't set this flag and the code doesn't either, it'd
  812. # have the same effect as errorMax = 1
  813. let ret = parseInt(arg)
  814. conf.errorMax = if ret == 0: high(int) else: ret
  815. of "verbosity":
  816. expectArg(conf, switch, arg, pass, info)
  817. let verbosity = parseInt(arg)
  818. if verbosity notin 0..3:
  819. localError(conf, info, "invalid verbosity level: '$1'" % arg)
  820. conf.verbosity = verbosity
  821. var verb = NotesVerbosity[conf.verbosity]
  822. ## We override the default `verb` by explicitly modified (set/unset) notes.
  823. conf.notes = (conf.modifiedyNotes * conf.notes + verb) -
  824. (conf.modifiedyNotes * verb - conf.notes)
  825. conf.mainPackageNotes = conf.notes
  826. of "parallelbuild":
  827. expectArg(conf, switch, arg, pass, info)
  828. conf.numberOfProcessors = parseInt(arg)
  829. of "version", "v":
  830. expectNoArg(conf, switch, arg, pass, info)
  831. writeVersionInfo(conf, pass)
  832. of "advanced":
  833. expectNoArg(conf, switch, arg, pass, info)
  834. writeAdvancedUsage(conf, pass)
  835. of "fullhelp":
  836. expectNoArg(conf, switch, arg, pass, info)
  837. writeFullhelp(conf, pass)
  838. of "help", "h":
  839. expectNoArg(conf, switch, arg, pass, info)
  840. helpOnError(conf, pass)
  841. of "symbolfiles", "incremental", "ic":
  842. if switch.normalize == "symbolfiles": deprecatedAlias(switch, "incremental")
  843. # xxx maybe also ic, since not in help?
  844. if pass in {passCmd2, passPP}:
  845. case arg.normalize
  846. of "on": conf.symbolFiles = v2Sf
  847. of "off": conf.symbolFiles = disabledSf
  848. of "writeonly": conf.symbolFiles = writeOnlySf
  849. of "readonly": conf.symbolFiles = readOnlySf
  850. of "v2": conf.symbolFiles = v2Sf
  851. of "stress": conf.symbolFiles = stressTest
  852. else: localError(conf, info, "invalid option for --incremental: " & arg)
  853. setUseIc(conf.symbolFiles != disabledSf)
  854. of "skipcfg":
  855. processOnOffSwitchG(conf, {optSkipSystemConfigFile}, arg, pass, info)
  856. of "skipprojcfg":
  857. processOnOffSwitchG(conf, {optSkipProjConfigFile}, arg, pass, info)
  858. of "skipusercfg":
  859. processOnOffSwitchG(conf, {optSkipUserConfigFile}, arg, pass, info)
  860. of "skipparentcfg":
  861. processOnOffSwitchG(conf, {optSkipParentConfigFiles}, arg, pass, info)
  862. of "genscript", "gendeps":
  863. if switch.normalize == "gendeps": deprecatedAlias(switch, "genscript")
  864. processOnOffSwitchG(conf, {optGenScript}, arg, pass, info)
  865. processOnOffSwitchG(conf, {optCompileOnly}, arg, pass, info)
  866. of "gencdeps":
  867. processOnOffSwitchG(conf, {optGenCDeps}, arg, pass, info)
  868. of "colors": processOnOffSwitchG(conf, {optUseColors}, arg, pass, info)
  869. of "lib":
  870. expectArg(conf, switch, arg, pass, info)
  871. conf.libpath = processPath(conf, arg, info, notRelativeToProj=true)
  872. of "putenv":
  873. expectArg(conf, switch, arg, pass, info)
  874. splitSwitch(conf, arg, key, val, pass, info)
  875. os.putEnv(key, val)
  876. of "cc":
  877. if conf.backend != backendJs: # bug #19330
  878. expectArg(conf, switch, arg, pass, info)
  879. setCC(conf, arg, info)
  880. of "track":
  881. expectArg(conf, switch, arg, pass, info)
  882. track(conf, arg, info)
  883. of "trackdirty":
  884. expectArg(conf, switch, arg, pass, info)
  885. trackDirty(conf, arg, info)
  886. of "suggest":
  887. expectNoArg(conf, switch, arg, pass, info)
  888. conf.ideCmd = ideSug
  889. of "def":
  890. expectArg(conf, switch, arg, pass, info)
  891. trackIde(conf, ideDef, arg, info)
  892. of "context":
  893. expectNoArg(conf, switch, arg, pass, info)
  894. conf.ideCmd = ideCon
  895. of "usages":
  896. expectArg(conf, switch, arg, pass, info)
  897. trackIde(conf, ideUse, arg, info)
  898. of "defusages":
  899. expectArg(conf, switch, arg, pass, info)
  900. trackIde(conf, ideDus, arg, info)
  901. of "stdout":
  902. processOnOffSwitchG(conf, {optStdout}, arg, pass, info)
  903. of "filenames":
  904. case arg.normalize
  905. of "abs": conf.filenameOption = foAbs
  906. of "canonical": conf.filenameOption = foCanonical
  907. of "legacyrelproj": conf.filenameOption = foLegacyRelProj
  908. else: localError(conf, info, "expected: abs|canonical|legacyRelProj, got: $1" % arg)
  909. of "processing":
  910. incl(conf.notes, hintProcessing)
  911. incl(conf.mainPackageNotes, hintProcessing)
  912. case arg.normalize
  913. of "dots": conf.hintProcessingDots = true
  914. of "filenames": conf.hintProcessingDots = false
  915. of "off":
  916. excl(conf.notes, hintProcessing)
  917. excl(conf.mainPackageNotes, hintProcessing)
  918. else: localError(conf, info, "expected: dots|filenames|off, got: $1" % arg)
  919. of "unitsep":
  920. conf.unitSep = if switchOn(arg): "\31" else: ""
  921. of "listfullpaths":
  922. # xxx in future work, use `warningDeprecated`
  923. conf.filenameOption = if switchOn(arg): foAbs else: foCanonical
  924. of "spellsuggest":
  925. if arg.len == 0: conf.spellSuggestMax = spellSuggestSecretSauce
  926. elif arg == "auto": conf.spellSuggestMax = spellSuggestSecretSauce
  927. else: conf.spellSuggestMax = parseInt(arg)
  928. of "declaredlocs":
  929. processOnOffSwitchG(conf, {optDeclaredLocs}, arg, pass, info)
  930. of "dynliboverride":
  931. dynlibOverride(conf, switch, arg, pass, info)
  932. of "dynliboverrideall":
  933. processOnOffSwitchG(conf, {optDynlibOverrideAll}, arg, pass, info)
  934. of "experimental":
  935. if arg.len == 0:
  936. conf.features.incl oldExperimentalFeatures
  937. else:
  938. try:
  939. conf.features.incl parseEnum[Feature](arg)
  940. except ValueError:
  941. localError(conf, info, "unknown experimental feature")
  942. of "legacy":
  943. try:
  944. conf.legacyFeatures.incl parseEnum[LegacyFeature](arg)
  945. except ValueError:
  946. localError(conf, info, "unknown obsolete feature")
  947. of "nocppexceptions":
  948. expectNoArg(conf, switch, arg, pass, info)
  949. conf.exc = low(ExceptionSystem)
  950. defineSymbol(conf.symbols, "noCppExceptions")
  951. of "shownonexports":
  952. expectNoArg(conf, switch, arg, pass, info)
  953. showNonExportedFields(conf)
  954. of "exceptions":
  955. case arg.normalize
  956. of "cpp": conf.exc = excCpp
  957. of "setjmp": conf.exc = excSetjmp
  958. of "quirky": conf.exc = excQuirky
  959. of "goto": conf.exc = excGoto
  960. else: localError(conf, info, errInvalidExceptionSystem % arg)
  961. of "cppdefine":
  962. expectArg(conf, switch, arg, pass, info)
  963. if conf != nil:
  964. conf.cppDefine(arg)
  965. of "newruntime":
  966. warningDeprecated(conf, info, "newruntime is deprecated, use arc/orc instead!")
  967. expectNoArg(conf, switch, arg, pass, info)
  968. if pass in {passCmd2, passPP}:
  969. doAssert(conf != nil)
  970. incl(conf.features, destructor)
  971. incl(conf.globalOptions, optTinyRtti)
  972. incl(conf.globalOptions, optOwnedRefs)
  973. incl(conf.globalOptions, optSeqDestructors)
  974. defineSymbol(conf.symbols, "nimV2")
  975. conf.selectedGC = gcHooks
  976. defineSymbol(conf.symbols, "gchooks")
  977. defineSymbol(conf.symbols, "nimSeqsV2")
  978. defineSymbol(conf.symbols, "nimOwnedEnabled")
  979. of "seqsv2":
  980. processOnOffSwitchG(conf, {optSeqDestructors}, arg, pass, info)
  981. if pass in {passCmd2, passPP}:
  982. defineSymbol(conf.symbols, "nimSeqsV2")
  983. of "stylecheck":
  984. case arg.normalize
  985. of "off": conf.globalOptions = conf.globalOptions - {optStyleHint, optStyleError}
  986. of "hint": conf.globalOptions = conf.globalOptions + {optStyleHint} - {optStyleError}
  987. of "error": conf.globalOptions = conf.globalOptions + {optStyleError}
  988. of "usages": conf.globalOptions.incl optStyleUsages
  989. else: localError(conf, info, errOffHintsError % arg)
  990. of "showallmismatches":
  991. processOnOffSwitchG(conf, {optShowAllMismatches}, arg, pass, info)
  992. of "cppcompiletonamespace":
  993. if arg.len > 0:
  994. conf.cppCustomNamespace = arg
  995. else:
  996. conf.cppCustomNamespace = "Nim"
  997. defineSymbol(conf.symbols, "cppCompileToNamespace", conf.cppCustomNamespace)
  998. of "docinternal":
  999. processOnOffSwitchG(conf, {optDocInternal}, arg, pass, info)
  1000. of "multimethods":
  1001. processOnOffSwitchG(conf, {optMultiMethods}, arg, pass, info)
  1002. of "expandmacro":
  1003. expectArg(conf, switch, arg, pass, info)
  1004. conf.macrosToExpand[arg] = "T"
  1005. of "expandarc":
  1006. expectArg(conf, switch, arg, pass, info)
  1007. conf.arcToExpand[arg] = "T"
  1008. of "benchmarkvm":
  1009. processOnOffSwitchG(conf, {optBenchmarkVM}, arg, pass, info)
  1010. of "profilevm":
  1011. processOnOffSwitchG(conf, {optProfileVM}, arg, pass, info)
  1012. of "sinkinference":
  1013. processOnOffSwitch(conf, {optSinkInference}, arg, pass, info)
  1014. of "cursorinference":
  1015. # undocumented, for debugging purposes only:
  1016. processOnOffSwitch(conf, {optCursorInference}, arg, pass, info)
  1017. of "panics":
  1018. processOnOffSwitchG(conf, {optPanics}, arg, pass, info)
  1019. if optPanics in conf.globalOptions:
  1020. defineSymbol(conf.symbols, "nimPanics")
  1021. of "jsbigint64":
  1022. processOnOffSwitchG(conf, {optJsBigInt64}, arg, pass, info)
  1023. of "sourcemap": # xxx document in --fullhelp
  1024. conf.globalOptions.incl optSourcemap
  1025. conf.options.incl optLineDir
  1026. of "deepcopy":
  1027. processOnOffSwitchG(conf, {optEnableDeepCopy}, arg, pass, info)
  1028. of "": # comes from "-" in for example: `nim c -r -` (gets stripped from -)
  1029. handleStdinInput(conf)
  1030. of "nilseqs", "nilchecks", "symbol", "taintmode", "cs", "deadcodeelim": warningOptionNoop(switch)
  1031. of "nimmainprefix": conf.nimMainPrefix = arg
  1032. else:
  1033. if strutils.find(switch, '.') >= 0: options.setConfigVar(conf, switch, arg)
  1034. else: invalidCmdLineOption(conf, pass, switch, info)
  1035. proc processCommand*(switch: string, pass: TCmdLinePass; config: ConfigRef) =
  1036. var cmd, arg: string
  1037. splitSwitch(config, switch, cmd, arg, pass, gCmdLineInfo)
  1038. processSwitch(cmd, arg, pass, gCmdLineInfo, config)
  1039. proc processSwitch*(pass: TCmdLinePass; p: OptParser; config: ConfigRef) =
  1040. # hint[X]:off is parsed as (p.key = "hint[X]", p.val = "off")
  1041. # we transform it to (key = hint, val = [X]:off)
  1042. var bracketLe = strutils.find(p.key, '[')
  1043. if bracketLe >= 0:
  1044. var key = substr(p.key, 0, bracketLe - 1)
  1045. var val = substr(p.key, bracketLe) & ':' & p.val
  1046. processSwitch(key, val, pass, gCmdLineInfo, config)
  1047. else:
  1048. processSwitch(p.key, p.val, pass, gCmdLineInfo, config)
  1049. proc processArgument*(pass: TCmdLinePass; p: OptParser;
  1050. argsCount: var int; config: ConfigRef): bool =
  1051. if argsCount == 0 and config.implicitCmd:
  1052. argsCount.inc
  1053. if argsCount == 0:
  1054. # nim filename.nims is the same as "nim e filename.nims":
  1055. if p.key.endsWith(".nims"):
  1056. config.setCmd cmdNimscript
  1057. incl(config.globalOptions, optWasNimscript)
  1058. config.projectName = unixToNativePath(p.key)
  1059. config.arguments = cmdLineRest(p)
  1060. result = true
  1061. elif pass != passCmd2: setCommandEarly(config, p.key)
  1062. else:
  1063. if pass == passCmd1: config.commandArgs.add p.key
  1064. if argsCount == 1:
  1065. if p.key.endsWith(".nims"):
  1066. incl(config.globalOptions, optWasNimscript)
  1067. # support UNIX style filenames everywhere for portable build scripts:
  1068. if config.projectName.len == 0:
  1069. config.projectName = unixToNativePath(p.key)
  1070. config.arguments = cmdLineRest(p)
  1071. result = true
  1072. inc argsCount