msgs.nim 27 KB

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