msgs.nim 27 KB

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