msgs.nim 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. import
  10. std/[strutils, os, tables, terminal, macros, times],
  11. std/private/miscdollars,
  12. options, ropes, lineinfos, pathutils, strutils2
  13. type InstantiationInfo* = typeof(instantiationInfo())
  14. template instLoc*(): InstantiationInfo = instantiationInfo(-2, fullPaths = true)
  15. template toStdOrrKind(stdOrr): untyped =
  16. if stdOrr == stdout: stdOrrStdout else: stdOrrStderr
  17. proc flushDot*(conf: ConfigRef) =
  18. ## safe to call multiple times
  19. # xxx one edge case not yet handled is when `printf` is called at CT with `compiletimeFFI`.
  20. let stdOrr = if optStdout in conf.globalOptions: stdout else: stderr
  21. let stdOrrKind = toStdOrrKind(stdOrr)
  22. if stdOrrKind in conf.lastMsgWasDot:
  23. conf.lastMsgWasDot.excl stdOrrKind
  24. write(stdOrr, "\n")
  25. proc toCChar*(c: char; result: var string) {.inline.} =
  26. case c
  27. of '\0'..'\x1F', '\x7F'..'\xFF':
  28. result.add '\\'
  29. result.add toOctal(c)
  30. of '\'', '\"', '\\', '?':
  31. result.add '\\'
  32. result.add c
  33. else:
  34. result.add c
  35. proc makeCString*(s: string): Rope =
  36. result = nil
  37. var res = newStringOfCap(int(s.len.toFloat * 1.1) + 1)
  38. res.add("\"")
  39. for i in 0..<s.len:
  40. # line wrapping of string litterals in cgen'd code was a bad idea, e.g. causes: bug #16265
  41. # It also makes reading c sources or grepping harder, for zero benefit.
  42. # const MaxLineLength = 64
  43. # if (i + 1) mod MaxLineLength == 0:
  44. # res.add("\"\L\"")
  45. toCChar(s[i], res)
  46. res.add('\"')
  47. result.add(rope(res))
  48. proc newFileInfo(fullPath: AbsoluteFile, projPath: RelativeFile): TFileInfo =
  49. result.fullPath = fullPath
  50. #shallow(result.fullPath)
  51. result.projPath = projPath
  52. #shallow(result.projPath)
  53. result.shortName = fullPath.extractFilename
  54. result.quotedName = result.shortName.makeCString
  55. result.quotedFullName = fullPath.string.makeCString
  56. result.lines = @[]
  57. when defined(nimpretty):
  58. if not result.fullPath.isEmpty:
  59. try:
  60. result.fullContent = readFile(result.fullPath.string)
  61. except IOError:
  62. #rawMessage(errCannotOpenFile, result.fullPath)
  63. # XXX fixme
  64. result.fullContent = ""
  65. when defined(nimpretty):
  66. proc fileSection*(conf: ConfigRef; fid: FileIndex; a, b: int): string =
  67. substr(conf.m.fileInfos[fid.int].fullContent, a, b)
  68. proc canonicalCase(path: var string) =
  69. ## the idea is to only use this for checking whether a path is already in
  70. ## the table but otherwise keep the original case
  71. when FileSystemCaseSensitive: discard
  72. else: toLowerAscii(path)
  73. proc fileInfoKnown*(conf: ConfigRef; filename: AbsoluteFile): bool =
  74. var
  75. canon: AbsoluteFile
  76. try:
  77. canon = canonicalizePath(conf, filename)
  78. except OSError:
  79. canon = filename
  80. canon.string.canonicalCase
  81. result = conf.m.filenameToIndexTbl.hasKey(canon.string)
  82. proc fileInfoIdx*(conf: ConfigRef; filename: AbsoluteFile; isKnownFile: var bool): FileIndex =
  83. var
  84. canon: AbsoluteFile
  85. pseudoPath = false
  86. try:
  87. canon = canonicalizePath(conf, filename)
  88. shallow(canon.string)
  89. except OSError:
  90. canon = filename
  91. # The compiler uses "filenames" such as `command line` or `stdin`
  92. # This flag indicates that we are working with such a path here
  93. pseudoPath = true
  94. var canon2: string
  95. forceCopy(canon2, canon.string) # because `canon` may be shallow
  96. canon2.canonicalCase
  97. if conf.m.filenameToIndexTbl.hasKey(canon2):
  98. isKnownFile = true
  99. result = conf.m.filenameToIndexTbl[canon2]
  100. else:
  101. isKnownFile = false
  102. result = conf.m.fileInfos.len.FileIndex
  103. #echo "ID ", result.int, " ", canon2
  104. conf.m.fileInfos.add(newFileInfo(canon, if pseudoPath: RelativeFile filename
  105. else: relativeTo(canon, conf.projectPath)))
  106. conf.m.filenameToIndexTbl[canon2] = result
  107. proc fileInfoIdx*(conf: ConfigRef; filename: AbsoluteFile): FileIndex =
  108. var dummy: bool
  109. result = fileInfoIdx(conf, filename, dummy)
  110. proc fileInfoIdx*(conf: ConfigRef; filename: RelativeFile; isKnownFile: var bool): FileIndex =
  111. fileInfoIdx(conf, AbsoluteFile expandFilename(filename.string), isKnownFile)
  112. proc fileInfoIdx*(conf: ConfigRef; filename: RelativeFile): FileIndex =
  113. var dummy: bool
  114. fileInfoIdx(conf, AbsoluteFile expandFilename(filename.string), dummy)
  115. proc newLineInfo*(fileInfoIdx: FileIndex, line, col: int): TLineInfo =
  116. result.fileIndex = fileInfoIdx
  117. if line < int high(uint16):
  118. result.line = uint16(line)
  119. else:
  120. result.line = high(uint16)
  121. if col < int high(int16):
  122. result.col = int16(col)
  123. else:
  124. result.col = -1
  125. proc newLineInfo*(conf: ConfigRef; filename: AbsoluteFile, line, col: int): TLineInfo {.inline.} =
  126. result = newLineInfo(fileInfoIdx(conf, filename), line, col)
  127. const gCmdLineInfo* = newLineInfo(commandLineIdx, 1, 1)
  128. proc concat(strings: openArray[string]): string =
  129. var totalLen = 0
  130. for s in strings: totalLen += s.len
  131. result = newStringOfCap totalLen
  132. for s in strings: result.add s
  133. proc suggestWriteln*(conf: ConfigRef; s: string) =
  134. if eStdOut in conf.m.errorOutputs:
  135. if isNil(conf.writelnHook):
  136. writeLine(stdout, s)
  137. flushFile(stdout)
  138. else:
  139. conf.writelnHook(s)
  140. proc msgQuit*(x: int8) = quit x
  141. proc msgQuit*(x: string) = quit x
  142. proc suggestQuit*() =
  143. raise newException(ESuggestDone, "suggest done")
  144. # this format is understood by many text editors: it is the same that
  145. # Borland and Freepascal use
  146. const
  147. KindFormat = " [$1]"
  148. KindColor = fgCyan
  149. ErrorTitle = "Error: "
  150. ErrorColor = fgRed
  151. WarningTitle = "Warning: "
  152. WarningColor = fgYellow
  153. HintTitle = "Hint: "
  154. HintColor = fgGreen
  155. # NOTE: currently line info line numbers start with 1,
  156. # but column numbers start with 0, however most editors expect
  157. # first column to be 1, so we need to +1 here
  158. ColOffset* = 1
  159. commandLineDesc* = "command line"
  160. proc getInfoContextLen*(conf: ConfigRef): int = return conf.m.msgContext.len
  161. proc setInfoContextLen*(conf: ConfigRef; L: int) = setLen(conf.m.msgContext, L)
  162. proc pushInfoContext*(conf: ConfigRef; info: TLineInfo; detail: string = "") =
  163. conf.m.msgContext.add((info, detail))
  164. proc popInfoContext*(conf: ConfigRef) =
  165. setLen(conf.m.msgContext, conf.m.msgContext.len - 1)
  166. proc getInfoContext*(conf: ConfigRef; index: int): TLineInfo =
  167. let i = if index < 0: conf.m.msgContext.len + index else: index
  168. if i >=% conf.m.msgContext.len: result = unknownLineInfo
  169. else: result = conf.m.msgContext[i].info
  170. template toFilename*(conf: ConfigRef; fileIdx: FileIndex): string =
  171. if fileIdx.int32 < 0 or conf == nil:
  172. (if fileIdx == commandLineIdx: commandLineDesc else: "???")
  173. else:
  174. conf.m.fileInfos[fileIdx.int32].shortName
  175. proc toProjPath*(conf: ConfigRef; fileIdx: FileIndex): string =
  176. if fileIdx.int32 < 0 or conf == nil:
  177. (if fileIdx == commandLineIdx: commandLineDesc else: "???")
  178. else: conf.m.fileInfos[fileIdx.int32].projPath.string
  179. proc toFullPath*(conf: ConfigRef; fileIdx: FileIndex): string =
  180. if fileIdx.int32 < 0 or conf == nil:
  181. result = (if fileIdx == commandLineIdx: commandLineDesc else: "???")
  182. else:
  183. result = conf.m.fileInfos[fileIdx.int32].fullPath.string
  184. proc setDirtyFile*(conf: ConfigRef; fileIdx: FileIndex; filename: AbsoluteFile) =
  185. assert fileIdx.int32 >= 0
  186. conf.m.fileInfos[fileIdx.int32].dirtyFile = filename
  187. setLen conf.m.fileInfos[fileIdx.int32].lines, 0
  188. proc setHash*(conf: ConfigRef; fileIdx: FileIndex; hash: string) =
  189. assert fileIdx.int32 >= 0
  190. shallowCopy(conf.m.fileInfos[fileIdx.int32].hash, hash)
  191. proc getHash*(conf: ConfigRef; fileIdx: FileIndex): string =
  192. assert fileIdx.int32 >= 0
  193. shallowCopy(result, conf.m.fileInfos[fileIdx.int32].hash)
  194. proc toFullPathConsiderDirty*(conf: ConfigRef; fileIdx: FileIndex): AbsoluteFile =
  195. if fileIdx.int32 < 0:
  196. result = AbsoluteFile(if fileIdx == commandLineIdx: commandLineDesc else: "???")
  197. elif not conf.m.fileInfos[fileIdx.int32].dirtyFile.isEmpty:
  198. result = conf.m.fileInfos[fileIdx.int32].dirtyFile
  199. else:
  200. result = conf.m.fileInfos[fileIdx.int32].fullPath
  201. template toFilename*(conf: ConfigRef; info: TLineInfo): string =
  202. toFilename(conf, info.fileIndex)
  203. template toProjPath*(conf: ConfigRef; info: TLineInfo): string =
  204. toProjPath(conf, info.fileIndex)
  205. template toFullPath*(conf: ConfigRef; info: TLineInfo): string =
  206. toFullPath(conf, info.fileIndex)
  207. template toFullPathConsiderDirty*(conf: ConfigRef; info: TLineInfo): string =
  208. string toFullPathConsiderDirty(conf, info.fileIndex)
  209. proc toFilenameOption*(conf: ConfigRef, fileIdx: FileIndex, opt: FilenameOption): string =
  210. case opt
  211. of foAbs: result = toFullPath(conf, fileIdx)
  212. of foRelProject: result = toProjPath(conf, fileIdx)
  213. of foCanonical:
  214. let absPath = toFullPath(conf, fileIdx)
  215. result = canonicalImportAux(conf, absPath.AbsoluteFile)
  216. of foName: result = toProjPath(conf, fileIdx).lastPathPart
  217. of foLegacyRelProj:
  218. let
  219. absPath = toFullPath(conf, fileIdx)
  220. relPath = toProjPath(conf, fileIdx)
  221. result = if (relPath.len > absPath.len) or (relPath.count("..") > 2):
  222. absPath
  223. else:
  224. relPath
  225. of foStacktrace:
  226. if optExcessiveStackTrace in conf.globalOptions:
  227. result = toFilenameOption(conf, fileIdx, foAbs)
  228. else:
  229. result = toFilenameOption(conf, fileIdx, foName)
  230. proc toMsgFilename*(conf: ConfigRef; fileIdx: FileIndex): string =
  231. toFilenameOption(conf, fileIdx, conf.filenameOption)
  232. template toMsgFilename*(conf: ConfigRef; info: TLineInfo): string =
  233. toMsgFilename(conf, info.fileIndex)
  234. proc toLinenumber*(info: TLineInfo): int {.inline.} =
  235. result = int info.line
  236. proc toColumn*(info: TLineInfo): int {.inline.} =
  237. result = info.col
  238. proc toFileLineCol(info: InstantiationInfo): string {.inline.} =
  239. result.toLocation(info.filename, info.line, info.column + ColOffset)
  240. proc toFileLineCol*(conf: ConfigRef; info: TLineInfo): string {.inline.} =
  241. result.toLocation(toMsgFilename(conf, info), info.line.int, info.col.int + ColOffset)
  242. proc `$`*(conf: ConfigRef; info: TLineInfo): string = toFileLineCol(conf, info)
  243. proc `$`*(info: TLineInfo): string {.error.} = discard
  244. proc `??`* (conf: ConfigRef; info: TLineInfo, filename: string): bool =
  245. # only for debugging purposes
  246. result = filename in toFilename(conf, info)
  247. type
  248. MsgFlag* = enum ## flags altering msgWriteln behavior
  249. msgStdout, ## force writing to stdout, even stderr is default
  250. msgSkipHook ## skip message hook even if it is present
  251. msgNoUnitSep ## the message is a complete "paragraph".
  252. MsgFlags* = set[MsgFlag]
  253. proc msgWriteln*(conf: ConfigRef; s: string, flags: MsgFlags = {}) =
  254. ## Writes given message string to stderr by default.
  255. ## If ``--stdout`` option is given, writes to stdout instead. If message hook
  256. ## is present, then it is used to output message rather than stderr/stdout.
  257. ## This behavior can be altered by given optional flags.
  258. ## This is used for 'nim dump' etc. where we don't have nimsuggest
  259. ## support.
  260. #if conf.cmd == cmdIdeTools and optCDebug notin gGlobalOptions: return
  261. let sep = if msgNoUnitSep notin flags: conf.unitSep else: ""
  262. if not isNil(conf.writelnHook) and msgSkipHook notin flags:
  263. conf.writelnHook(s & sep)
  264. elif optStdout in conf.globalOptions or msgStdout in flags:
  265. if eStdOut in conf.m.errorOutputs:
  266. flushDot(conf)
  267. write stdout, s
  268. writeLine(stdout, sep)
  269. flushFile(stdout)
  270. else:
  271. if eStdErr in conf.m.errorOutputs:
  272. flushDot(conf)
  273. write stderr, s
  274. writeLine(stderr, sep)
  275. # On Windows stderr is fully-buffered when piped, regardless of C std.
  276. when defined(windows):
  277. flushFile(stderr)
  278. macro callIgnoringStyle(theProc: typed, first: typed,
  279. args: varargs[typed]): untyped =
  280. let typForegroundColor = bindSym"ForegroundColor".getType
  281. let typBackgroundColor = bindSym"BackgroundColor".getType
  282. let typStyle = bindSym"Style".getType
  283. let typTerminalCmd = bindSym"TerminalCmd".getType
  284. result = newCall(theProc)
  285. if first.kind != nnkNilLit: result.add(first)
  286. for arg in children(args[0][1]):
  287. if arg.kind == nnkNilLit: continue
  288. let typ = arg.getType
  289. if typ.kind != nnkEnumTy or
  290. typ != typForegroundColor and
  291. typ != typBackgroundColor and
  292. typ != typStyle and
  293. typ != typTerminalCmd:
  294. result.add(arg)
  295. macro callStyledWriteLineStderr(args: varargs[typed]): untyped =
  296. result = newCall(bindSym"styledWriteLine")
  297. result.add(bindSym"stderr")
  298. for arg in children(args[0][1]):
  299. result.add(arg)
  300. when false:
  301. # not needed because styledWriteLine already ends with resetAttributes
  302. result = newStmtList(result, newCall(bindSym"resetAttributes", bindSym"stderr"))
  303. template callWritelnHook(args: varargs[string, `$`]) =
  304. conf.writelnHook concat(args)
  305. proc msgWrite(conf: ConfigRef; s: string) =
  306. if conf.m.errorOutputs != {}:
  307. let stdOrr =
  308. if optStdout in conf.globalOptions:
  309. stdout
  310. else:
  311. stderr
  312. write(stdOrr, s)
  313. flushFile(stdOrr)
  314. conf.lastMsgWasDot.incl stdOrr.toStdOrrKind() # subsequent writes need `flushDot`
  315. template styledMsgWriteln(args: varargs[typed]) =
  316. if not isNil(conf.writelnHook):
  317. callIgnoringStyle(callWritelnHook, nil, args)
  318. elif optStdout in conf.globalOptions:
  319. if eStdOut in conf.m.errorOutputs:
  320. flushDot(conf)
  321. callIgnoringStyle(writeLine, stdout, args)
  322. flushFile(stdout)
  323. elif eStdErr in conf.m.errorOutputs:
  324. flushDot(conf)
  325. if optUseColors in conf.globalOptions:
  326. callStyledWriteLineStderr(args)
  327. else:
  328. callIgnoringStyle(writeLine, stderr, args)
  329. # On Windows stderr is fully-buffered when piped, regardless of C std.
  330. when defined(windows):
  331. flushFile(stderr)
  332. proc msgKindToString*(kind: TMsgKind): string = MsgKindToStr[kind]
  333. # later versions may provide translated error messages
  334. proc getMessageStr(msg: TMsgKind, arg: string): string = msgKindToString(msg) % [arg]
  335. type TErrorHandling* = enum doNothing, doAbort, doRaise
  336. proc log*(s: string) =
  337. var f: File
  338. if open(f, getHomeDir() / "nimsuggest.log", fmAppend):
  339. f.writeLine(s)
  340. close(f)
  341. proc quit(conf: ConfigRef; msg: TMsgKind) {.gcsafe.} =
  342. if conf.isDefined("nimDebug"): quitOrRaise(conf, $msg)
  343. elif defined(debug) or msg == errInternal or conf.hasHint(hintStackTrace):
  344. {.gcsafe.}:
  345. if stackTraceAvailable() and isNil(conf.writelnHook):
  346. writeStackTrace()
  347. else:
  348. styledMsgWriteln(fgRed, """
  349. No stack traceback available
  350. To create a stacktrace, rerun compilation with './koch temp $1 <file>', see $2 for details""" %
  351. [conf.command, "intern.html#debugging-the-compiler".createDocLink], conf.unitSep)
  352. quit 1
  353. proc handleError(conf: ConfigRef; msg: TMsgKind, eh: TErrorHandling, s: string, ignoreMsg: bool) =
  354. if msg in fatalMsgs:
  355. if conf.cmd == cmdIdeTools: log(s)
  356. quit(conf, msg)
  357. if msg >= errMin and msg <= errMax or
  358. (msg in warnMin..hintMax and msg in conf.warningAsErrors and not ignoreMsg):
  359. inc(conf.errorCounter)
  360. conf.exitcode = 1'i8
  361. if conf.errorCounter >= conf.errorMax:
  362. # only really quit when we're not in the new 'nim check --def' mode:
  363. if conf.ideCmd == ideNone:
  364. quit(conf, msg)
  365. elif eh == doAbort and conf.cmd != cmdIdeTools:
  366. quit(conf, msg)
  367. elif eh == doRaise:
  368. raiseRecoverableError(s)
  369. proc `==`*(a, b: TLineInfo): bool =
  370. result = a.line == b.line and a.fileIndex == b.fileIndex
  371. proc exactEquals*(a, b: TLineInfo): bool =
  372. result = a.fileIndex == b.fileIndex and a.line == b.line and a.col == b.col
  373. proc writeContext(conf: ConfigRef; lastinfo: TLineInfo) =
  374. const instantiationFrom = "template/generic instantiation from here"
  375. const instantiationOfFrom = "template/generic instantiation of `$1` from here"
  376. var info = lastinfo
  377. for i in 0..<conf.m.msgContext.len:
  378. let context = conf.m.msgContext[i]
  379. if context.info != lastinfo and context.info != info:
  380. if conf.structuredErrorHook != nil:
  381. conf.structuredErrorHook(conf, context.info, instantiationFrom,
  382. Severity.Hint)
  383. else:
  384. let message =
  385. if context.detail == "":
  386. instantiationFrom
  387. else:
  388. instantiationOfFrom.format(context.detail)
  389. styledMsgWriteln(styleBright, conf.toFileLineCol(context.info), " ", resetStyle, message)
  390. info = context.info
  391. proc ignoreMsgBecauseOfIdeTools(conf: ConfigRef; msg: TMsgKind): bool =
  392. msg >= errGenerated and conf.cmd == cmdIdeTools and optIdeDebug notin conf.globalOptions
  393. proc addSourceLine(conf: ConfigRef; fileIdx: FileIndex, line: string) =
  394. conf.m.fileInfos[fileIdx.int32].lines.add line
  395. proc numLines*(conf: ConfigRef, fileIdx: FileIndex): int =
  396. ## xxx there's an off by 1 error that should be fixed; if a file ends with "foo" or "foo\n"
  397. ## it will return same number of lines (ie, a trailing empty line is discounted)
  398. result = conf.m.fileInfos[fileIdx.int32].lines.len
  399. if result == 0:
  400. try:
  401. for line in lines(toFullPathConsiderDirty(conf, fileIdx).string):
  402. addSourceLine conf, fileIdx, line
  403. except IOError:
  404. discard
  405. result = conf.m.fileInfos[fileIdx.int32].lines.len
  406. proc sourceLine*(conf: ConfigRef; i: TLineInfo): string =
  407. ## 1-based index (matches editor line numbers); 1st line is for i.line = 1
  408. ## last valid line is `numLines` inclusive
  409. if i.fileIndex.int32 < 0: return ""
  410. let num = numLines(conf, i.fileIndex)
  411. # can happen if the error points to EOF:
  412. if i.line.int > num: return ""
  413. result = conf.m.fileInfos[i.fileIndex.int32].lines[i.line.int-1]
  414. proc getSurroundingSrc(conf: ConfigRef; info: TLineInfo): string =
  415. if conf.hasHint(hintSource) and info != unknownLineInfo:
  416. const indent = " "
  417. result = "\n" & indent & $sourceLine(conf, info)
  418. if info.col >= 0:
  419. result.add "\n" & indent & spaces(info.col) & '^'
  420. proc formatMsg*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string): string =
  421. let title = case msg
  422. of warnMin..warnMax: WarningTitle
  423. of hintMin..hintMax: HintTitle
  424. else: ErrorTitle
  425. conf.toFileLineCol(info) & " " & title & getMessageStr(msg, arg)
  426. proc liMessage*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string,
  427. eh: TErrorHandling, info2: InstantiationInfo, isRaw = false) {.noinline.} =
  428. var
  429. title: string
  430. color: ForegroundColor
  431. ignoreMsg = false
  432. sev: Severity
  433. let errorOutputsOld = conf.m.errorOutputs
  434. if msg in fatalMsgs:
  435. # don't gag, refs bug #7080, bug #18278; this can happen with `{.fatal.}`
  436. # or inside a `tryConstExpr`.
  437. conf.m.errorOutputs = {eStdOut, eStdErr}
  438. let kind = if msg in warnMin..hintMax and msg != hintUserRaw: $msg else: "" # xxx not sure why hintUserRaw is special
  439. case msg
  440. of errMin..errMax:
  441. sev = Severity.Error
  442. writeContext(conf, info)
  443. title = ErrorTitle
  444. color = ErrorColor
  445. when false:
  446. # we try to filter error messages so that not two error message
  447. # in the same file and line are produced:
  448. # xxx `lastError` is only used in this disabled code; but could be useful to revive
  449. ignoreMsg = conf.m.lastError == info and info != unknownLineInfo and eh != doAbort
  450. if info != unknownLineInfo: conf.m.lastError = info
  451. of warnMin..warnMax:
  452. sev = Severity.Warning
  453. ignoreMsg = not conf.hasWarn(msg)
  454. if not ignoreMsg and msg in conf.warningAsErrors:
  455. title = ErrorTitle
  456. else:
  457. title = WarningTitle
  458. if not ignoreMsg: writeContext(conf, info)
  459. color = WarningColor
  460. inc(conf.warnCounter)
  461. of hintMin..hintMax:
  462. sev = Severity.Hint
  463. ignoreMsg = not conf.hasHint(msg)
  464. if not ignoreMsg and msg in conf.warningAsErrors:
  465. title = ErrorTitle
  466. else:
  467. title = HintTitle
  468. color = HintColor
  469. inc(conf.hintCounter)
  470. let s = if isRaw: arg else: getMessageStr(msg, arg)
  471. if not ignoreMsg:
  472. let loc = if info != unknownLineInfo: conf.toFileLineCol(info) & " " else: ""
  473. # we could also show `conf.cmdInput` here for `projectIsCmd`
  474. var kindmsg = if kind.len > 0: KindFormat % kind else: ""
  475. if conf.structuredErrorHook != nil:
  476. conf.structuredErrorHook(conf, info, s & kindmsg, sev)
  477. if not ignoreMsgBecauseOfIdeTools(conf, msg):
  478. if msg == hintProcessing and conf.hintProcessingDots:
  479. msgWrite(conf, ".")
  480. else:
  481. styledMsgWriteln(styleBright, loc, resetStyle, color, title, resetStyle, s, KindColor, kindmsg,
  482. resetStyle, conf.getSurroundingSrc(info), conf.unitSep)
  483. if hintMsgOrigin in conf.mainPackageNotes:
  484. # xxx needs a bit of refactoring to honor `conf.filenameOption`
  485. styledMsgWriteln(styleBright, toFileLineCol(info2), resetStyle,
  486. " compiler msg initiated here", KindColor,
  487. KindFormat % $hintMsgOrigin,
  488. resetStyle, conf.unitSep)
  489. handleError(conf, msg, eh, s, ignoreMsg)
  490. if msg in fatalMsgs:
  491. # most likely would have died here but just in case, we restore state
  492. conf.m.errorOutputs = errorOutputsOld
  493. template rawMessage*(conf: ConfigRef; msg: TMsgKind, args: openArray[string]) =
  494. let arg = msgKindToString(msg) % args
  495. liMessage(conf, unknownLineInfo, msg, arg, eh = doAbort, instLoc(), isRaw = true)
  496. template rawMessage*(conf: ConfigRef; msg: TMsgKind, arg: string) =
  497. liMessage(conf, unknownLineInfo, msg, arg, eh = doAbort, instLoc())
  498. template fatal*(conf: ConfigRef; info: TLineInfo, arg = "", msg = errFatal) =
  499. liMessage(conf, info, msg, arg, doAbort, instLoc())
  500. template globalAssert*(conf: ConfigRef; cond: untyped, info: TLineInfo = unknownLineInfo, arg = "") =
  501. ## avoids boilerplate
  502. if not cond:
  503. var arg2 = "'$1' failed" % [astToStr(cond)]
  504. if arg.len > 0: arg2.add "; " & astToStr(arg) & ": " & arg
  505. liMessage(conf, info, errGenerated, arg2, doRaise, instLoc())
  506. template globalError*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
  507. ## `local` means compilation keeps going until errorMax is reached (via `doNothing`),
  508. ## `global` means it stops.
  509. liMessage(conf, info, msg, arg, doRaise, instLoc())
  510. template globalError*(conf: ConfigRef; info: TLineInfo, arg: string) =
  511. liMessage(conf, info, errGenerated, arg, doRaise, instLoc())
  512. template localError*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
  513. liMessage(conf, info, msg, arg, doNothing, instLoc())
  514. template localError*(conf: ConfigRef; info: TLineInfo, arg: string) =
  515. liMessage(conf, info, errGenerated, arg, doNothing, instLoc())
  516. template message*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
  517. liMessage(conf, info, msg, arg, doNothing, instLoc())
  518. proc warningDeprecated*(conf: ConfigRef, info: TLineInfo = gCmdLineInfo, msg = "") {.inline.} =
  519. message(conf, info, warnDeprecated, msg)
  520. proc internalErrorImpl(conf: ConfigRef; info: TLineInfo, errMsg: string, info2: InstantiationInfo) =
  521. if conf.cmd == cmdIdeTools and conf.structuredErrorHook.isNil: return
  522. writeContext(conf, info)
  523. liMessage(conf, info, errInternal, errMsg, doAbort, info2)
  524. template internalError*(conf: ConfigRef; info: TLineInfo, errMsg: string) =
  525. internalErrorImpl(conf, info, errMsg, instLoc())
  526. template internalError*(conf: ConfigRef; errMsg: string) =
  527. internalErrorImpl(conf, unknownLineInfo, errMsg, instLoc())
  528. template internalAssert*(conf: ConfigRef, e: bool) =
  529. # xxx merge with `globalAssert`
  530. if not e:
  531. const info2 = instLoc()
  532. let arg = info2.toFileLineCol
  533. internalErrorImpl(conf, unknownLineInfo, arg, info2)
  534. template lintReport*(conf: ConfigRef; info: TLineInfo, beau, got: string, extraMsg = "") =
  535. let m = "'$1' should be: '$2'$3" % [got, beau, extraMsg]
  536. let msg = if optStyleError in conf.globalOptions: errGenerated else: hintName
  537. liMessage(conf, info, msg, m, doNothing, instLoc())
  538. proc quotedFilename*(conf: ConfigRef; i: TLineInfo): Rope =
  539. if i.fileIndex.int32 < 0:
  540. result = makeCString "???"
  541. elif optExcessiveStackTrace in conf.globalOptions:
  542. result = conf.m.fileInfos[i.fileIndex.int32].quotedFullName
  543. else:
  544. result = conf.m.fileInfos[i.fileIndex.int32].quotedName
  545. template listMsg(title, r) =
  546. msgWriteln(conf, title, {msgNoUnitSep})
  547. for a in r: msgWriteln(conf, " [$1] $2" % [if a in conf.notes: "x" else: " ", $a], {msgNoUnitSep})
  548. proc listWarnings*(conf: ConfigRef) = listMsg("Warnings:", warnMin..warnMax)
  549. proc listHints*(conf: ConfigRef) = listMsg("Hints:", hintMin..hintMax)
  550. proc uniqueModuleName*(conf: ConfigRef; fid: FileIndex): string =
  551. ## The unique module name is guaranteed to only contain {'A'..'Z', 'a'..'z', '0'..'9', '_'}
  552. ## so that it is useful as a C identifier snippet.
  553. let path = AbsoluteFile toFullPath(conf, fid)
  554. let rel =
  555. if path.string.startsWith(conf.libpath.string):
  556. relativeTo(path, conf.libpath).string
  557. else:
  558. relativeTo(path, conf.projectPath).string
  559. let trunc = if rel.endsWith(".nim"): rel.len - len(".nim") else: rel.len
  560. result = newStringOfCap(trunc)
  561. for i in 0..<trunc:
  562. let c = rel[i]
  563. case c
  564. of 'a'..'z':
  565. result.add c
  566. of {os.DirSep, os.AltSep}:
  567. result.add 'Z' # because it looks a bit like '/'
  568. of '.':
  569. result.add 'O' # a circle
  570. else:
  571. # We mangle upper letters and digits too so that there cannot
  572. # be clashes with our special meanings of 'Z' and 'O'
  573. result.addInt ord(c)
  574. proc genSuccessX*(conf: ConfigRef) =
  575. let mem =
  576. when declared(system.getMaxMem): formatSize(getMaxMem()) & " peakmem"
  577. else: formatSize(getTotalMem()) & " totmem"
  578. let loc = $conf.linesCompiled
  579. var build = ""
  580. var flags = ""
  581. const debugModeHints = "none (DEBUG BUILD, `-d:release` generates faster code)"
  582. if conf.cmd in cmdBackends:
  583. if conf.backend != backendJs:
  584. build.add "gc: $#; " % $conf.selectedGC
  585. if optThreads in conf.globalOptions: build.add "threads: on; "
  586. build.add "opt: "
  587. if optOptimizeSpeed in conf.options: build.add "speed"
  588. elif optOptimizeSize in conf.options: build.add "size"
  589. else: build.add debugModeHints
  590. # pending https://github.com/timotheecour/Nim/issues/752, point to optimization.html
  591. if isDefined(conf, "danger"): flags.add " -d:danger"
  592. elif isDefined(conf, "release"): flags.add " -d:release"
  593. else:
  594. build.add "opt: "
  595. if isDefined(conf, "danger"):
  596. build.add "speed"
  597. flags.add " -d:danger"
  598. elif isDefined(conf, "release"):
  599. build.add "speed"
  600. flags.add " -d:release"
  601. else: build.add debugModeHints
  602. if flags.len > 0: build.add "; options:" & flags
  603. let sec = formatFloat(epochTime() - conf.lastCmdTime, ffDecimal, 3)
  604. let project = if conf.filenameOption == foAbs: $conf.projectFull else: $conf.projectName
  605. # xxx honor conf.filenameOption more accurately
  606. var output: string
  607. if optCompileOnly in conf.globalOptions and conf.cmd != cmdJsonscript:
  608. output = $conf.jsonBuildFile
  609. elif conf.outFile.isEmpty and conf.cmd notin {cmdJsonscript} + cmdDocLike + cmdBackends:
  610. # for some cmd we expect a valid absOutFile
  611. output = "unknownOutput"
  612. else:
  613. output = $conf.absOutFile
  614. if conf.filenameOption != foAbs: output = output.AbsoluteFile.extractFilename
  615. # xxx honor filenameOption more accurately
  616. rawMessage(conf, hintSuccessX, [
  617. "build", build,
  618. "loc", loc,
  619. "sec", sec,
  620. "mem", mem,
  621. "project", project,
  622. "output", output,
  623. ])