lineinfos.nim 14 KB

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