commands.nim 48 KB

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