lineinfos.nim 15 KB

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