lineinfos.nim 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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, hintConditionAlwaysFalse, 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. hintConditionAlwaysFalse: "condition is always false: '$1'",
  106. hintName: "name should be: '$1'",
  107. hintPattern: "$1",
  108. hintExecuting: "$1",
  109. hintLinking: "",
  110. hintDependency: "$1",
  111. hintSource: "$1",
  112. hintPerformance: "$1",
  113. hintStackTrace: "$1",
  114. hintGCStats: "$1",
  115. hintGlobalVar: "global variable declared here",
  116. hintUser: "$1",
  117. hintUserRaw: "$1",
  118. hintExtendedContext: "$1",
  119. ]
  120. const
  121. WarningsToStr* = ["CannotOpenFile", "OctalEscape",
  122. "XIsNeverRead", "XmightNotBeenInit",
  123. "Deprecated", "ConfigDeprecated",
  124. "SmallLshouldNotBeUsed", "UnknownMagic",
  125. "RedefinitionOfLabel", "UnknownSubstitutionX",
  126. "LanguageXNotSupported", "FieldXNotSupported",
  127. "CommentXIgnored",
  128. "TypelessParam", "UseBase", "WriteToForeignHeap",
  129. "UnsafeCode", "EachIdentIsTuple", "ShadowIdent",
  130. "ProveInit", "ProveField", "ProveIndex", "GcUnsafe", "GcUnsafe2", "Uninit",
  131. "GcMem", "Destructor", "LockLevel", "ResultShadowed",
  132. "Spacing", "User"]
  133. HintsToStr* = [
  134. "Success", "SuccessX", "CC", "LineTooLong",
  135. "XDeclaredButNotUsed", "ConvToBaseNotNeeded", "ConvFromXtoItselfNotNeeded",
  136. "ExprAlwaysX", "QuitCalled", "Processing", "CodeBegin", "CodeEnd", "Conf",
  137. "Path", "CondTrue", "CondFalse", "Name", "Pattern", "Exec", "Link", "Dependency",
  138. "Source", "Performance", "StackTrace", "GCStats", "GlobalVar",
  139. "User", "UserRaw", "ExtendedContext",
  140. ]
  141. const
  142. fatalMin* = errUnknown
  143. fatalMax* = errInternal
  144. errMin* = errUnknown
  145. errMax* = errUser
  146. warnMin* = warnCannotOpenFile
  147. warnMax* = pred(hintSuccess)
  148. hintMin* = hintSuccess
  149. hintMax* = high(TMsgKind)
  150. static:
  151. doAssert HintsToStr.len == ord(hintMax) - ord(hintMin) + 1
  152. doAssert WarningsToStr.len == ord(warnMax) - ord(warnMin) + 1
  153. type
  154. TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints
  155. TNoteKinds* = set[TNoteKind]
  156. proc computeNotesVerbosity(): array[0..3, TNoteKinds] =
  157. result[3] = {low(TNoteKind)..high(TNoteKind)} - {}
  158. result[2] = result[3] - {hintStackTrace, warnUninit, hintExtendedContext}
  159. result[1] = result[2] - {warnShadowIdent, warnProveField, warnProveIndex,
  160. warnGcUnsafe, hintPath, hintDependency, hintCodeBegin, hintCodeEnd,
  161. hintSource, hintGlobalVar, hintGCStats}
  162. result[0] = result[1] - {hintSuccessX, hintSuccess, hintConf,
  163. hintProcessing, hintPattern, hintExecuting, hintLinking}
  164. const
  165. NotesVerbosity* = computeNotesVerbosity()
  166. errXMustBeCompileTime* = "'$1' can only be used in compile-time context"
  167. errArgsNeedRunOption* = "arguments can only be given if the '--run' option is selected"
  168. type
  169. TFileInfo* = object
  170. fullPath*: AbsoluteFile # This is a canonical full filesystem path
  171. projPath*: RelativeFile # This is relative to the project's root
  172. shortName*: string # short name of the module
  173. quotedName*: Rope # cached quoted short name for codegen
  174. # purposes
  175. quotedFullName*: Rope # cached quoted full name for codegen
  176. # purposes
  177. lines*: seq[string] # the source code of the module
  178. # used for better error messages and
  179. # embedding the original source in the
  180. # generated code
  181. dirtyfile*: AbsoluteFile # the file that is actually read into memory
  182. # and parsed; usually "" but is used
  183. # for 'nimsuggest'
  184. hash*: string # the checksum of the file
  185. dirty*: bool # for 'nimfix' / 'nimpretty' like tooling
  186. when defined(nimpretty):
  187. fullContent*: string
  188. FileIndex* = distinct int32
  189. TLineInfo* = object # This is designed to be as small as possible,
  190. # because it is used
  191. # in syntax nodes. We save space here by using
  192. # two int16 and an int32.
  193. # On 64 bit and on 32 bit systems this is
  194. # only 8 bytes.
  195. line*: uint16
  196. col*: int16
  197. fileIndex*: FileIndex
  198. when defined(nimpretty):
  199. offsetA*, offsetB*: int
  200. commentOffsetA*, commentOffsetB*: int
  201. TErrorOutput* = enum
  202. eStdOut
  203. eStdErr
  204. TErrorOutputs* = set[TErrorOutput]
  205. ERecoverableError* = object of ValueError
  206. ESuggestDone* = object of Exception
  207. proc `==`*(a, b: FileIndex): bool {.borrow.}
  208. proc raiseRecoverableError*(msg: string) {.noinline, noreturn.} =
  209. raise newException(ERecoverableError, msg)
  210. const
  211. InvalidFileIDX* = FileIndex(-1)
  212. proc unknownLineInfo*(): TLineInfo =
  213. result.line = uint16(0)
  214. result.col = int16(-1)
  215. result.fileIndex = InvalidFileIDX
  216. type
  217. Severity* {.pure.} = enum ## VS Code only supports these three
  218. Hint, Warning, Error
  219. const trackPosInvalidFileIdx* = FileIndex(-2) # special marker so that no suggestions
  220. # are produced within comments and string literals
  221. type
  222. MsgConfig* = object ## does not need to be stored in the incremental cache
  223. trackPos*: TLineInfo
  224. trackPosAttached*: bool ## whether the tracking position was attached to
  225. ## some close token.
  226. errorOutputs*: TErrorOutputs
  227. msgContext*: seq[tuple[info: TLineInfo, detail: string]]
  228. lastError*: TLineInfo
  229. filenameToIndexTbl*: Table[string, FileIndex]
  230. fileInfos*: seq[TFileInfo]
  231. systemFileIdx*: FileIndex
  232. proc initMsgConfig*(): MsgConfig =
  233. result.msgContext = @[]
  234. result.lastError = unknownLineInfo()
  235. result.filenameToIndexTbl = initTable[string, FileIndex]()
  236. result.fileInfos = @[]
  237. result.errorOutputs = {eStdOut, eStdErr}