lineinfos.nim 15 KB

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