msgs.nim 27 KB

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