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