lineinfos.nim 12 KB

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