commands.nim 49 KB

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