lineinfos.nim 16 KB

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