commands.nim 49 KB

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