lineinfos.nim 15 KB

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