msgs.nim 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. import
  10. options, strutils, os, tables, ropes, platform, terminal, macros
  11. type
  12. TMsgKind* = enum
  13. errUnknown, errInternal, errIllFormedAstX, errCannotOpenFile, errGenerated,
  14. errXCompilerDoesNotSupportCpp, errStringLiteralExpected,
  15. errIntLiteralExpected, errInvalidCharacterConstant,
  16. errClosingTripleQuoteExpected, errClosingQuoteExpected,
  17. errTabulatorsAreNotAllowed, errInvalidToken, errLineTooLong,
  18. errInvalidNumber, errInvalidNumberOctalCode, errNumberOutOfRange,
  19. errNnotAllowedInCharacter, errClosingBracketExpected, errMissingFinalQuote,
  20. errIdentifierExpected, errNewlineExpected, errInvalidModuleName,
  21. errOperatorExpected, errTokenExpected, errStringAfterIncludeExpected,
  22. errRecursiveDependencyX, errOnOrOffExpected, errNoneSpeedOrSizeExpected,
  23. errInvalidPragma, errUnknownPragma, errInvalidDirectiveX,
  24. errAtPopWithoutPush, errEmptyAsm, errInvalidIndentation,
  25. errExceptionExpected, errExceptionAlreadyHandled,
  26. errYieldNotAllowedHere, errYieldNotAllowedInTryStmt,
  27. errInvalidNumberOfYieldExpr, errCannotReturnExpr, errAttemptToRedefine,
  28. errStmtInvalidAfterReturn, errStmtExpected, errInvalidLabel,
  29. errInvalidCmdLineOption, errCmdLineArgExpected, errCmdLineNoArgExpected,
  30. errInvalidVarSubstitution, errUnknownVar, errUnknownCcompiler,
  31. errOnOrOffExpectedButXFound, errOnOffOrListExpectedButXFound,
  32. errNoneBoehmRefcExpectedButXFound,
  33. errNoneSpeedOrSizeExpectedButXFound, errGuiConsoleOrLibExpectedButXFound,
  34. errUnknownOS, errUnknownCPU, errGenOutExpectedButXFound,
  35. errArgsNeedRunOption, errInvalidMultipleAsgn, errColonOrEqualsExpected,
  36. errExprExpected, errUndeclaredField,
  37. errUndeclaredRoutine, errUseQualifier,
  38. errTypeExpected,
  39. errSystemNeeds, errExecutionOfProgramFailed, errNotOverloadable,
  40. errInvalidArgForX, errStmtHasNoEffect, errXExpectsTypeOrValue,
  41. errXExpectsArrayType, errIteratorCannotBeInstantiated, errExprXAmbiguous,
  42. errConstantDivisionByZero, errOrdinalTypeExpected,
  43. errOrdinalOrFloatTypeExpected, errOverOrUnderflow,
  44. errCannotEvalXBecauseIncompletelyDefined, errChrExpectsRange0_255,
  45. errDynlibRequiresExportc, errUndeclaredFieldX, errNilAccess,
  46. errIndexOutOfBounds, errIndexTypesDoNotMatch, errBracketsInvalidForType,
  47. errValueOutOfSetBounds, errFieldInitTwice, errFieldNotInit,
  48. errExprXCannotBeCalled, errExprHasNoType, errExprXHasNoType,
  49. errCastNotInSafeMode, errExprCannotBeCastToX, errCommaOrParRiExpected,
  50. errCurlyLeOrParLeExpected, errSectionExpected, errRangeExpected,
  51. errMagicOnlyInSystem, errPowerOfTwoExpected,
  52. errStringMayNotBeEmpty, errCallConvExpected, errProcOnlyOneCallConv,
  53. errSymbolMustBeImported, errExprMustBeBool, errConstExprExpected,
  54. errDuplicateCaseLabel, errRangeIsEmpty, errSelectorMustBeOfCertainTypes,
  55. errSelectorMustBeOrdinal, errOrdXMustNotBeNegative, errLenXinvalid,
  56. errWrongNumberOfVariables, errExprCannotBeRaised, errBreakOnlyInLoop,
  57. errTypeXhasUnknownSize, errConstNeedsConstExpr, errConstNeedsValue,
  58. errResultCannotBeOpenArray, errSizeTooBig, errSetTooBig,
  59. errBaseTypeMustBeOrdinal, errInheritanceOnlyWithNonFinalObjects,
  60. errInheritanceOnlyWithEnums, errIllegalRecursionInTypeX,
  61. errCannotInstantiateX, errExprHasNoAddress, errXStackEscape,
  62. errVarForOutParamNeeded,
  63. errPureTypeMismatch, errTypeMismatch, errButExpected, errButExpectedX,
  64. errAmbiguousCallXYZ, errWrongNumberOfArguments,
  65. errWrongNumberOfArgumentsInCall,
  66. errMissingGenericParamsForTemplate,
  67. errXCannotBePassedToProcVar,
  68. errXCannotBeInParamDecl, errPragmaOnlyInHeaderOfProcX, errImplOfXNotAllowed,
  69. errImplOfXexpected, errNoSymbolToBorrowFromFound, errDiscardValueX,
  70. errInvalidDiscard, errIllegalConvFromXtoY, errCannotBindXTwice,
  71. errInvalidOrderInArrayConstructor,
  72. errInvalidOrderInEnumX, errEnumXHasHoles, errExceptExpected, errInvalidTry,
  73. errOptionExpected, errXisNoLabel, errNotAllCasesCovered,
  74. errUnknownSubstitionVar, errComplexStmtRequiresInd, errXisNotCallable,
  75. errNoPragmasAllowedForX, errNoGenericParamsAllowedForX,
  76. errInvalidParamKindX, errDefaultArgumentInvalid, errNamedParamHasToBeIdent,
  77. errNoReturnTypeForX, errConvNeedsOneArg, errInvalidPragmaX,
  78. errXNotAllowedHere, errInvalidControlFlowX,
  79. errXisNoType, errCircumNeedsPointer, errInvalidExpression,
  80. errInvalidExpressionX, errEnumHasNoValueX, errNamedExprExpected,
  81. errNamedExprNotAllowed, errXExpectsOneTypeParam,
  82. errArrayExpectsTwoTypeParams, errInvalidVisibilityX, errInitHereNotAllowed,
  83. errXCannotBeAssignedTo, errIteratorNotAllowed, errXNeedsReturnType,
  84. errNoReturnTypeDeclared,
  85. errNoCommand, errInvalidCommandX, errXOnlyAtModuleScope,
  86. errXNeedsParamObjectType,
  87. errTemplateInstantiationTooNested, errInstantiationFrom,
  88. errInvalidIndexValueForTuple, errCommandExpectsFilename,
  89. errMainModuleMustBeSpecified,
  90. errXExpected,
  91. errTIsNotAConcreteType,
  92. errCastToANonConcreteType,
  93. errInvalidSectionStart, errGridTableNotImplemented, errGeneralParseError,
  94. errNewSectionExpected, errWhitespaceExpected, errXisNoValidIndexFile,
  95. errCannotRenderX, errVarVarTypeNotAllowed, errInstantiateXExplicitly,
  96. errOnlyACallOpCanBeDelegator, errUsingNoSymbol,
  97. errMacroBodyDependsOnGenericTypes,
  98. errDestructorNotGenericEnough,
  99. errInlineIteratorsAsProcParams,
  100. errXExpectsTwoArguments,
  101. errXExpectsObjectTypes, errXcanNeverBeOfThisSubtype, errTooManyIterations,
  102. errCannotInterpretNodeX, errFieldXNotFound, errInvalidConversionFromTypeX,
  103. errAssertionFailed, errCannotGenerateCodeForX, errXRequiresOneArgument,
  104. errUnhandledExceptionX, errCyclicTree, errXisNoMacroOrTemplate,
  105. errXhasSideEffects, errIteratorExpected, errLetNeedsInit,
  106. errThreadvarCannotInit, errWrongSymbolX, errIllegalCaptureX,
  107. errXCannotBeClosure, errXMustBeCompileTime,
  108. errCannotInferTypeOfTheLiteral,
  109. errCannotInferReturnType,
  110. errCannotInferStaticParam,
  111. errGenericLambdaNotAllowed,
  112. errProcHasNoConcreteType,
  113. errCompilerDoesntSupportTarget,
  114. errInOutFlagNotExtern,
  115. errUser,
  116. warnCannotOpenFile,
  117. warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit,
  118. warnDeprecated, warnConfigDeprecated,
  119. warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel,
  120. warnUnknownSubstitutionX, warnLanguageXNotSupported,
  121. warnFieldXNotSupported, warnCommentXIgnored,
  122. warnNilStatement, warnTypelessParam,
  123. warnUseBase, warnWriteToForeignHeap, warnUnsafeCode,
  124. warnEachIdentIsTuple, warnShadowIdent,
  125. warnProveInit, warnProveField, warnProveIndex, warnGcUnsafe, warnGcUnsafe2,
  126. warnUninit, warnGcMem, warnDestructor, warnLockLevel, warnResultShadowed,
  127. warnUser,
  128. hintSuccess, hintSuccessX,
  129. hintLineTooLong, hintXDeclaredButNotUsed, hintConvToBaseNotNeeded,
  130. hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled,
  131. hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath,
  132. hintConditionAlwaysTrue, hintName, hintPattern,
  133. hintExecuting, hintLinking, hintDependency,
  134. hintSource, hintStackTrace, hintGCStats,
  135. hintUser, hintUserRaw
  136. const
  137. MsgKindToStr*: array[TMsgKind, string] = [
  138. errUnknown: "unknown error",
  139. errInternal: "internal error: $1",
  140. errIllFormedAstX: "illformed AST: $1",
  141. errCannotOpenFile: "cannot open \'$1\'",
  142. errGenerated: "$1",
  143. errXCompilerDoesNotSupportCpp: "\'$1\' compiler does not support C++",
  144. errStringLiteralExpected: "string literal expected",
  145. errIntLiteralExpected: "integer literal expected",
  146. errInvalidCharacterConstant: "invalid character constant",
  147. errClosingTripleQuoteExpected: "closing \"\"\" expected, but end of file reached",
  148. errClosingQuoteExpected: "closing \" expected",
  149. errTabulatorsAreNotAllowed: "tabulators are not allowed",
  150. errInvalidToken: "invalid token: $1",
  151. errLineTooLong: "line too long",
  152. errInvalidNumber: "$1 is not a valid number",
  153. errInvalidNumberOctalCode: "$1 is not a valid number; did you mean octal? Then use one of '0o', '0c' or '0C'.",
  154. errNumberOutOfRange: "number $1 out of valid range",
  155. errNnotAllowedInCharacter: "\\n not allowed in character literal",
  156. errClosingBracketExpected: "closing ']' expected, but end of file reached",
  157. errMissingFinalQuote: "missing final \' for character literal",
  158. errIdentifierExpected: "identifier expected, but found \'$1\'",
  159. errNewlineExpected: "newline expected, but found \'$1\'",
  160. errInvalidModuleName: "invalid module name: '$1'",
  161. errOperatorExpected: "operator expected, but found \'$1\'",
  162. errTokenExpected: "\'$1\' expected",
  163. errStringAfterIncludeExpected: "string after \'include\' expected",
  164. errRecursiveDependencyX: "recursive dependency: \'$1\'",
  165. errOnOrOffExpected: "\'on\' or \'off\' expected",
  166. errNoneSpeedOrSizeExpected: "\'none\', \'speed\' or \'size\' expected",
  167. errInvalidPragma: "invalid pragma",
  168. errUnknownPragma: "unknown pragma: \'$1\'",
  169. errInvalidDirectiveX: "invalid directive: \'$1\'",
  170. errAtPopWithoutPush: "\'pop\' without a \'push\' pragma",
  171. errEmptyAsm: "empty asm statement",
  172. errInvalidIndentation: "invalid indentation",
  173. errExceptionExpected: "exception expected",
  174. errExceptionAlreadyHandled: "exception already handled",
  175. errYieldNotAllowedHere: "'yield' only allowed in an iterator",
  176. errYieldNotAllowedInTryStmt: "'yield' cannot be used within 'try' in a non-inlined iterator",
  177. errInvalidNumberOfYieldExpr: "invalid number of \'yield\' expressions",
  178. errCannotReturnExpr: "current routine cannot return an expression",
  179. errAttemptToRedefine: "redefinition of \'$1\'",
  180. errStmtInvalidAfterReturn: "statement not allowed after \'return\', \'break\', \'raise\' or \'continue'",
  181. errStmtExpected: "statement expected",
  182. errInvalidLabel: "\'$1\' is no label",
  183. errInvalidCmdLineOption: "invalid command line option: \'$1\'",
  184. errCmdLineArgExpected: "argument for command line option expected: \'$1\'",
  185. errCmdLineNoArgExpected: "invalid argument for command line option: \'$1\'",
  186. errInvalidVarSubstitution: "invalid variable substitution in \'$1\'",
  187. errUnknownVar: "unknown variable: \'$1\'",
  188. errUnknownCcompiler: "unknown C compiler: \'$1\'",
  189. errOnOrOffExpectedButXFound: "\'on\' or \'off\' expected, but \'$1\' found",
  190. errOnOffOrListExpectedButXFound: "\'on\', \'off\' or \'list\' expected, but \'$1\' found",
  191. errNoneBoehmRefcExpectedButXFound: "'none', 'boehm' or 'refc' expected, but '$1' found",
  192. errNoneSpeedOrSizeExpectedButXFound: "'none', 'speed' or 'size' expected, but '$1' found",
  193. errGuiConsoleOrLibExpectedButXFound: "'gui', 'console' or 'lib' expected, but '$1' found",
  194. errUnknownOS: "unknown OS: '$1'",
  195. errUnknownCPU: "unknown CPU: '$1'",
  196. errGenOutExpectedButXFound: "'c', 'c++' or 'yaml' expected, but '$1' found",
  197. errArgsNeedRunOption: "arguments can only be given if the '--run' option is selected",
  198. errInvalidMultipleAsgn: "multiple assignment is not allowed",
  199. errColonOrEqualsExpected: "\':\' or \'=\' expected, but found \'$1\'",
  200. errExprExpected: "expression expected, but found \'$1\'",
  201. errUndeclaredField: "undeclared field: \'$1\'",
  202. errUndeclaredRoutine: "attempting to call undeclared routine: \'$1\'",
  203. errUseQualifier: "ambiguous identifier: \'$1\' -- use a qualifier",
  204. errTypeExpected: "type expected",
  205. errSystemNeeds: "system module needs \'$1\'",
  206. errExecutionOfProgramFailed: "execution of an external program failed: '$1'",
  207. errNotOverloadable: "overloaded \'$1\' leads to ambiguous calls",
  208. errInvalidArgForX: "invalid argument for \'$1\'",
  209. errStmtHasNoEffect: "statement has no effect",
  210. errXExpectsTypeOrValue: "\'$1\' expects a type or value",
  211. errXExpectsArrayType: "\'$1\' expects an array type",
  212. errIteratorCannotBeInstantiated: "'$1' cannot be instantiated because its body has not been compiled yet",
  213. errExprXAmbiguous: "expression '$1' ambiguous in this context",
  214. errConstantDivisionByZero: "division by zero",
  215. errOrdinalTypeExpected: "ordinal type expected",
  216. errOrdinalOrFloatTypeExpected: "ordinal or float type expected",
  217. errOverOrUnderflow: "over- or underflow",
  218. errCannotEvalXBecauseIncompletelyDefined: "cannot evaluate '$1' because type is not defined completely",
  219. errChrExpectsRange0_255: "\'chr\' expects an int in the range 0..255",
  220. errDynlibRequiresExportc: "\'dynlib\' requires \'exportc\'",
  221. errUndeclaredFieldX: "undeclared field: \'$1\'",
  222. errNilAccess: "attempt to access a nil address",
  223. errIndexOutOfBounds: "index out of bounds",
  224. errIndexTypesDoNotMatch: "index types do not match",
  225. errBracketsInvalidForType: "\'[]\' operator invalid for this type",
  226. errValueOutOfSetBounds: "value out of set bounds",
  227. errFieldInitTwice: "field initialized twice: \'$1\'",
  228. errFieldNotInit: "field \'$1\' not initialized",
  229. errExprXCannotBeCalled: "expression \'$1\' cannot be called",
  230. errExprHasNoType: "expression has no type",
  231. errExprXHasNoType: "expression \'$1\' has no type (or is ambiguous)",
  232. errCastNotInSafeMode: "\'cast\' not allowed in safe mode",
  233. errExprCannotBeCastToX: "expression cannot be cast to $1",
  234. errCommaOrParRiExpected: "',' or ')' expected",
  235. errCurlyLeOrParLeExpected: "\'{\' or \'(\' expected",
  236. errSectionExpected: "section (\'type\', \'proc\', etc.) expected",
  237. errRangeExpected: "range expected",
  238. errMagicOnlyInSystem: "\'magic\' only allowed in system module",
  239. errPowerOfTwoExpected: "power of two expected",
  240. errStringMayNotBeEmpty: "string literal may not be empty",
  241. errCallConvExpected: "calling convention expected",
  242. errProcOnlyOneCallConv: "a proc can only have one calling convention",
  243. errSymbolMustBeImported: "symbol must be imported if 'lib' pragma is used",
  244. errExprMustBeBool: "expression must be of type 'bool'",
  245. errConstExprExpected: "constant expression expected",
  246. errDuplicateCaseLabel: "duplicate case label",
  247. errRangeIsEmpty: "range is empty",
  248. errSelectorMustBeOfCertainTypes: "selector must be of an ordinal type, float or string",
  249. errSelectorMustBeOrdinal: "selector must be of an ordinal type",
  250. errOrdXMustNotBeNegative: "ord($1) must not be negative",
  251. errLenXinvalid: "len($1) must be less than 32768",
  252. errWrongNumberOfVariables: "wrong number of variables",
  253. errExprCannotBeRaised: "only a 'ref object' can be raised",
  254. errBreakOnlyInLoop: "'break' only allowed in loop construct",
  255. errTypeXhasUnknownSize: "type \'$1\' has unknown size",
  256. errConstNeedsConstExpr: "a constant can only be initialized with a constant expression",
  257. errConstNeedsValue: "a constant needs a value",
  258. errResultCannotBeOpenArray: "the result type cannot be on open array",
  259. errSizeTooBig: "computing the type\'s size produced an overflow",
  260. errSetTooBig: "set is too large",
  261. errBaseTypeMustBeOrdinal: "base type of a set must be an ordinal",
  262. errInheritanceOnlyWithNonFinalObjects: "inheritance only works with non-final objects",
  263. errInheritanceOnlyWithEnums: "inheritance only works with an enum",
  264. errIllegalRecursionInTypeX: "illegal recursion in type \'$1\'",
  265. errCannotInstantiateX: "cannot instantiate: \'$1\'",
  266. errExprHasNoAddress: "expression has no address",
  267. errXStackEscape: "address of '$1' may not escape its stack frame",
  268. errVarForOutParamNeeded: "for a \'var\' type a variable needs to be passed",
  269. errPureTypeMismatch: "type mismatch",
  270. errTypeMismatch: "type mismatch: got (",
  271. errButExpected: "but expected one of: ",
  272. errButExpectedX: "but expected \'$1\'",
  273. errAmbiguousCallXYZ: "ambiguous call; both $1 and $2 match for: $3",
  274. errWrongNumberOfArguments: "wrong number of arguments",
  275. errWrongNumberOfArgumentsInCall: "wrong number of arguments in call to '$1'",
  276. errMissingGenericParamsForTemplate: "'$1' has unspecified generic parameters",
  277. errXCannotBePassedToProcVar: "\'$1\' cannot be passed to a procvar",
  278. errXCannotBeInParamDecl: "$1 cannot be declared in parameter declaration",
  279. errPragmaOnlyInHeaderOfProcX: "pragmas are only allowed in the header of a proc; redefinition of $1",
  280. errImplOfXNotAllowed: "implementation of \'$1\' is not allowed",
  281. errImplOfXexpected: "implementation of \'$1\' expected",
  282. errNoSymbolToBorrowFromFound: "no symbol to borrow from found",
  283. errDiscardValueX: "value of type '$1' has to be discarded",
  284. errInvalidDiscard: "statement returns no value that can be discarded",
  285. errIllegalConvFromXtoY: "conversion from $1 to $2 is invalid",
  286. errCannotBindXTwice: "cannot bind parameter \'$1\' twice",
  287. errInvalidOrderInArrayConstructor: "invalid order in array constructor",
  288. errInvalidOrderInEnumX: "invalid order in enum \'$1\'",
  289. errEnumXHasHoles: "enum \'$1\' has holes",
  290. errExceptExpected: "\'except\' or \'finally\' expected",
  291. errInvalidTry: "after catch all \'except\' or \'finally\' no section may follow",
  292. errOptionExpected: "option expected, but found \'$1\'",
  293. errXisNoLabel: "\'$1\' is not a label",
  294. errNotAllCasesCovered: "not all cases are covered",
  295. errUnknownSubstitionVar: "unknown substitution variable: \'$1\'",
  296. errComplexStmtRequiresInd: "complex statement requires indentation",
  297. errXisNotCallable: "\'$1\' is not callable",
  298. errNoPragmasAllowedForX: "no pragmas allowed for $1",
  299. errNoGenericParamsAllowedForX: "no generic parameters allowed for $1",
  300. errInvalidParamKindX: "invalid param kind: \'$1\'",
  301. errDefaultArgumentInvalid: "default argument invalid",
  302. errNamedParamHasToBeIdent: "named parameter has to be an identifier",
  303. errNoReturnTypeForX: "no return type allowed for $1",
  304. errConvNeedsOneArg: "a type conversion needs exactly one argument",
  305. errInvalidPragmaX: "invalid pragma: $1",
  306. errXNotAllowedHere: "$1 not allowed here",
  307. errInvalidControlFlowX: "invalid control flow: $1",
  308. errXisNoType: "invalid type: \'$1\'",
  309. errCircumNeedsPointer: "'[]' needs a pointer or reference type",
  310. errInvalidExpression: "invalid expression",
  311. errInvalidExpressionX: "invalid expression: \'$1\'",
  312. errEnumHasNoValueX: "enum has no value \'$1\'",
  313. errNamedExprExpected: "named expression expected",
  314. errNamedExprNotAllowed: "named expression not allowed here",
  315. errXExpectsOneTypeParam: "\'$1\' expects one type parameter",
  316. errArrayExpectsTwoTypeParams: "array expects two type parameters",
  317. errInvalidVisibilityX: "invalid visibility: \'$1\'",
  318. errInitHereNotAllowed: "initialization not allowed here",
  319. errXCannotBeAssignedTo: "\'$1\' cannot be assigned to",
  320. errIteratorNotAllowed: "iterators can only be defined at the module\'s top level",
  321. errXNeedsReturnType: "$1 needs a return type",
  322. errNoReturnTypeDeclared: "no return type declared",
  323. errNoCommand: "no command given",
  324. errInvalidCommandX: "invalid command: \'$1\'",
  325. errXOnlyAtModuleScope: "\'$1\' is only allowed at top level",
  326. errXNeedsParamObjectType: "'$1' needs a parameter that has an object type",
  327. errTemplateInstantiationTooNested: "template/macro instantiation too nested",
  328. errInstantiationFrom: "template/generic instantiation from here",
  329. errInvalidIndexValueForTuple: "invalid index value for tuple subscript",
  330. errCommandExpectsFilename: "command expects a filename argument",
  331. errMainModuleMustBeSpecified: "please, specify a main module in the project configuration file",
  332. errXExpected: "\'$1\' expected",
  333. errTIsNotAConcreteType: "\'$1\' is not a concrete type.",
  334. errCastToANonConcreteType: "cannot cast to a non concrete type: \'$1\'",
  335. errInvalidSectionStart: "invalid section start",
  336. errGridTableNotImplemented: "grid table is not implemented",
  337. errGeneralParseError: "general parse error",
  338. errNewSectionExpected: "new section expected",
  339. errWhitespaceExpected: "whitespace expected, got \'$1\'",
  340. errXisNoValidIndexFile: "\'$1\' is no valid index file",
  341. errCannotRenderX: "cannot render reStructuredText element \'$1\'",
  342. errVarVarTypeNotAllowed: "type \'var var\' is not allowed",
  343. errInstantiateXExplicitly: "instantiate '$1' explicitly",
  344. errOnlyACallOpCanBeDelegator: "only a call operator can be a delegator",
  345. errUsingNoSymbol: "'$1' is not a variable, constant or a proc name",
  346. errMacroBodyDependsOnGenericTypes: "the macro body cannot be compiled, " &
  347. "because the parameter '$1' has a generic type",
  348. errDestructorNotGenericEnough: "Destructor signature is too specific. " &
  349. "A destructor must be associated will all instantiations of a generic type",
  350. errInlineIteratorsAsProcParams: "inline iterators can be used as parameters only for " &
  351. "templates, macros and other inline iterators",
  352. errXExpectsTwoArguments: "\'$1\' expects two arguments",
  353. errXExpectsObjectTypes: "\'$1\' expects object types",
  354. errXcanNeverBeOfThisSubtype: "\'$1\' can never be of this subtype",
  355. errTooManyIterations: "interpretation requires too many iterations",
  356. errCannotInterpretNodeX: "cannot evaluate \'$1\'",
  357. errFieldXNotFound: "field \'$1\' cannot be found",
  358. errInvalidConversionFromTypeX: "invalid conversion from type \'$1\'",
  359. errAssertionFailed: "assertion failed",
  360. errCannotGenerateCodeForX: "cannot generate code for \'$1\'",
  361. errXRequiresOneArgument: "$1 requires one parameter",
  362. errUnhandledExceptionX: "unhandled exception: $1",
  363. errCyclicTree: "macro returned a cyclic abstract syntax tree",
  364. errXisNoMacroOrTemplate: "\'$1\' is no macro or template",
  365. errXhasSideEffects: "\'$1\' can have side effects",
  366. errIteratorExpected: "iterator within for loop context expected",
  367. errLetNeedsInit: "'let' symbol requires an initialization",
  368. errThreadvarCannotInit: "a thread var cannot be initialized explicitly",
  369. errWrongSymbolX: "usage of \'$1\' is a user-defined error",
  370. errIllegalCaptureX: "illegal capture '$1'",
  371. errXCannotBeClosure: "'$1' cannot have 'closure' calling convention",
  372. errXMustBeCompileTime: "'$1' can only be used in compile-time context",
  373. errCannotInferTypeOfTheLiteral: "cannot infer the type of the $1",
  374. errCannotInferReturnType: "cannot infer the return type of the proc",
  375. errCannotInferStaticParam: "cannot infer the value of the static param `$1`",
  376. errGenericLambdaNotAllowed: "A nested proc can have generic parameters only when " &
  377. "it is used as an operand to another routine and the types " &
  378. "of the generic paramers can be inferred from the expected signature.",
  379. errProcHasNoConcreteType: "'$1' doesn't have a concrete type, due to unspecified generic parameters.",
  380. errCompilerDoesntSupportTarget: "The current compiler \'$1\' doesn't support the requested compilation target",
  381. errInOutFlagNotExtern: "The `$1` modifier can be used only with imported types",
  382. errUser: "$1",
  383. warnCannotOpenFile: "cannot open \'$1\'",
  384. warnOctalEscape: "octal escape sequences do not exist; leading zero is ignored",
  385. warnXIsNeverRead: "\'$1\' is never read",
  386. warnXmightNotBeenInit: "\'$1\' might not have been initialized",
  387. warnDeprecated: "$1 is deprecated",
  388. warnConfigDeprecated: "config file '$1' is deprecated",
  389. warnSmallLshouldNotBeUsed: "\'l\' should not be used as an identifier; may look like \'1\' (one)",
  390. warnUnknownMagic: "unknown magic \'$1\' might crash the compiler",
  391. warnRedefinitionOfLabel: "redefinition of label \'$1\'",
  392. warnUnknownSubstitutionX: "unknown substitution \'$1\'",
  393. warnLanguageXNotSupported: "language \'$1\' not supported",
  394. warnFieldXNotSupported: "field \'$1\' not supported",
  395. warnCommentXIgnored: "comment \'$1\' ignored",
  396. warnNilStatement: "'nil' statement is deprecated; use an empty 'discard' statement instead",
  397. warnTypelessParam: "'$1' has no type. Typeless parameters are deprecated; only allowed for 'template'",
  398. warnUseBase: "use {.base.} for base methods; baseless methods are deprecated",
  399. warnWriteToForeignHeap: "write to foreign heap",
  400. warnUnsafeCode: "unsafe code: '$1'",
  401. warnEachIdentIsTuple: "each identifier is a tuple",
  402. warnShadowIdent: "shadowed identifier: '$1'",
  403. warnProveInit: "Cannot prove that '$1' is initialized. This will become a compile time error in the future.",
  404. warnProveField: "cannot prove that field '$1' is accessible",
  405. warnProveIndex: "cannot prove index '$1' is valid",
  406. warnGcUnsafe: "not GC-safe: '$1'",
  407. warnGcUnsafe2: "$1",
  408. warnUninit: "'$1' might not have been initialized",
  409. warnGcMem: "'$1' uses GC'ed memory",
  410. warnDestructor: "usage of a type with a destructor in a non destructible context. This will become a compile time error in the future.",
  411. warnLockLevel: "$1",
  412. warnResultShadowed: "Special variable 'result' is shadowed.",
  413. warnUser: "$1",
  414. hintSuccess: "operation successful",
  415. hintSuccessX: "operation successful ($# lines compiled; $# sec total; $#; $#)",
  416. hintLineTooLong: "line too long",
  417. hintXDeclaredButNotUsed: "\'$1\' is declared but not used",
  418. hintConvToBaseNotNeeded: "conversion to base object is not needed",
  419. hintConvFromXtoItselfNotNeeded: "conversion from $1 to itself is pointless",
  420. hintExprAlwaysX: "expression evaluates always to \'$1\'",
  421. hintQuitCalled: "quit() called",
  422. hintProcessing: "$1",
  423. hintCodeBegin: "generated code listing:",
  424. hintCodeEnd: "end of listing",
  425. hintConf: "used config file \'$1\'",
  426. hintPath: "added path: '$1'",
  427. hintConditionAlwaysTrue: "condition is always true: '$1'",
  428. hintName: "name should be: '$1'",
  429. hintPattern: "$1",
  430. hintExecuting: "$1",
  431. hintLinking: "",
  432. hintDependency: "$1",
  433. hintSource: "$1",
  434. hintStackTrace: "$1",
  435. hintGCStats: "$1",
  436. hintUser: "$1",
  437. hintUserRaw: "$1"]
  438. const
  439. WarningsToStr* = ["CannotOpenFile", "OctalEscape",
  440. "XIsNeverRead", "XmightNotBeenInit",
  441. "Deprecated", "ConfigDeprecated",
  442. "SmallLshouldNotBeUsed", "UnknownMagic",
  443. "RedefinitionOfLabel", "UnknownSubstitutionX",
  444. "LanguageXNotSupported", "FieldXNotSupported",
  445. "CommentXIgnored", "NilStmt",
  446. "TypelessParam", "UseBase", "WriteToForeignHeap",
  447. "UnsafeCode", "EachIdentIsTuple", "ShadowIdent",
  448. "ProveInit", "ProveField", "ProveIndex", "GcUnsafe", "GcUnsafe2", "Uninit",
  449. "GcMem", "Destructor", "LockLevel", "ResultShadowed", "User"]
  450. HintsToStr* = ["Success", "SuccessX", "LineTooLong",
  451. "XDeclaredButNotUsed", "ConvToBaseNotNeeded", "ConvFromXtoItselfNotNeeded",
  452. "ExprAlwaysX", "QuitCalled", "Processing", "CodeBegin", "CodeEnd", "Conf",
  453. "Path", "CondTrue", "Name", "Pattern", "Exec", "Link", "Dependency",
  454. "Source", "StackTrace", "GCStats",
  455. "User", "UserRaw"]
  456. const
  457. fatalMin* = errUnknown
  458. fatalMax* = errInternal
  459. errMin* = errUnknown
  460. errMax* = errUser
  461. warnMin* = warnCannotOpenFile
  462. warnMax* = pred(hintSuccess)
  463. hintMin* = hintSuccess
  464. hintMax* = high(TMsgKind)
  465. type
  466. TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints
  467. TNoteKinds* = set[TNoteKind]
  468. TFileInfo* = object
  469. fullPath: string # This is a canonical full filesystem path
  470. projPath*: string # This is relative to the project's root
  471. shortName*: string # short name of the module
  472. quotedName*: Rope # cached quoted short name for codegen
  473. # purposes
  474. quotedFullName*: Rope # cached quoted full name for codegen
  475. # purposes
  476. lines*: seq[Rope] # the source code of the module
  477. # used for better error messages and
  478. # embedding the original source in the
  479. # generated code
  480. dirtyfile: string # the file that is actually read into memory
  481. # and parsed; usually 'nil' but is used
  482. # for 'nimsuggest'
  483. TLineInfo* = object # This is designed to be as small as possible,
  484. # because it is used
  485. # in syntax nodes. We save space here by using
  486. # two int16 and an int32.
  487. # On 64 bit and on 32 bit systems this is
  488. # only 8 bytes.
  489. line*, col*: int16
  490. fileIndex*: int32
  491. when defined(nimpretty):
  492. offsetA*, offsetB*: int
  493. commentOffsetA*, commentOffsetB*: int
  494. TErrorOutput* = enum
  495. eStdOut
  496. eStdErr
  497. TErrorOutputs* = set[TErrorOutput]
  498. ERecoverableError* = object of ValueError
  499. ESuggestDone* = object of Exception
  500. const
  501. NotesVerbosity*: array[0..3, TNoteKinds] = [
  502. {low(TNoteKind)..high(TNoteKind)} - {warnShadowIdent, warnUninit,
  503. warnProveField, warnProveIndex,
  504. warnGcUnsafe,
  505. hintSuccessX, hintPath, hintConf,
  506. hintProcessing, hintPattern,
  507. hintDependency,
  508. hintExecuting, hintLinking,
  509. hintCodeBegin, hintCodeEnd,
  510. hintSource, hintStackTrace,
  511. hintGCStats},
  512. {low(TNoteKind)..high(TNoteKind)} - {warnShadowIdent, warnUninit,
  513. warnProveField, warnProveIndex,
  514. warnGcUnsafe,
  515. hintPath,
  516. hintDependency,
  517. hintCodeBegin, hintCodeEnd,
  518. hintSource, hintStackTrace,
  519. hintGCStats},
  520. {low(TNoteKind)..high(TNoteKind)} - {hintStackTrace, warnUninit},
  521. {low(TNoteKind)..high(TNoteKind)}]
  522. const
  523. InvalidFileIDX* = int32(-1)
  524. var
  525. ForeignPackageNotes*: TNoteKinds = {hintProcessing, warnUnknownMagic,
  526. hintQuitCalled, hintExecuting}
  527. filenameToIndexTbl = initTable[string, int32]()
  528. fileInfos*: seq[TFileInfo] = @[]
  529. systemFileIdx*: int32
  530. proc toCChar*(c: char): string =
  531. case c
  532. of '\0'..'\x1F', '\x7F'..'\xFF': result = '\\' & toOctal(c)
  533. of '\'', '\"', '\\', '?': result = '\\' & c
  534. else: result = $(c)
  535. proc makeCString*(s: string): Rope =
  536. const
  537. MaxLineLength = 64
  538. result = nil
  539. var res = newStringOfCap(int(s.len.toFloat * 1.1) + 1)
  540. add(res, "\"")
  541. for i in countup(0, len(s) - 1):
  542. if (i + 1) mod MaxLineLength == 0:
  543. add(res, '\"')
  544. add(res, tnl)
  545. add(res, '\"')
  546. add(res, toCChar(s[i]))
  547. add(res, '\"')
  548. add(result, rope(res))
  549. proc newFileInfo(fullPath, projPath: string): TFileInfo =
  550. result.fullPath = fullPath
  551. #shallow(result.fullPath)
  552. result.projPath = projPath
  553. #shallow(result.projPath)
  554. let fileName = projPath.extractFilename
  555. result.shortName = fileName.changeFileExt("")
  556. result.quotedName = fileName.makeCString
  557. result.quotedFullName = fullPath.makeCString
  558. if optEmbedOrigSrc in gGlobalOptions or true:
  559. result.lines = @[]
  560. proc fileInfoKnown*(filename: string): bool =
  561. var
  562. canon: string
  563. try:
  564. canon = canonicalizePath(filename)
  565. except:
  566. canon = filename
  567. result = filenameToIndexTbl.hasKey(canon)
  568. proc fileInfoIdx*(filename: string; isKnownFile: var bool): int32 =
  569. var
  570. canon: string
  571. pseudoPath = false
  572. try:
  573. canon = canonicalizePath(filename)
  574. shallow(canon)
  575. except:
  576. canon = filename
  577. # The compiler uses "filenames" such as `command line` or `stdin`
  578. # This flag indicates that we are working with such a path here
  579. pseudoPath = true
  580. if filenameToIndexTbl.hasKey(canon):
  581. result = filenameToIndexTbl[canon]
  582. else:
  583. isKnownFile = false
  584. result = fileInfos.len.int32
  585. fileInfos.add(newFileInfo(canon, if pseudoPath: filename
  586. else: canon.shortenDir))
  587. filenameToIndexTbl[canon] = result
  588. proc fileInfoIdx*(filename: string): int32 =
  589. var dummy: bool
  590. result = fileInfoIdx(filename, dummy)
  591. proc newLineInfo*(fileInfoIdx: int32, line, col: int): TLineInfo =
  592. result.fileIndex = fileInfoIdx
  593. result.line = int16(line)
  594. result.col = int16(col)
  595. proc newLineInfo*(filename: string, line, col: int): TLineInfo {.inline.} =
  596. result = newLineInfo(filename.fileInfoIdx, line, col)
  597. fileInfos.add(newFileInfo("", "command line"))
  598. var gCmdLineInfo* = newLineInfo(int32(0), 1, 1)
  599. fileInfos.add(newFileInfo("", "compilation artifact"))
  600. var gCodegenLineInfo* = newLineInfo(int32(1), 1, 1)
  601. proc raiseRecoverableError*(msg: string) {.noinline, noreturn.} =
  602. raise newException(ERecoverableError, msg)
  603. proc sourceLine*(i: TLineInfo): Rope
  604. var
  605. gNotes*: TNoteKinds = NotesVerbosity[1] # defaults to verbosity of 1
  606. gErrorCounter*: int = 0 # counts the number of errors
  607. gHintCounter*: int = 0
  608. gWarnCounter*: int = 0
  609. gErrorMax*: int = 1 # stop after gErrorMax errors
  610. gMainPackageNotes*: TNoteKinds = NotesVerbosity[1]
  611. proc unknownLineInfo*(): TLineInfo =
  612. result.line = int16(-1)
  613. result.col = int16(-1)
  614. result.fileIndex = -1
  615. type
  616. Severity* {.pure.} = enum ## VS Code only supports these three
  617. Hint, Warning, Error
  618. var
  619. msgContext: seq[TLineInfo] = @[]
  620. lastError = unknownLineInfo()
  621. errorOutputs* = {eStdOut, eStdErr}
  622. writelnHook*: proc (output: string) {.closure.}
  623. structuredErrorHook*: proc (info: TLineInfo; msg: string; severity: Severity) {.closure.}
  624. proc concat(strings: openarray[string]): string =
  625. var totalLen = 0
  626. for s in strings: totalLen += s.len
  627. result = newStringOfCap totalLen
  628. for s in strings: result.add s
  629. proc suggestWriteln*(s: string) =
  630. if eStdOut in errorOutputs:
  631. if isNil(writelnHook):
  632. writeLine(stdout, s)
  633. flushFile(stdout)
  634. else:
  635. writelnHook(s)
  636. proc msgQuit*(x: int8) = quit x
  637. proc msgQuit*(x: string) = quit x
  638. proc suggestQuit*() =
  639. raise newException(ESuggestDone, "suggest done")
  640. # this format is understood by many text editors: it is the same that
  641. # Borland and Freepascal use
  642. const
  643. PosFormat = "$1($2, $3) "
  644. KindFormat = " [$1]"
  645. KindColor = fgCyan
  646. ErrorTitle = "Error: "
  647. ErrorColor = fgRed
  648. WarningTitle = "Warning: "
  649. WarningColor = fgYellow
  650. HintTitle = "Hint: "
  651. HintColor = fgGreen
  652. proc getInfoContextLen*(): int = return msgContext.len
  653. proc setInfoContextLen*(L: int) = setLen(msgContext, L)
  654. proc pushInfoContext*(info: TLineInfo) =
  655. msgContext.add(info)
  656. proc popInfoContext*() =
  657. setLen(msgContext, len(msgContext) - 1)
  658. proc getInfoContext*(index: int): TLineInfo =
  659. let L = msgContext.len
  660. let i = if index < 0: L + index else: index
  661. if i >=% L: result = unknownLineInfo()
  662. else: result = msgContext[i]
  663. template toFilename*(fileIdx: int32): string =
  664. (if fileIdx < 0: "???" else: fileInfos[fileIdx].projPath)
  665. proc toFullPath*(fileIdx: int32): string =
  666. if fileIdx < 0: result = "???"
  667. else: result = fileInfos[fileIdx].fullPath
  668. proc setDirtyFile*(fileIdx: int32; filename: string) =
  669. assert fileIdx >= 0
  670. fileInfos[fileIdx].dirtyFile = filename
  671. proc toFullPathConsiderDirty*(fileIdx: int32): string =
  672. if fileIdx < 0:
  673. result = "???"
  674. elif not fileInfos[fileIdx].dirtyFile.isNil:
  675. result = fileInfos[fileIdx].dirtyFile
  676. else:
  677. result = fileInfos[fileIdx].fullPath
  678. template toFilename*(info: TLineInfo): string =
  679. info.fileIndex.toFilename
  680. template toFullPath*(info: TLineInfo): string =
  681. info.fileIndex.toFullPath
  682. proc toMsgFilename*(info: TLineInfo): string =
  683. if info.fileIndex < 0:
  684. result = "???"
  685. elif gListFullPaths:
  686. result = fileInfos[info.fileIndex].fullPath
  687. else:
  688. result = fileInfos[info.fileIndex].projPath
  689. proc toLinenumber*(info: TLineInfo): int {.inline.} =
  690. result = info.line
  691. proc toColumn*(info: TLineInfo): int {.inline.} =
  692. result = info.col
  693. proc toFileLine*(info: TLineInfo): string {.inline.} =
  694. result = info.toFilename & ":" & $info.line
  695. proc toFileLineCol*(info: TLineInfo): string {.inline.} =
  696. result = info.toFilename & "(" & $info.line & ", " & $info.col & ")"
  697. proc `$`*(info: TLineInfo): string = toFileLineCol(info)
  698. proc `??`* (info: TLineInfo, filename: string): bool =
  699. # only for debugging purposes
  700. result = filename in info.toFilename
  701. const trackPosInvalidFileIdx* = -2 # special marker so that no suggestions
  702. # are produced within comments and string literals
  703. var gTrackPos*: TLineInfo
  704. var gTrackPosAttached*: bool ## whether the tracking position was attached to some
  705. ## close token.
  706. type
  707. MsgFlag* = enum ## flags altering msgWriteln behavior
  708. msgStdout, ## force writing to stdout, even stderr is default
  709. msgSkipHook ## skip message hook even if it is present
  710. MsgFlags* = set[MsgFlag]
  711. proc msgWriteln*(s: string, flags: MsgFlags = {}) =
  712. ## Writes given message string to stderr by default.
  713. ## If ``--stdout`` option is given, writes to stdout instead. If message hook
  714. ## is present, then it is used to output message rather than stderr/stdout.
  715. ## This behavior can be altered by given optional flags.
  716. ## This is used for 'nim dump' etc. where we don't have nimsuggest
  717. ## support.
  718. #if gCmd == cmdIdeTools and optCDebug notin gGlobalOptions: return
  719. if not isNil(writelnHook) and msgSkipHook notin flags:
  720. writelnHook(s)
  721. elif optStdout in gGlobalOptions or msgStdout in flags:
  722. if eStdOut in errorOutputs:
  723. writeLine(stdout, s)
  724. flushFile(stdout)
  725. else:
  726. if eStdErr in errorOutputs:
  727. writeLine(stderr, s)
  728. # On Windows stderr is fully-buffered when piped, regardless of C std.
  729. when defined(windows):
  730. flushFile(stderr)
  731. macro callIgnoringStyle(theProc: typed, first: typed,
  732. args: varargs[typed]): untyped =
  733. let typForegroundColor = bindSym"ForegroundColor".getType
  734. let typBackgroundColor = bindSym"BackgroundColor".getType
  735. let typStyle = bindSym"Style".getType
  736. let typTerminalCmd = bindSym"TerminalCmd".getType
  737. result = newCall(theProc)
  738. if first.kind != nnkNilLit: result.add(first)
  739. for arg in children(args[0][1]):
  740. if arg.kind == nnkNilLit: continue
  741. let typ = arg.getType
  742. if typ.kind != nnkEnumTy or
  743. typ != typForegroundColor and
  744. typ != typBackgroundColor and
  745. typ != typStyle and
  746. typ != typTerminalCmd:
  747. result.add(arg)
  748. macro callStyledWriteLineStderr(args: varargs[typed]): untyped =
  749. result = newCall(bindSym"styledWriteLine")
  750. result.add(bindSym"stderr")
  751. for arg in children(args[0][1]):
  752. result.add(arg)
  753. template callWritelnHook(args: varargs[string, `$`]) =
  754. writelnHook concat(args)
  755. template styledMsgWriteln*(args: varargs[typed]) =
  756. if not isNil(writelnHook):
  757. callIgnoringStyle(callWritelnHook, nil, args)
  758. elif optStdout in gGlobalOptions:
  759. if eStdOut in errorOutputs:
  760. callIgnoringStyle(writeLine, stdout, args)
  761. flushFile(stdout)
  762. else:
  763. if eStdErr in errorOutputs:
  764. if optUseColors in gGlobalOptions:
  765. callStyledWriteLineStderr(args)
  766. else:
  767. callIgnoringStyle(writeLine, stderr, args)
  768. # On Windows stderr is fully-buffered when piped, regardless of C std.
  769. when defined(windows):
  770. flushFile(stderr)
  771. proc coordToStr(coord: int): string =
  772. if coord == -1: result = "???"
  773. else: result = $coord
  774. proc msgKindToString*(kind: TMsgKind): string =
  775. # later versions may provide translated error messages
  776. result = MsgKindToStr[kind]
  777. proc getMessageStr(msg: TMsgKind, arg: string): string =
  778. result = msgKindToString(msg) % [arg]
  779. type
  780. TErrorHandling = enum doNothing, doAbort, doRaise
  781. proc log*(s: string) {.procvar.} =
  782. var f: File
  783. if open(f, getHomeDir() / "nimsuggest.log", fmAppend):
  784. f.writeLine(s)
  785. close(f)
  786. proc quit(msg: TMsgKind) =
  787. if defined(debug) or msg == errInternal or hintStackTrace in gNotes:
  788. if stackTraceAvailable() and isNil(writelnHook):
  789. writeStackTrace()
  790. else:
  791. styledMsgWriteln(fgRed, "No stack traceback available\n" &
  792. "To create a stacktrace, rerun compilation with ./koch temp " &
  793. options.command & " <file>")
  794. quit 1
  795. proc handleError(msg: TMsgKind, eh: TErrorHandling, s: string) =
  796. if msg >= fatalMin and msg <= fatalMax:
  797. if gCmd == cmdIdeTools: log(s)
  798. quit(msg)
  799. if msg >= errMin and msg <= errMax:
  800. inc(gErrorCounter)
  801. options.gExitcode = 1'i8
  802. if gErrorCounter >= gErrorMax:
  803. quit(msg)
  804. elif eh == doAbort and gCmd != cmdIdeTools:
  805. quit(msg)
  806. elif eh == doRaise:
  807. raiseRecoverableError(s)
  808. proc `==`*(a, b: TLineInfo): bool =
  809. result = a.line == b.line and a.fileIndex == b.fileIndex
  810. proc exactEquals*(a, b: TLineInfo): bool =
  811. result = a.fileIndex == b.fileIndex and a.line == b.line and a.col == b.col
  812. proc writeContext(lastinfo: TLineInfo) =
  813. var info = lastinfo
  814. for i in countup(0, len(msgContext) - 1):
  815. if msgContext[i] != lastinfo and msgContext[i] != info:
  816. if structuredErrorHook != nil:
  817. structuredErrorHook(msgContext[i], getMessageStr(errInstantiationFrom, ""),
  818. Severity.Error)
  819. else:
  820. styledMsgWriteln(styleBright,
  821. PosFormat % [toMsgFilename(msgContext[i]),
  822. coordToStr(msgContext[i].line),
  823. coordToStr(msgContext[i].col+1)],
  824. resetStyle,
  825. getMessageStr(errInstantiationFrom, ""))
  826. info = msgContext[i]
  827. proc ignoreMsgBecauseOfIdeTools(msg: TMsgKind): bool =
  828. msg >= errGenerated and gCmd == cmdIdeTools and optIdeDebug notin gGlobalOptions
  829. proc rawMessage*(msg: TMsgKind, args: openArray[string]) =
  830. var
  831. title: string
  832. color: ForegroundColor
  833. kind: string
  834. sev: Severity
  835. case msg
  836. of errMin..errMax:
  837. sev = Severity.Error
  838. writeContext(unknownLineInfo())
  839. title = ErrorTitle
  840. color = ErrorColor
  841. of warnMin..warnMax:
  842. sev = Severity.Warning
  843. if optWarns notin gOptions: return
  844. if msg notin gNotes: return
  845. writeContext(unknownLineInfo())
  846. title = WarningTitle
  847. color = WarningColor
  848. kind = WarningsToStr[ord(msg) - ord(warnMin)]
  849. inc(gWarnCounter)
  850. of hintMin..hintMax:
  851. sev = Severity.Hint
  852. if optHints notin gOptions: return
  853. if msg notin gNotes: return
  854. title = HintTitle
  855. color = HintColor
  856. if msg != hintUserRaw: kind = HintsToStr[ord(msg) - ord(hintMin)]
  857. inc(gHintCounter)
  858. let s = msgKindToString(msg) % args
  859. if structuredErrorHook != nil:
  860. structuredErrorHook(unknownLineInfo(), s & (if kind != nil: KindFormat % kind else: ""), sev)
  861. if not ignoreMsgBecauseOfIdeTools(msg):
  862. if kind != nil:
  863. styledMsgWriteln(color, title, resetStyle, s,
  864. KindColor, `%`(KindFormat, kind))
  865. else:
  866. styledMsgWriteln(color, title, resetStyle, s)
  867. handleError(msg, doAbort, s)
  868. proc rawMessage*(msg: TMsgKind, arg: string) =
  869. rawMessage(msg, [arg])
  870. proc resetAttributes* =
  871. if {optUseColors, optStdout} * gGlobalOptions == {optUseColors}:
  872. terminal.resetAttributes(stderr)
  873. proc writeSurroundingSrc(info: TLineInfo) =
  874. const indent = " "
  875. msgWriteln(indent & $info.sourceLine)
  876. msgWriteln(indent & spaces(info.col) & '^')
  877. proc formatMsg*(info: TLineInfo, msg: TMsgKind, arg: string): string =
  878. let title = case msg
  879. of warnMin..warnMax: WarningTitle
  880. of hintMin..hintMax: HintTitle
  881. else: ErrorTitle
  882. result = PosFormat % [toMsgFilename(info), coordToStr(info.line),
  883. coordToStr(info.col+1)] &
  884. title &
  885. getMessageStr(msg, arg)
  886. proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string,
  887. eh: TErrorHandling) =
  888. var
  889. title: string
  890. color: ForegroundColor
  891. kind: string
  892. ignoreMsg = false
  893. sev: Severity
  894. case msg
  895. of errMin..errMax:
  896. sev = Severity.Error
  897. writeContext(info)
  898. title = ErrorTitle
  899. color = ErrorColor
  900. # we try to filter error messages so that not two error message
  901. # in the same file and line are produced:
  902. #ignoreMsg = lastError == info and eh != doAbort
  903. lastError = info
  904. of warnMin..warnMax:
  905. sev = Severity.Warning
  906. ignoreMsg = optWarns notin gOptions or msg notin gNotes
  907. if not ignoreMsg: writeContext(info)
  908. title = WarningTitle
  909. color = WarningColor
  910. kind = WarningsToStr[ord(msg) - ord(warnMin)]
  911. inc(gWarnCounter)
  912. of hintMin..hintMax:
  913. sev = Severity.Hint
  914. ignoreMsg = optHints notin gOptions or msg notin gNotes
  915. title = HintTitle
  916. color = HintColor
  917. if msg != hintUserRaw: kind = HintsToStr[ord(msg) - ord(hintMin)]
  918. inc(gHintCounter)
  919. # NOTE: currently line info line numbers start with 1,
  920. # but column numbers start with 0, however most editors expect
  921. # first column to be 1, so we need to +1 here
  922. let x = PosFormat % [toMsgFilename(info), coordToStr(info.line),
  923. coordToStr(info.col+1)]
  924. let s = getMessageStr(msg, arg)
  925. if not ignoreMsg:
  926. if structuredErrorHook != nil:
  927. structuredErrorHook(info, s & (if kind != nil: KindFormat % kind else: ""), sev)
  928. if not ignoreMsgBecauseOfIdeTools(msg):
  929. if kind != nil:
  930. styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s,
  931. KindColor, `%`(KindFormat, kind))
  932. else:
  933. styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s)
  934. if msg in errMin..errMax and hintSource in gNotes:
  935. info.writeSurroundingSrc
  936. handleError(msg, eh, s)
  937. proc fatal*(info: TLineInfo, msg: TMsgKind, arg = "") =
  938. liMessage(info, msg, arg, doAbort)
  939. proc globalError*(info: TLineInfo, msg: TMsgKind, arg = "") =
  940. liMessage(info, msg, arg, doRaise)
  941. proc globalError*(info: TLineInfo, arg: string) =
  942. liMessage(info, errGenerated, arg, doRaise)
  943. proc localError*(info: TLineInfo, msg: TMsgKind, arg = "") =
  944. liMessage(info, msg, arg, doNothing)
  945. proc localError*(info: TLineInfo, arg: string) =
  946. liMessage(info, errGenerated, arg, doNothing)
  947. proc localError*(info: TLineInfo, format: string, params: openarray[string]) =
  948. localError(info, format % params)
  949. proc message*(info: TLineInfo, msg: TMsgKind, arg = "") =
  950. liMessage(info, msg, arg, doNothing)
  951. proc internalError*(info: TLineInfo, errMsg: string) =
  952. if gCmd == cmdIdeTools and structuredErrorHook.isNil: return
  953. writeContext(info)
  954. liMessage(info, errInternal, errMsg, doAbort)
  955. proc internalError*(errMsg: string) =
  956. if gCmd == cmdIdeTools and structuredErrorHook.isNil: return
  957. writeContext(unknownLineInfo())
  958. rawMessage(errInternal, errMsg)
  959. template assertNotNil*(e): untyped =
  960. if e == nil: internalError($instantiationInfo())
  961. e
  962. template internalAssert*(e: bool) =
  963. if not e: internalError($instantiationInfo())
  964. proc addSourceLine*(fileIdx: int32, line: string) =
  965. fileInfos[fileIdx].lines.add line.rope
  966. proc sourceLine*(i: TLineInfo): Rope =
  967. if i.fileIndex < 0: return nil
  968. if not optPreserveOrigSource and fileInfos[i.fileIndex].lines.len == 0:
  969. try:
  970. for line in lines(i.toFullPath):
  971. addSourceLine i.fileIndex, line.string
  972. except IOError:
  973. discard
  974. internalAssert i.fileIndex < fileInfos.len
  975. # can happen if the error points to EOF:
  976. if i.line > fileInfos[i.fileIndex].lines.len: return nil
  977. result = fileInfos[i.fileIndex].lines[i.line-1]
  978. proc quotedFilename*(i: TLineInfo): Rope =
  979. internalAssert i.fileIndex >= 0
  980. if optExcessiveStackTrace in gGlobalOptions:
  981. result = fileInfos[i.fileIndex].quotedFullName
  982. else:
  983. result = fileInfos[i.fileIndex].quotedName
  984. ropes.errorHandler = proc (err: RopesError, msg: string, useWarning: bool) =
  985. case err
  986. of rInvalidFormatStr:
  987. internalError("ropes: invalid format string: " & msg)
  988. of rCannotOpenFile:
  989. rawMessage(if useWarning: warnCannotOpenFile else: errCannotOpenFile, msg)
  990. proc listWarnings*() =
  991. msgWriteln("Warnings:")
  992. for warn in warnMin..warnMax:
  993. msgWriteln(" [$1] $2" % [
  994. if warn in gNotes: "x" else: " ",
  995. msgs.WarningsToStr[ord(warn) - ord(warnMin)]
  996. ])
  997. proc listHints*() =
  998. msgWriteln("Hints:")
  999. for hint in hintMin..hintMax:
  1000. msgWriteln(" [$1] $2" % [
  1001. if hint in gNotes: "x" else: " ",
  1002. msgs.HintsToStr[ord(hint) - ord(hintMin)]
  1003. ])
  1004. # enable colors by default on terminals
  1005. if terminal.isatty(stderr):
  1006. incl(gGlobalOptions, optUseColors)