lineinfos.nim 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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
  12. const
  13. explanationsBaseUrl* = "https://nim-lang.org/docs/manual"
  14. type
  15. TMsgKind* = enum
  16. errUnknown, errInternal, errIllFormedAstX, errCannotOpenFile,
  17. errXExpected,
  18. errGridTableNotImplemented,
  19. errGeneralParseError,
  20. errNewSectionExpected,
  21. errInvalidDirectiveX,
  22. errGenerated,
  23. errUser,
  24. warnCannotOpenFile,
  25. warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit,
  26. warnDeprecated, warnConfigDeprecated,
  27. warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel,
  28. warnUnknownSubstitutionX, warnLanguageXNotSupported,
  29. warnFieldXNotSupported, warnCommentXIgnored,
  30. warnTypelessParam,
  31. warnUseBase, warnWriteToForeignHeap, warnUnsafeCode,
  32. warnEachIdentIsTuple, warnShadowIdent,
  33. warnProveInit, warnProveField, warnProveIndex, warnGcUnsafe, warnGcUnsafe2,
  34. warnUninit, warnGcMem, warnDestructor, warnLockLevel, warnResultShadowed,
  35. warnInconsistentSpacing, warnUser,
  36. hintSuccess, hintSuccessX, hintCC,
  37. hintLineTooLong, hintXDeclaredButNotUsed, hintConvToBaseNotNeeded,
  38. hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled,
  39. hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath,
  40. hintConditionAlwaysTrue, hintName, hintPattern,
  41. hintExecuting, hintLinking, hintDependency,
  42. hintSource, hintPerformance, hintStackTrace, hintGCStats,
  43. hintGlobalVar,
  44. hintUser, hintUserRaw,
  45. hintExtendedContext
  46. const
  47. MsgKindToStr*: array[TMsgKind, string] = [
  48. errUnknown: "unknown error",
  49. errInternal: "internal error: $1",
  50. errIllFormedAstX: "illformed AST: $1",
  51. errCannotOpenFile: "cannot open '$1'",
  52. errXExpected: "'$1' expected",
  53. errGridTableNotImplemented: "grid table is not implemented",
  54. errGeneralParseError: "general parse error",
  55. errNewSectionExpected: "new section expected",
  56. errInvalidDirectiveX: "invalid directive: '$1'",
  57. errGenerated: "$1",
  58. errUser: "$1",
  59. warnCannotOpenFile: "cannot open '$1'",
  60. warnOctalEscape: "octal escape sequences do not exist; leading zero is ignored",
  61. warnXIsNeverRead: "'$1' is never read",
  62. warnXmightNotBeenInit: "'$1' might not have been initialized",
  63. warnDeprecated: "$1 is deprecated",
  64. warnConfigDeprecated: "config file '$1' is deprecated",
  65. warnSmallLshouldNotBeUsed: "'l' should not be used as an identifier; may look like '1' (one)",
  66. warnUnknownMagic: "unknown magic '$1' might crash the compiler",
  67. warnRedefinitionOfLabel: "redefinition of label '$1'",
  68. warnUnknownSubstitutionX: "unknown substitution '$1'",
  69. warnLanguageXNotSupported: "language '$1' not supported",
  70. warnFieldXNotSupported: "field '$1' not supported",
  71. warnCommentXIgnored: "comment '$1' ignored",
  72. warnTypelessParam: "'$1' has no type. Typeless parameters are deprecated; only allowed for 'template'",
  73. warnUseBase: "use {.base.} for base methods; baseless methods are deprecated",
  74. warnWriteToForeignHeap: "write to foreign heap",
  75. warnUnsafeCode: "unsafe code: '$1'",
  76. warnEachIdentIsTuple: "each identifier is a tuple",
  77. warnShadowIdent: "shadowed identifier: '$1'",
  78. warnProveInit: "Cannot prove that '$1' is initialized. This will become a compile time error in the future.",
  79. warnProveField: "cannot prove that field '$1' is accessible",
  80. warnProveIndex: "cannot prove index '$1' is valid",
  81. warnGcUnsafe: "not GC-safe: '$1'",
  82. warnGcUnsafe2: "$1",
  83. warnUninit: "'$1' might not have been initialized",
  84. warnGcMem: "'$1' uses GC'ed memory",
  85. warnDestructor: "usage of a type with a destructor in a non destructible context. This will become a compile time error in the future.",
  86. warnLockLevel: "$1",
  87. warnResultShadowed: "Special variable 'result' is shadowed.",
  88. warnInconsistentSpacing: "Number of spaces around '$#' is not consistent",
  89. warnUser: "$1",
  90. hintSuccess: "operation successful: $#",
  91. hintSuccessX: "operation successful ($# lines compiled; $# sec total; $#; $#)",
  92. hintCC: "CC: \'$1\'", # unused
  93. hintLineTooLong: "line too long",
  94. hintXDeclaredButNotUsed: "'$1' is declared but not used",
  95. hintConvToBaseNotNeeded: "conversion to base object is not needed",
  96. hintConvFromXtoItselfNotNeeded: "conversion from $1 to itself is pointless",
  97. hintExprAlwaysX: "expression evaluates always to '$1'",
  98. hintQuitCalled: "quit() called",
  99. hintProcessing: "$1",
  100. hintCodeBegin: "generated code listing:",
  101. hintCodeEnd: "end of listing",
  102. hintConf: "used config file '$1'",
  103. hintPath: "added path: '$1'",
  104. hintConditionAlwaysTrue: "condition is always true: '$1'",
  105. hintName: "name should be: '$1'",
  106. hintPattern: "$1",
  107. hintExecuting: "$1",
  108. hintLinking: "",
  109. hintDependency: "$1",
  110. hintSource: "$1",
  111. hintPerformance: "$1",
  112. hintStackTrace: "$1",
  113. hintGCStats: "$1",
  114. hintGlobalVar: "global variable declared here",
  115. hintUser: "$1",
  116. hintUserRaw: "$1",
  117. hintExtendedContext: "$1",
  118. ]
  119. const
  120. WarningsToStr* = ["CannotOpenFile", "OctalEscape",
  121. "XIsNeverRead", "XmightNotBeenInit",
  122. "Deprecated", "ConfigDeprecated",
  123. "SmallLshouldNotBeUsed", "UnknownMagic",
  124. "RedefinitionOfLabel", "UnknownSubstitutionX",
  125. "LanguageXNotSupported", "FieldXNotSupported",
  126. "CommentXIgnored",
  127. "TypelessParam", "UseBase", "WriteToForeignHeap",
  128. "UnsafeCode", "EachIdentIsTuple", "ShadowIdent",
  129. "ProveInit", "ProveField", "ProveIndex", "GcUnsafe", "GcUnsafe2", "Uninit",
  130. "GcMem", "Destructor", "LockLevel", "ResultShadowed",
  131. "Spacing", "User"]
  132. HintsToStr* = [
  133. "Success", "SuccessX", "CC", "LineTooLong",
  134. "XDeclaredButNotUsed", "ConvToBaseNotNeeded", "ConvFromXtoItselfNotNeeded",
  135. "ExprAlwaysX", "QuitCalled", "Processing", "CodeBegin", "CodeEnd", "Conf",
  136. "Path", "CondTrue", "Name", "Pattern", "Exec", "Link", "Dependency",
  137. "Source", "Performance", "StackTrace", "GCStats", "GlobalVar",
  138. "User", "UserRaw", "ExtendedContext",
  139. ]
  140. const
  141. fatalMin* = errUnknown
  142. fatalMax* = errInternal
  143. errMin* = errUnknown
  144. errMax* = errUser
  145. warnMin* = warnCannotOpenFile
  146. warnMax* = pred(hintSuccess)
  147. hintMin* = hintSuccess
  148. hintMax* = high(TMsgKind)
  149. static:
  150. doAssert HintsToStr.len == ord(hintMax) - ord(hintMin) + 1
  151. doAssert WarningsToStr.len == ord(warnMax) - ord(warnMin) + 1
  152. type
  153. TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints
  154. TNoteKinds* = set[TNoteKind]
  155. proc computeNotesVerbosity(): array[0..3, TNoteKinds] =
  156. result[3] = {low(TNoteKind)..high(TNoteKind)} - {}
  157. result[2] = result[3] - {hintStackTrace, warnUninit, hintExtendedContext}
  158. result[1] = result[2] - {warnShadowIdent, warnProveField, warnProveIndex,
  159. warnGcUnsafe, hintPath, hintDependency, hintCodeBegin, hintCodeEnd,
  160. hintSource, hintGlobalVar, hintGCStats}
  161. result[0] = result[1] - {hintSuccessX, hintSuccess, hintConf,
  162. hintProcessing, hintPattern, hintExecuting, hintLinking}
  163. const
  164. NotesVerbosity* = computeNotesVerbosity()
  165. errXMustBeCompileTime* = "'$1' can only be used in compile-time context"
  166. errArgsNeedRunOption* = "arguments can only be given if the '--run' option is selected"
  167. type
  168. TFileInfo* = object
  169. fullPath*: AbsoluteFile # This is a canonical full filesystem path
  170. projPath*: RelativeFile # This is relative to the project's root
  171. shortName*: string # short name of the module
  172. quotedName*: Rope # cached quoted short name for codegen
  173. # purposes
  174. quotedFullName*: Rope # cached quoted full name for codegen
  175. # purposes
  176. lines*: seq[string] # the source code of the module
  177. # used for better error messages and
  178. # embedding the original source in the
  179. # generated code
  180. dirtyfile*: AbsoluteFile # the file that is actually read into memory
  181. # and parsed; usually "" but is used
  182. # for 'nimsuggest'
  183. hash*: string # the checksum of the file
  184. dirty*: bool # for 'nimfix' / 'nimpretty' like tooling
  185. when defined(nimpretty):
  186. fullContent*: string
  187. FileIndex* = distinct int32
  188. TLineInfo* = object # This is designed to be as small as possible,
  189. # because it is used
  190. # in syntax nodes. We save space here by using
  191. # two int16 and an int32.
  192. # On 64 bit and on 32 bit systems this is
  193. # only 8 bytes.
  194. line*: uint16
  195. col*: int16
  196. fileIndex*: FileIndex
  197. when defined(nimpretty):
  198. offsetA*, offsetB*: int
  199. commentOffsetA*, commentOffsetB*: int
  200. TErrorOutput* = enum
  201. eStdOut
  202. eStdErr
  203. TErrorOutputs* = set[TErrorOutput]
  204. ERecoverableError* = object of ValueError
  205. ESuggestDone* = object of Exception
  206. proc `==`*(a, b: FileIndex): bool {.borrow.}
  207. proc raiseRecoverableError*(msg: string) {.noinline, noreturn.} =
  208. raise newException(ERecoverableError, msg)
  209. const
  210. InvalidFileIDX* = FileIndex(-1)
  211. proc unknownLineInfo*(): TLineInfo =
  212. result.line = uint16(0)
  213. result.col = int16(-1)
  214. result.fileIndex = InvalidFileIDX
  215. type
  216. Severity* {.pure.} = enum ## VS Code only supports these three
  217. Hint, Warning, Error
  218. const trackPosInvalidFileIdx* = FileIndex(-2) # special marker so that no suggestions
  219. # are produced within comments and string literals
  220. type
  221. MsgConfig* = object ## does not need to be stored in the incremental cache
  222. trackPos*: TLineInfo
  223. trackPosAttached*: bool ## whether the tracking position was attached to
  224. ## some close token.
  225. errorOutputs*: TErrorOutputs
  226. msgContext*: seq[tuple[info: TLineInfo, detail: string]]
  227. lastError*: TLineInfo
  228. filenameToIndexTbl*: Table[string, FileIndex]
  229. fileInfos*: seq[TFileInfo]
  230. systemFileIdx*: FileIndex
  231. proc initMsgConfig*(): MsgConfig =
  232. result.msgContext = @[]
  233. result.lastError = unknownLineInfo()
  234. result.filenameToIndexTbl = initTable[string, FileIndex]()
  235. result.fileInfos = @[]
  236. result.errorOutputs = {eStdOut, eStdErr}