commands.nim 49 KB

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