lineinfos.nim 15 KB

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