lineinfos.nim 11 KB

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