commands.nim 49 KB

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