lineinfos.nim 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2018 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains the ``TMsgKind`` enum as well as the
  10. ## ``TLineInfo`` object.
  11. import ropes, tables, pathutils
  12. const
  13. explanationsBaseUrl* = "https://nim-lang.github.io/Nim"
  14. # was: "https://nim-lang.org/docs" but we're now usually showing devel docs
  15. # instead of latest release docs.
  16. proc createDocLink*(urlSuffix: string): string =
  17. # os.`/` is not appropriate for urls.
  18. result = explanationsBaseUrl
  19. if urlSuffix.len > 0 and urlSuffix[0] == '/':
  20. result.add urlSuffix
  21. else:
  22. result.add "/" & urlSuffix
  23. type
  24. TMsgKind* = enum
  25. errUnknown, errInternal, errIllFormedAstX, errCannotOpenFile,
  26. errXExpected,
  27. errGridTableNotImplemented,
  28. errGeneralParseError,
  29. errNewSectionExpected,
  30. errInvalidDirectiveX,
  31. errProveInit, # deadcode
  32. errGenerated,
  33. errUser,
  34. warnCannotOpenFile,
  35. warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit,
  36. warnDeprecated, warnConfigDeprecated,
  37. warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel,
  38. warnUnknownSubstitutionX, warnLanguageXNotSupported,
  39. warnFieldXNotSupported, warnCommentXIgnored,
  40. warnTypelessParam,
  41. warnUseBase, warnWriteToForeignHeap, warnUnsafeCode,
  42. warnUnusedImportX,
  43. warnInheritFromException,
  44. warnEachIdentIsTuple,
  45. warnUnsafeSetLen,
  46. warnUnsafeDefault,
  47. warnProveInit, warnProveField, warnProveIndex,
  48. warnUnreachableElse, warnUnreachableCode,
  49. warnStaticIndexCheck, warnGcUnsafe, warnGcUnsafe2,
  50. warnUninit, warnGcMem, warnDestructor, warnLockLevel, warnResultShadowed,
  51. warnInconsistentSpacing, warnCaseTransition, warnCycleCreated,
  52. warnObservableStores,
  53. warnUser,
  54. hintSuccess, hintSuccessX, hintCC,
  55. hintLineTooLong, hintXDeclaredButNotUsed,
  56. hintConvToBaseNotNeeded,
  57. hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled,
  58. hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath,
  59. hintConditionAlwaysTrue, hintConditionAlwaysFalse, hintName, hintPattern,
  60. hintExecuting, hintLinking, hintDependency,
  61. hintSource, hintPerformance, hintStackTrace, hintGCStats,
  62. hintGlobalVar, hintExpandMacro,
  63. hintUser, hintUserRaw,
  64. hintExtendedContext,
  65. hintMsgOrigin, # since 1.3.5
  66. const
  67. MsgKindToStr*: array[TMsgKind, string] = [
  68. errUnknown: "unknown error",
  69. errInternal: "internal error: $1",
  70. errIllFormedAstX: "illformed AST: $1",
  71. errCannotOpenFile: "cannot open '$1'",
  72. errXExpected: "'$1' expected",
  73. errGridTableNotImplemented: "grid table is not implemented",
  74. errGeneralParseError: "general parse error",
  75. errNewSectionExpected: "new section expected",
  76. errInvalidDirectiveX: "invalid directive: '$1'",
  77. errProveInit: "Cannot prove that '$1' is initialized.", # deadcode
  78. errGenerated: "$1",
  79. errUser: "$1",
  80. warnCannotOpenFile: "cannot open '$1'",
  81. warnOctalEscape: "octal escape sequences do not exist; leading zero is ignored",
  82. warnXIsNeverRead: "'$1' is never read",
  83. warnXmightNotBeenInit: "'$1' might not have been initialized",
  84. warnDeprecated: "$1",
  85. warnConfigDeprecated: "config file '$1' is deprecated",
  86. warnSmallLshouldNotBeUsed: "'l' should not be used as an identifier; may look like '1' (one)",
  87. warnUnknownMagic: "unknown magic '$1' might crash the compiler",
  88. warnRedefinitionOfLabel: "redefinition of label '$1'",
  89. warnUnknownSubstitutionX: "unknown substitution '$1'",
  90. warnLanguageXNotSupported: "language '$1' not supported",
  91. warnFieldXNotSupported: "field '$1' not supported",
  92. warnCommentXIgnored: "comment '$1' ignored",
  93. warnTypelessParam: "'$1' has no type. Typeless parameters are deprecated; only allowed for 'template'",
  94. warnUseBase: "use {.base.} for base methods; baseless methods are deprecated",
  95. warnWriteToForeignHeap: "write to foreign heap",
  96. warnUnsafeCode: "unsafe code: '$1'",
  97. warnUnusedImportX: "imported and not used: '$1'",
  98. warnInheritFromException: "inherit from a more precise exception type like ValueError, " &
  99. "IOError or OSError. If these don't suit, inherit from CatchableError or Defect.",
  100. warnEachIdentIsTuple: "each identifier is a tuple",
  101. warnUnsafeSetLen: "setLen can potentially expand the sequence, " &
  102. "but the element type '$1' doesn't have a valid default value",
  103. warnUnsafeDefault: "The '$1' type doesn't have a valid default value",
  104. warnProveInit: "Cannot prove that '$1' is initialized. This will become a compile time error in the future.",
  105. warnProveField: "cannot prove that field '$1' is accessible",
  106. warnProveIndex: "cannot prove index '$1' is valid",
  107. warnUnreachableElse: "unreachable else, all cases are already covered",
  108. warnUnreachableCode: "unreachable code after 'return' statement or '{.noReturn.}' proc",
  109. warnStaticIndexCheck: "$1",
  110. warnGcUnsafe: "not GC-safe: '$1'",
  111. warnGcUnsafe2: "$1",
  112. warnUninit: "use explicit initialization of '$1' for clarity",
  113. warnGcMem: "'$1' uses GC'ed memory",
  114. warnDestructor: "usage of a type with a destructor in a non destructible context. This will become a compile time error in the future.",
  115. warnLockLevel: "$1",
  116. warnResultShadowed: "Special variable 'result' is shadowed.",
  117. warnInconsistentSpacing: "Number of spaces around '$#' is not consistent",
  118. warnCaseTransition: "Potential object case transition, instantiate new object instead",
  119. warnCycleCreated: "$1",
  120. warnObservableStores: "observable stores to '$1'",
  121. warnUser: "$1",
  122. hintSuccess: "operation successful: $#",
  123. # keep in sync with `testament.isSuccess`
  124. hintSuccessX: "${loc} lines; ${sec}s; $mem; $build build; proj: $project; out: $output",
  125. hintCC: "CC: $1",
  126. hintLineTooLong: "line too long",
  127. hintXDeclaredButNotUsed: "'$1' is declared but not used",
  128. hintConvToBaseNotNeeded: "conversion to base object is not needed",
  129. hintConvFromXtoItselfNotNeeded: "conversion from $1 to itself is pointless",
  130. hintExprAlwaysX: "expression evaluates always to '$1'",
  131. hintQuitCalled: "quit() called",
  132. hintProcessing: "$1",
  133. hintCodeBegin: "generated code listing:",
  134. hintCodeEnd: "end of listing",
  135. hintConf: "used config file '$1'",
  136. hintPath: "added path: '$1'",
  137. hintConditionAlwaysTrue: "condition is always true: '$1'",
  138. hintConditionAlwaysFalse: "condition is always false: '$1'",
  139. hintName: "$1",
  140. hintPattern: "$1",
  141. hintExecuting: "$1",
  142. hintLinking: "$1",
  143. hintDependency: "$1",
  144. hintSource: "$1",
  145. hintPerformance: "$1",
  146. hintStackTrace: "$1",
  147. hintGCStats: "$1",
  148. hintGlobalVar: "global variable declared here",
  149. hintExpandMacro: "expanded macro: $1",
  150. hintUser: "$1",
  151. hintUserRaw: "$1",
  152. hintExtendedContext: "$1",
  153. hintMsgOrigin: "$1",
  154. ]
  155. const
  156. WarningsToStr* = ["CannotOpenFile", "OctalEscape",
  157. "XIsNeverRead", "XmightNotBeenInit",
  158. "Deprecated", "ConfigDeprecated",
  159. "SmallLshouldNotBeUsed", "UnknownMagic",
  160. "RedefinitionOfLabel", "UnknownSubstitutionX",
  161. "LanguageXNotSupported", "FieldXNotSupported",
  162. "CommentXIgnored",
  163. "TypelessParam", "UseBase", "WriteToForeignHeap",
  164. "UnsafeCode", "UnusedImport", "InheritFromException",
  165. "EachIdentIsTuple",
  166. "UnsafeSetLen", "UnsafeDefault",
  167. "ProveInit", "ProveField", "ProveIndex", "UnreachableElse", "UnreachableCode",
  168. "IndexCheck", "GcUnsafe", "GcUnsafe2", "Uninit",
  169. "GcMem", "Destructor", "LockLevel", "ResultShadowed",
  170. "Spacing", "CaseTransition", "CycleCreated",
  171. "ObservableStores", "User"]
  172. HintsToStr* = [
  173. "Success", "SuccessX", "CC", "LineTooLong",
  174. "XDeclaredButNotUsed",
  175. "ConvToBaseNotNeeded", "ConvFromXtoItselfNotNeeded",
  176. "ExprAlwaysX", "QuitCalled", "Processing", "CodeBegin", "CodeEnd", "Conf",
  177. "Path", "CondTrue", "CondFalse", "Name", "Pattern", "Exec", "Link", "Dependency",
  178. "Source", "Performance", "StackTrace", "GCStats", "GlobalVar", "ExpandMacro",
  179. "User", "UserRaw", "ExtendedContext", "MsgOrigin",
  180. ]
  181. const
  182. fatalMin* = errUnknown
  183. fatalMax* = errInternal
  184. errMin* = errUnknown
  185. errMax* = errUser
  186. warnMin* = warnCannotOpenFile
  187. warnMax* = pred(hintSuccess)
  188. hintMin* = hintSuccess
  189. hintMax* = high(TMsgKind)
  190. proc msgToStr*(msg: TMsgKind): string =
  191. case msg
  192. of warnMin..warnMax: WarningsToStr[ord(msg) - ord(warnMin)]
  193. of hintMin..hintMax: HintsToStr[ord(msg) - ord(hintMin)]
  194. else: "" # we could at least do $msg - prefix `err`
  195. static:
  196. doAssert HintsToStr.len == ord(hintMax) - ord(hintMin) + 1
  197. doAssert WarningsToStr.len == ord(warnMax) - ord(warnMin) + 1
  198. type
  199. TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints
  200. TNoteKinds* = set[TNoteKind]
  201. proc computeNotesVerbosity(): array[0..3, TNoteKinds] =
  202. result[3] = {low(TNoteKind)..high(TNoteKind)} - {}
  203. result[2] = result[3] - {hintStackTrace, warnUninit, hintExtendedContext}
  204. result[1] = result[2] - {warnProveField, warnProveIndex,
  205. warnGcUnsafe, hintPath, hintDependency, hintCodeBegin, hintCodeEnd,
  206. hintSource, hintGlobalVar, hintGCStats, hintMsgOrigin}
  207. result[0] = result[1] - {hintSuccessX, hintSuccess, hintConf,
  208. hintProcessing, hintPattern, hintExecuting, hintLinking, hintCC}
  209. const
  210. NotesVerbosity* = computeNotesVerbosity()
  211. errXMustBeCompileTime* = "'$1' can only be used in compile-time context"
  212. errArgsNeedRunOption* = "arguments can only be given if the '--run' option is selected"
  213. type
  214. TFileInfo* = object
  215. fullPath*: AbsoluteFile # This is a canonical full filesystem path
  216. projPath*: RelativeFile # This is relative to the project's root
  217. shortName*: string # short name of the module
  218. quotedName*: Rope # cached quoted short name for codegen
  219. # purposes
  220. quotedFullName*: Rope # cached quoted full name for codegen
  221. # purposes
  222. lines*: seq[string] # the source code of the module
  223. # used for better error messages and
  224. # embedding the original source in the
  225. # generated code
  226. dirtyFile*: AbsoluteFile # the file that is actually read into memory
  227. # and parsed; usually "" but is used
  228. # for 'nimsuggest'
  229. hash*: string # the checksum of the file
  230. dirty*: bool # for 'nimfix' / 'nimpretty' like tooling
  231. when defined(nimpretty):
  232. fullContent*: string
  233. FileIndex* = distinct int32
  234. TLineInfo* = object # This is designed to be as small as possible,
  235. # because it is used
  236. # in syntax nodes. We save space here by using
  237. # two int16 and an int32.
  238. # On 64 bit and on 32 bit systems this is
  239. # only 8 bytes.
  240. line*: uint16
  241. col*: int16
  242. fileIndex*: FileIndex
  243. when defined(nimpretty):
  244. offsetA*, offsetB*: int
  245. commentOffsetA*, commentOffsetB*: int
  246. TErrorOutput* = enum
  247. eStdOut
  248. eStdErr
  249. TErrorOutputs* = set[TErrorOutput]
  250. ERecoverableError* = object of ValueError
  251. ESuggestDone* = object of ValueError
  252. proc `==`*(a, b: FileIndex): bool {.borrow.}
  253. proc raiseRecoverableError*(msg: string) {.noinline.} =
  254. raise newException(ERecoverableError, msg)
  255. const
  256. InvalidFileIdx* = FileIndex(-1)
  257. unknownLineInfo* = TLineInfo(line: 0, col: -1, fileIndex: InvalidFileIdx)
  258. type
  259. Severity* {.pure.} = enum ## VS Code only supports these three
  260. Hint, Warning, Error
  261. const
  262. trackPosInvalidFileIdx* = FileIndex(-2) # special marker so that no suggestions
  263. # are produced within comments and string literals
  264. commandLineIdx* = FileIndex(-3)
  265. type
  266. MsgConfig* = object ## does not need to be stored in the incremental cache
  267. trackPos*: TLineInfo
  268. trackPosAttached*: bool ## whether the tracking position was attached to
  269. ## some close token.
  270. errorOutputs*: TErrorOutputs
  271. msgContext*: seq[tuple[info: TLineInfo, detail: string]]
  272. lastError*: TLineInfo
  273. filenameToIndexTbl*: Table[string, FileIndex]
  274. fileInfos*: seq[TFileInfo]
  275. systemFileIdx*: FileIndex
  276. proc initMsgConfig*(): MsgConfig =
  277. result.msgContext = @[]
  278. result.lastError = unknownLineInfo
  279. result.filenameToIndexTbl = initTable[string, FileIndex]()
  280. result.fileInfos = @[]
  281. result.errorOutputs = {eStdOut, eStdErr}