lineinfos.nim 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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, hashes
  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. # fatal errors
  26. errUnknown, errFatal, errInternal,
  27. # non-fatal errors
  28. errIllFormedAstX, errCannotOpenFile,
  29. errXExpected,
  30. errRstMissingClosing,
  31. errRstGridTableNotImplemented,
  32. errRstMarkdownIllformedTable,
  33. errRstIllformedTable,
  34. errRstNewSectionExpected,
  35. errRstGeneralParseError,
  36. errRstInvalidDirectiveX,
  37. errRstInvalidField,
  38. errRstFootnoteMismatch,
  39. errRstSandboxedDirective,
  40. errProveInit, # deadcode
  41. errGenerated,
  42. errUser,
  43. # warnings
  44. warnCannotOpenFile = "CannotOpenFile", warnOctalEscape = "OctalEscape",
  45. warnXIsNeverRead = "XIsNeverRead", warnXmightNotBeenInit = "XmightNotBeenInit",
  46. warnDeprecated = "Deprecated", warnConfigDeprecated = "ConfigDeprecated",
  47. warnDotLikeOps = "DotLikeOps",
  48. warnSmallLshouldNotBeUsed = "SmallLshouldNotBeUsed", warnUnknownMagic = "UnknownMagic",
  49. warnRstRedefinitionOfLabel = "RedefinitionOfLabel",
  50. warnRstUnknownSubstitutionX = "UnknownSubstitutionX",
  51. warnRstAmbiguousLink = "AmbiguousLink",
  52. warnRstBrokenLink = "BrokenLink",
  53. warnRstLanguageXNotSupported = "LanguageXNotSupported",
  54. warnRstFieldXNotSupported = "FieldXNotSupported",
  55. warnRstStyle = "warnRstStyle",
  56. warnCommentXIgnored = "CommentXIgnored",
  57. warnTypelessParam = "TypelessParam",
  58. warnUseBase = "UseBase", warnWriteToForeignHeap = "WriteToForeignHeap",
  59. warnUnsafeCode = "UnsafeCode", warnUnusedImportX = "UnusedImport",
  60. warnInheritFromException = "InheritFromException", warnEachIdentIsTuple = "EachIdentIsTuple",
  61. warnUnsafeSetLen = "UnsafeSetLen", warnUnsafeDefault = "UnsafeDefault",
  62. warnProveInit = "ProveInit", warnProveField = "ProveField", warnProveIndex = "ProveIndex",
  63. warnUnreachableElse = "UnreachableElse", warnUnreachableCode = "UnreachableCode",
  64. warnStaticIndexCheck = "IndexCheck", warnGcUnsafe = "GcUnsafe", warnGcUnsafe2 = "GcUnsafe2",
  65. warnUninit = "Uninit", warnGcMem = "GcMem", warnDestructor = "Destructor",
  66. warnLockLevel = "LockLevel", warnResultShadowed = "ResultShadowed",
  67. warnInconsistentSpacing = "Spacing", warnCaseTransition = "CaseTransition",
  68. warnCycleCreated = "CycleCreated", warnObservableStores = "ObservableStores",
  69. warnStrictNotNil = "StrictNotNil",
  70. warnResultUsed = "ResultUsed",
  71. warnCannotOpen = "CannotOpen",
  72. warnFileChanged = "FileChanged",
  73. warnSuspiciousEnumConv = "EnumConv",
  74. warnAnyEnumConv = "AnyEnumConv",
  75. warnHoleEnumConv = "HoleEnumConv",
  76. warnCstringConv = "CStringConv",
  77. warnEffect = "Effect",
  78. warnCastSizes = "CastSizes"
  79. warnTemplateRedefinition = "TemplateRedefinition",
  80. warnUser = "User",
  81. # hints
  82. hintSuccess = "Success", hintSuccessX = "SuccessX",
  83. hintCC = "CC",
  84. hintLineTooLong = "LineTooLong",
  85. hintXDeclaredButNotUsed = "XDeclaredButNotUsed", hintDuplicateModuleImport = "DuplicateModuleImport",
  86. hintXCannotRaiseY = "XCannotRaiseY", hintConvToBaseNotNeeded = "ConvToBaseNotNeeded",
  87. hintConvFromXtoItselfNotNeeded = "ConvFromXtoItselfNotNeeded", hintExprAlwaysX = "ExprAlwaysX",
  88. hintQuitCalled = "QuitCalled", hintProcessing = "Processing", hintProcessingStmt = "ProcessingStmt", hintCodeBegin = "CodeBegin",
  89. hintCodeEnd = "CodeEnd", hintConf = "Conf", hintPath = "Path",
  90. hintConditionAlwaysTrue = "CondTrue", hintConditionAlwaysFalse = "CondFalse", hintName = "Name",
  91. hintPattern = "Pattern", hintExecuting = "Exec", hintLinking = "Link", hintDependency = "Dependency",
  92. hintSource = "Source", hintPerformance = "Performance", hintStackTrace = "StackTrace",
  93. hintGCStats = "GCStats", hintGlobalVar = "GlobalVar", hintExpandMacro = "ExpandMacro",
  94. hintAmbiguousEnum = "AmbiguousEnum",
  95. hintUser = "User", hintUserRaw = "UserRaw", hintExtendedContext = "ExtendedContext",
  96. hintMsgOrigin = "MsgOrigin", # since 1.3.5
  97. hintDeclaredLoc = "DeclaredLoc", # since 1.5.1
  98. const
  99. MsgKindToStr*: array[TMsgKind, string] = [
  100. errUnknown: "unknown error",
  101. errFatal: "fatal error: $1",
  102. errInternal: "internal error: $1",
  103. errIllFormedAstX: "illformed AST: $1",
  104. errCannotOpenFile: "cannot open '$1'",
  105. errXExpected: "'$1' expected",
  106. errRstMissingClosing: "$1",
  107. errRstGridTableNotImplemented: "grid table is not implemented",
  108. errRstMarkdownIllformedTable: "illformed delimiter row of a markdown table",
  109. errRstIllformedTable: "Illformed table: $1",
  110. errRstNewSectionExpected: "new section expected $1",
  111. errRstGeneralParseError: "general parse error",
  112. errRstInvalidDirectiveX: "invalid directive: '$1'",
  113. errRstInvalidField: "invalid field: $1",
  114. errRstFootnoteMismatch: "number of footnotes and their references don't match: $1",
  115. errRstSandboxedDirective: "disabled directive: '$1'",
  116. errProveInit: "Cannot prove that '$1' is initialized.", # deadcode
  117. errGenerated: "$1",
  118. errUser: "$1",
  119. warnCannotOpenFile: "cannot open '$1'",
  120. warnOctalEscape: "octal escape sequences do not exist; leading zero is ignored",
  121. warnXIsNeverRead: "'$1' is never read",
  122. warnXmightNotBeenInit: "'$1' might not have been initialized",
  123. warnDeprecated: "$1",
  124. warnConfigDeprecated: "config file '$1' is deprecated",
  125. warnDotLikeOps: "$1",
  126. warnSmallLshouldNotBeUsed: "'l' should not be used as an identifier; may look like '1' (one)",
  127. warnUnknownMagic: "unknown magic '$1' might crash the compiler",
  128. warnRstRedefinitionOfLabel: "redefinition of label '$1'",
  129. warnRstUnknownSubstitutionX: "unknown substitution '$1'",
  130. warnRstAmbiguousLink: "ambiguous doc link $1",
  131. warnRstBrokenLink: "broken link '$1'",
  132. warnRstLanguageXNotSupported: "language '$1' not supported",
  133. warnRstFieldXNotSupported: "field '$1' not supported",
  134. warnRstStyle: "RST style: $1",
  135. warnCommentXIgnored: "comment '$1' ignored",
  136. warnTypelessParam: "", # deadcode
  137. warnUseBase: "use {.base.} for base methods; baseless methods are deprecated",
  138. warnWriteToForeignHeap: "write to foreign heap",
  139. warnUnsafeCode: "unsafe code: '$1'",
  140. warnUnusedImportX: "imported and not used: '$1'",
  141. warnInheritFromException: "inherit from a more precise exception type like ValueError, " &
  142. "IOError or OSError. If these don't suit, inherit from CatchableError or Defect.",
  143. warnEachIdentIsTuple: "each identifier is a tuple",
  144. warnUnsafeSetLen: "setLen can potentially expand the sequence, " &
  145. "but the element type '$1' doesn't have a valid default value",
  146. warnUnsafeDefault: "The '$1' type doesn't have a valid default value",
  147. warnProveInit: "Cannot prove that '$1' is initialized. This will become a compile time error in the future.",
  148. warnProveField: "cannot prove that field '$1' is accessible",
  149. warnProveIndex: "cannot prove index '$1' is valid",
  150. warnUnreachableElse: "unreachable else, all cases are already covered",
  151. warnUnreachableCode: "unreachable code after 'return' statement or '{.noReturn.}' proc",
  152. warnStaticIndexCheck: "$1",
  153. warnGcUnsafe: "not GC-safe: '$1'",
  154. warnGcUnsafe2: "$1",
  155. warnUninit: "use explicit initialization of '$1' for clarity",
  156. warnGcMem: "'$1' uses GC'ed memory",
  157. warnDestructor: "usage of a type with a destructor in a non destructible context. This will become a compile time error in the future.",
  158. warnLockLevel: "$1",
  159. warnResultShadowed: "Special variable 'result' is shadowed.",
  160. warnInconsistentSpacing: "Number of spaces around '$#' is not consistent",
  161. warnCaseTransition: "Potential object case transition, instantiate new object instead",
  162. warnCycleCreated: "$1",
  163. warnObservableStores: "observable stores to '$1'",
  164. warnStrictNotNil: "$1",
  165. warnResultUsed: "used 'result' variable",
  166. warnCannotOpen: "cannot open: $1",
  167. warnFileChanged: "file changed: $1",
  168. warnSuspiciousEnumConv: "$1",
  169. warnAnyEnumConv: "$1",
  170. warnHoleEnumConv: "$1",
  171. warnCstringConv: "$1",
  172. warnEffect: "$1",
  173. warnCastSizes: "$1",
  174. warnTemplateRedefinition: "template '$1' is implicitly redefined, consider adding an explicit .redefine pragma",
  175. warnUser: "$1",
  176. hintSuccess: "operation successful: $#",
  177. # keep in sync with `testament.isSuccess`
  178. hintSuccessX: "$build\n$loc lines; ${sec}s; $mem; proj: $project; out: $output",
  179. hintCC: "CC: $1",
  180. hintLineTooLong: "line too long",
  181. hintXDeclaredButNotUsed: "'$1' is declared but not used",
  182. hintDuplicateModuleImport: "$1",
  183. hintXCannotRaiseY: "$1",
  184. hintConvToBaseNotNeeded: "conversion to base object is not needed",
  185. hintConvFromXtoItselfNotNeeded: "conversion from $1 to itself is pointless",
  186. hintExprAlwaysX: "expression evaluates always to '$1'",
  187. hintQuitCalled: "quit() called",
  188. hintProcessing: "$1",
  189. hintProcessingStmt: "$1",
  190. hintCodeBegin: "generated code listing:",
  191. hintCodeEnd: "end of listing",
  192. hintConf: "used config file '$1'",
  193. hintPath: "added path: '$1'",
  194. hintConditionAlwaysTrue: "condition is always true: '$1'",
  195. hintConditionAlwaysFalse: "condition is always false: '$1'",
  196. hintName: "$1",
  197. hintPattern: "$1",
  198. hintExecuting: "$1",
  199. hintLinking: "$1",
  200. hintDependency: "$1",
  201. hintSource: "$1",
  202. hintPerformance: "$1",
  203. hintStackTrace: "$1",
  204. hintGCStats: "$1",
  205. hintGlobalVar: "global variable declared here",
  206. hintExpandMacro: "expanded macro: $1",
  207. hintAmbiguousEnum: "$1",
  208. hintUser: "$1",
  209. hintUserRaw: "$1",
  210. hintExtendedContext: "$1",
  211. hintMsgOrigin: "$1",
  212. hintDeclaredLoc: "$1",
  213. ]
  214. const
  215. fatalMsgs* = {errUnknown..errInternal}
  216. errMin* = errUnknown
  217. errMax* = errUser
  218. warnMin* = warnCannotOpenFile
  219. warnMax* = pred(hintSuccess)
  220. hintMin* = hintSuccess
  221. hintMax* = high(TMsgKind)
  222. rstWarnings* = {warnRstRedefinitionOfLabel..warnRstStyle}
  223. type
  224. TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints
  225. TNoteKinds* = set[TNoteKind]
  226. proc computeNotesVerbosity(): array[0..3, TNoteKinds] =
  227. result[3] = {low(TNoteKind)..high(TNoteKind)} - {warnObservableStores, warnResultUsed, warnAnyEnumConv}
  228. result[2] = result[3] - {hintStackTrace, hintExtendedContext, hintDeclaredLoc, hintProcessingStmt}
  229. result[1] = result[2] - {warnProveField, warnProveIndex,
  230. warnGcUnsafe, hintPath, hintDependency, hintCodeBegin, hintCodeEnd,
  231. hintSource, hintGlobalVar, hintGCStats, hintMsgOrigin, hintPerformance}
  232. result[0] = result[1] - {hintSuccessX, hintSuccess, hintConf,
  233. hintProcessing, hintPattern, hintExecuting, hintLinking, hintCC}
  234. const
  235. NotesVerbosity* = computeNotesVerbosity()
  236. errXMustBeCompileTime* = "'$1' can only be used in compile-time context"
  237. errArgsNeedRunOption* = "arguments can only be given if the '--run' option is selected"
  238. type
  239. TFileInfo* = object
  240. fullPath*: AbsoluteFile # This is a canonical full filesystem path
  241. projPath*: RelativeFile # This is relative to the project's root
  242. shortName*: string # short name of the module
  243. quotedName*: Rope # cached quoted short name for codegen
  244. # purposes
  245. quotedFullName*: Rope # cached quoted full name for codegen
  246. # purposes
  247. lines*: seq[string] # the source code of the module
  248. # used for better error messages and
  249. # embedding the original source in the
  250. # generated code
  251. dirtyFile*: AbsoluteFile # the file that is actually read into memory
  252. # and parsed; usually "" but is used
  253. # for 'nimsuggest'
  254. hash*: string # the checksum of the file
  255. dirty*: bool # for 'nimfix' / 'nimpretty' like tooling
  256. when defined(nimpretty):
  257. fullContent*: string
  258. FileIndex* = distinct int32
  259. TLineInfo* = object # This is designed to be as small as possible,
  260. # because it is used
  261. # in syntax nodes. We save space here by using
  262. # two int16 and an int32.
  263. # On 64 bit and on 32 bit systems this is
  264. # only 8 bytes.
  265. line*: uint16
  266. col*: int16
  267. fileIndex*: FileIndex
  268. when defined(nimpretty):
  269. offsetA*, offsetB*: int
  270. commentOffsetA*, commentOffsetB*: int
  271. TErrorOutput* = enum
  272. eStdOut
  273. eStdErr
  274. TErrorOutputs* = set[TErrorOutput]
  275. ERecoverableError* = object of ValueError
  276. ESuggestDone* = object of ValueError
  277. proc `==`*(a, b: FileIndex): bool {.borrow.}
  278. proc hash*(i: TLineInfo): Hash =
  279. hash (i.line.int, i.col.int, i.fileIndex.int)
  280. proc raiseRecoverableError*(msg: string) {.noinline.} =
  281. raise newException(ERecoverableError, msg)
  282. const
  283. InvalidFileIdx* = FileIndex(-1)
  284. unknownLineInfo* = TLineInfo(line: 0, col: -1, fileIndex: InvalidFileIdx)
  285. type
  286. Severity* {.pure.} = enum ## VS Code only supports these three
  287. Hint, Warning, Error
  288. const
  289. trackPosInvalidFileIdx* = FileIndex(-2) # special marker so that no suggestions
  290. # are produced within comments and string literals
  291. commandLineIdx* = FileIndex(-3)
  292. type
  293. MsgConfig* = object ## does not need to be stored in the incremental cache
  294. trackPos*: TLineInfo
  295. trackPosAttached*: bool ## whether the tracking position was attached to
  296. ## some close token.
  297. errorOutputs*: TErrorOutputs
  298. msgContext*: seq[tuple[info: TLineInfo, detail: string]]
  299. lastError*: TLineInfo
  300. filenameToIndexTbl*: Table[string, FileIndex]
  301. fileInfos*: seq[TFileInfo]
  302. systemFileIdx*: FileIndex
  303. proc initMsgConfig*(): MsgConfig =
  304. result.msgContext = @[]
  305. result.lastError = unknownLineInfo
  306. result.filenameToIndexTbl = initTable[string, FileIndex]()
  307. result.fileInfos = @[]
  308. result.errorOutputs = {eStdOut, eStdErr}
  309. result.filenameToIndexTbl["???"] = FileIndex(-1)