From e726324e2e5adbae1b6b3862acd25b1b951b559e Mon Sep 17 00:00:00 2001 From: haxscramper Date: Wed, 26 Jan 2022 23:30:20 +0300 Subject: [PATCH] Refactor active configuration handing - Move active configuration handing into a separate type that should contain all the required configuration parameters. Use this type in `ConfigRef` module, and use accessor procs for getting and setting values of different options, thus removing unguarded access for fields in a number of cases. - Move report kind and category enums into `report_enums` in order to make them accessible from the `in_options` - it must be a lightweight dependency since it is supposed to be reused by other tools, like testament, that have to directly interact with the compiler. Closes https://github.com/nim-works/nimskull/issues/158 --- compiler/ast/ast_types.nim | 45 +- compiler/ast/report_enums.nim | 1096 ++++++++++++++++++++++++++++++ compiler/ast/reports.nim | 1084 +---------------------------- compiler/backend/extccomp.nim | 45 +- compiler/front/cli_reporter.nim | 4 +- compiler/front/cmdlinehelper.nim | 4 +- compiler/front/commands.nim | 279 ++++---- compiler/front/condsyms.nim | 18 +- compiler/front/in_options.nim | 318 +++++++++ compiler/front/main.nim | 22 +- compiler/front/options.nim | 489 ++++++------- compiler/front/scriptconfig.nim | 27 +- compiler/ic/ic.nim | 5 +- compiler/modules/nimblecmd.nim | 8 +- compiler/sem/passes.nim | 4 +- compiler/sem/pragmas.nim | 7 +- compiler/vm/vm.nim | 2 +- compiler/vm/vmops.nim | 42 +- 18 files changed, 1865 insertions(+), 1634 deletions(-) create mode 100644 compiler/ast/report_enums.nim create mode 100644 compiler/front/in_options.nim diff --git a/compiler/ast/ast_types.nim b/compiler/ast/ast_types.nim index 79f0ad97800..9967e411527 100644 --- a/compiler/ast/ast_types.nim +++ b/compiler/ast/ast_types.nim @@ -1,52 +1,11 @@ import utils/ropes import std/[hashes] +from front/in_options import TOption, TOptions # Stored in `PSym` + const hasFFI = defined(nimHasLibFFI) -type - TOption* = enum - ## please make sure we have under 32 options (improves code efficiency - ## a lot!) **keep binary compatible** - optNone - optObjCheck ## `ccgenexprs.nim` generates `isObj` check if this options - ## is enabled for a procedure - optFieldCheck ## Codegen uses it to conditionally generate check for a - ## discriminant field - optRangeCheck ## Control generation of range checks in the backend - optBoundsCheck ## Control generation of the array boundary checks in - ## the backend - optOverflowCheck ## Integer overflow check control - optRefCheck ## Deprecated option, does something with refs in te - ## `liftdestructors.nim`, need to investigate further - optNaNCheck ## Raise float invalid defect C backend if operation - ## returned nan - optInfCheck ## Raise float overflow in C backend if operation reaturned - ## inf - optStaticBoundsCheck - optStyleCheck ## Check symbol for spelling consistency - optAssert - optLineDir - optWarns - optHints - optOptimizeSpeed - optOptimizeSize - optStackTrace ## stack tracing support - optStackTraceMsgs ## enable custom runtime msgs via `setFrameMsg` - optLineTrace ## line tracing support (includes stack tracing) - optByRef ## use pass by ref for objects - ## (for interfacing with C) - optProfiler ## profiler turned on - optImplicitStatic ## optimization: implicit at compile time - ## evaluation - optTrMacros ## en/disable pattern matching - optMemTracker - optSinkInference ## 'sink T' inference - optCursorInference - optImportHidden - - TOptions* = set[TOption] - type FileIndex* = distinct int32 diff --git a/compiler/ast/report_enums.nim b/compiler/ast/report_enums.nim new file mode 100644 index 00000000000..07ad4edc750 --- /dev/null +++ b/compiler/ast/report_enums.nim @@ -0,0 +1,1096 @@ +type + ReportCategory* = enum + ## Kinds of the toplevel reports. Only dispatches on report topics, + ## such as sem, parse, macro (for `echo` in compile-time code) and so + ## on. Subdivision is based on different phases of the compiler + ## operation, and not on report's state itself, as those are completely + ## orthogonal to each other (lexer might provide errors and hints, + ## parser can provide errors, hints and warnings) + + repParser = "Parser" + repLexer = "Lexer" ## Report generated by lexer - bad tokens, lines + ## that are too long etc. + + repSem = "Sem" ## Report produced directly by semantic analysis - + ## compilation errors, warnings and hints + + repCmd = "Cmd" ## Report related to execution of the external command - + ## start of the command, execution failure, succes and so on. + + repDebug = "Debug" ## Side channel for the compiler debug report. Sem + ## expansion traces and other helper messages designed specifically to + ## aid development of the compiler + + repInternal = "Internal" ## Reports constructed during hanling of the + ## internal compilation errors. Separate from debugging reports since + ## they always exist - ICE, internal fatal errors etc. + + repBackend = "Backend" ## Backend-specific reports. + + repExternal = "External" ## Report constructed during handling of the + ## external configuration, command-line flags, packages, modules. + + + ReportKind* = enum + ## Toplevel enum for different categories. Order of definitions is + ## really important - elements are first separated into categories + ## (internal reports, backend reports and so on) and can be further + ## split into severity levels. + ## + ## Different naming scheme is used for a reports with different + ## categories - this enum exists only to make it easier to work with + ## different report kinds, without having to manage seven different + ## enum types. + + repNone + + #-------------------------- Internal reports ---------------------------# + # Internal reports being + # fatal errors begin + rintUnknown ## Unknown internal report kind + rintFatal ## Explicitly fatal compiler error + + rintUnreachable ## State in the compiler code that must not be reached + rintAssert ## Failed internal assert in the compiler + + + rintIce ## Internal compilation error + # fatal end + + # errors being + rintCannotOpenFile + rintUsingLeanCompiler + rintNotUsingNimcore + rintNotImplemented + # errors end + + # warnings begin + rintWarnCannotOpenFile + rintUnexpected + rintWarnFileChanged + # warnings end + + # hints start + rintSource = "Source" ## Show source in the report + # REFACTOR this is a global configuration option, + # not a hint. + + + rintGCStats = "GCStats" ## Print GC statistics for the compiler run + rintQuitCalled = "QuitCalled" ## `quit()` called by the macro code + ## compilation error handling and similar + rintMissingStackTrace ## Stack trace would've been generated in the + ## debug compiler build + rintMsgOrigin = "MsgOrigin" + rintErrKind = "ErrKind" ## Show report kind in error messages + + rintSuccessX = "SuccessX" ## Succesfull compilation + # hints end + + rintStackTrace = "StackTrace" ## Stack trace during internal + rintNimconfWrite + rintListWarnings + rintListHints + + rintCliHelp # cli report first! + rintCliFullHelp + rintCliVersion + rintCliAdvancedUsage # cli report last! + + rintDumpState + rintEchoMessage # last ! + + # internal reports end + + #-------------------------- External reports ---------------------------# + # External reports + # errors begin + rextUnknownCCompiler + + # malformed cmdline parameters begin + rextInvalidHint + rextInvalidWarning + rextInvalidCommandLineOption ## Invalid command-line option passed to + ## the compiler + rextOnlyAllOffSupported ## Only `all:off` is supported for mass + ## hint/warning modification. Separate diagnostics must be enabled on + ## one-by-one basis. + rextExpectedOnOrOff ## Command-line option expected 'on' or 'off' value + rextExpectedOnOrOffOrList ## Command-line option expected 'on', 'off' + ## or 'list' value. + rextExpectedCmdArgument ## Command-line option expected argument + rextExpectedNoCmdArgument ## Command-line option expected no arguments + rextInvalidNumber ## Command-line switch expected a number + rextInvalidValue + rextUnexpectedValue ## Command-line argument had value, but it did not + ## match with any expected. + + rextIcUnknownFileName + rextIcNoSymbolAtPosition + + rextExpectedCbackendForRun + rextExpectedTinyCForRun + rextInvalidCommand + rextCommandMissing + rextExpectedRunOptForArgs + rextUnexpectedRunOpt + rextInvalidPath ## Invalid path for a command-line argument + + rextInvalidPackageName ## When adding packages from the `--nimbleDir` + ## (or it's default value), names are validated. This error is + ## generated if package name is not correct. + # errors end + + # warnings begin + rextDeprecated ## Report about use of the deprecated feature that is + ## not in the semantic pass. Things like deprecated flags, compiler + ## commands and so on. + # warnings end + + # hints start + rextConf = "Conf" ## Processing user configutation file + rextPath = "Path" ## Add nimble path + # hints end + + # external reports end + + #---------------------------- Lexer reports ----------------------------# + # Lexer report begin + # errors begin + rlexMalformedUnderscores + rlexMalformedTrailingUnderscre + rlexInvalidToken + rlexNoTabs + + # numbers + rlexInvalidIntegerPrefix + rlexInvalidIntegerSuffix + rlexNumberNotInRange + rlexExpectedHex + rlexInvalidIntegerLiteral + + # char + rlexInvalidCharLiteral + rlexMissingClosingApostrophe + rlexInvalidUnicodeCodepoint + + # string + rlexUnclosedTripleString + rlexUnclosedSingleString + + rlexExpectedToken + rlexCfgInvalidDirective + + # comments + rlexUnclosedComment + + # errors end + + # warnings begin + rlexDeprecatedOctalPrefix = "OctalEscape" + # warnings end + + # hints begin + rlexLineTooLong = "LineTooLong" + rlexLinterReport = "Name" + + rlexSyntaxesCode + # hints end + + # Lexer report end + + #--------------------------- Parser reports ----------------------------# + # errors begin + # regular nim parser + rparInvalidIndentation + rparNestableRequiresIndentation + + rparIdentExpected + rparIdentOrKwdExpected + rparExprExpected + rparMissingToken + rparUnexpectedToken + rparUnexpectedTokenKind + + rparFuncNotAllowed + rparTupleTypeWithPar + rparMisplacedParameterVar + rparConceptNotinType + rparRotineExpected + rparPragmaAlreadyPresent + rparMisplacedExport + + # template parser `filter_tmpl.nim` + rparTemplMissingEndClose + rparTemplInvalidExpression + + rparInvalidFilter + + # erorrs end + + # warnings begin + rparInconsistentSpacing = "Spacing" + rparEnablePreviewDotOps = "DotLikeOps" + rparPragmaNotFollowingTypeName + rparPragmaBeforeGenericParameters + # warnings end + + rparName = "Name" ## Linter report about used identifier + + #----------------------------- Sem reports -----------------------------# + # semantic fatal + rsemFatalError + # end + + # Semantic errors begin + rsemUserError = "UserError" ## `{.error: }` + rsemUsageIsError + + rsemCompilesError + + rsemCustomError + rsemCustomPrintMsgAndNodeError + ## just like custom error, prints a message and renders wrongNode + rsemTypeMismatch + rsemTypeKindMismatch + rsemAmbiguous + rsemAmbiguousIdent + + rsemCustomUserError + ## just like customer error, but reported as a errUser in msgs + + rsemNodeNotAllowed + ## Generated in `filters.nim` + + rsemCannotProveNotNil + rsemProvablyNil + + # nimsuggest + rsemSugNoSymbolAtPosition + + # Global Errors + rsemCustomGlobalError + ## just like custom error, but treat it like a "raise" and fast track the + ## "graceful" abort of this compilation run, used by `errorreporting` to + ## bridge into the existing `msgs.liMessage` and `msgs.handleError`. + + # Module errors + rsemSystemNeeds + rsemInvalidModulePath + rsemInvalidModuleName + rsemCannotImportItself + rsemRecursiveInclude + rsemRecursiveImport + rsemCannotOpenFile + rsemExportRequiresToplevel + rsemExperimentalRequiresToplevel + rsemMethodRequiresToplevel + rsemPackageRequiresToplevel + rsemConverterRequiresToplevel + rsemImportRequiresToplevel + rsemUnexpectedToplevelDefer + rsemUsingRequiresToplevel + rsemInvalidVisibility + rsemUnknownPackageName + rsemUnexpectedInfixInInclude + + # .. + rsemConflictingExportnims + rsemNoMagicEqualsForType + rsemCantConvertLiteralToType + rsemCantConvertLiteralToRange + rsemCantComputeOffsetof + rsemStaticOutOfBounds ## Error generated when semfold or static bound + ## checking sees and out-of-bounds index error. + rsemStaticFieldNotFound # TODO DOC generated in `semfold.nim`, need + # better documentation, right now I don't know what exactly this error + # means and how to reproduce it in the example code. + rsemSemfoldOverflow + rsemSemfoldDivByZero + rsemSemfoldInvalidConversion + rsemInvalidIntdefine + rsemInvalidBooldefine + + + # Type definitions + rsemCaseInUnion ## `{.union.}` type cannot use `case:` statements + rsemOffsetInUnion ## `{.union.}` type cannot use inheritance and any + ## other features that add implicit chunk of data before the actually + ## listed fields. + rsemUnexpectedInNewConcept + rsemTooNestedConcept + rsemIllegalRecursion + rsemCannotInferStaticValue + + rsemVarVarNotAllowed ## `var lent`, `var var` etc. are not allowed in + ## types + rsemInvalidOrderInEnum + rsemSetTooBig + rsemTIsNotAConcreteType + rsemProcIsNotAConcreteType + rsemRangeIsEmpty + + rsemCannotInstantiate + rsemCannotInstantiateWithParameter + rsemCannotGenerateGenericDestructor + rsemUndeclaredField + rsemInheritanceOnlyWorksWithAnEnum # I have **//ABSOLUTELY NO IDEA//** + # what this error means. I think I might need to add something like + # `rsemWTF` + rsemExpectedOrdinal + rsemExpectedOrdinalOrFloat + rsemExpectedUnholyEnum # yes + rsemExpectedLow0Discriminant + rsemExpectedHighCappedDiscriminant + rsemMissingCaseBranches + rsemRangeDoesNotSupportNan + rsemRangeRequiresDotDot + rsemExpectedRange + rsemArrayExpectsPositiveRange + rsemExpectObjectForBase + rsemExpectNonFinalForBase + + rsemTVoidNotAllowed + rsemExpectedObjectForRegion + rsemUnexpectedVoidType + rsemUnexpectedArrayAssignForCstring + rsemMacroBodyDependsOnGenericTypes + rsemMalformedNotNilType + rsemEnableNotNilExperimental + rsemEnableDotOperatorsExperimental + rsemEnableCallOperatorExperimental + rsemExpectedObjectType + rsemExpectedImportedType + rsemUnexpectedExportcInAlias + rsemExpectedDistinctForBorrow + rsemBorrowTargetNotFound + rsemConceptInferenceFailed + rsemConceptPredicateFailed + + # Procedure definition and instantiation + rsemImplementationNotAllowed + rsemImplementationExpected + rsemRedefinitionOf + rsemDefaultParamIsIncompatible + rsemDeclarationVisibilityMismatch + rsemGenericLambdaNowAllowed + rsemUnexpectedAutoInForwardDeclaration + rsemUnexpectedClosureOnToplevelProc + rsemExpectedReturnTypeForIterator + rsemExpectedReturnTypeForConverter + rsemExpectedOneArgumentForConverter + rsemIncompatibleDefaultExpr + + # Call and procedures + rsemCallTypeMismatch + rsemCallIndirectTypeMismatch + rsemCallNotAProcOrField ## unknown or semantically invalid `obj.field`, + ## `obj.call()` + rsemExpressionCannotBeCalled + rsemWrongNumberOfArguments + rsemWrongNumberOfVariables + rsemWrongNumberOfGenericParams + rsemNoGenericParamsAllowed + rsemAmbiguousCall + rsemCallingConventionMismatch + rsemHasSideEffects + rsemCantPassProcvar + rsemUnlistedRaises + rsemUnlistedEffects + rsemOverrideSafetyMismatch + rsemOverrideLockMismatch + rsemMissingMethodDispatcher + rsemNotABaseMethod + rsemIllegalCallconvCapture + rsemIllegalMemoryCapture + rsemIgnoreInvalidForLoop + rsemMissingGenericParamsForTemplate + rsemMisplacedMagicType + rsemCannotInferParameterType + rsemParameterRequiresAType + rsemParameterRedefinition + rsemInvalidExpression + rsemExpectedNonemptyPattern + + rsemTemplateInstantiationTooNested + rsemMacroInstantiationTooNested + rsemGenericInstantiationTooNested # TODO write out list of generic, + # macro or template instantiations. There is a `pushOwner` called for + # each generic instantiation - can this be reused? + + rsemCannotSpawnProcWithVar + rsemCannotSpawnMagicProc + rsemCannotDiscardSpawn + rsemSpawnRequiresCall + rsemSpawnRequiresGcSafe + rsemSpawnForbidsClosure + rsemSpawnForbidsIterator + + rsemInvalidMethodDeclarationOrder # Right now I have no idea what this + # error means exactly. It /does/ have a 'sort of' reproducible example + # - https://github.com/nim-lang/Nim/issues/5325. No real tests for this + # one of course, I mean who needs this, right? + rsemIsNotParameterOf + rsemParameterNotPointerToPartial + + # Statements + rsemDiscardingVoid + rsemDiscardingProc + rsemInvalidControlFlow + rsemContinueCannotHaveLabel + rsemUseOrDiscard + rsemUseOrDiscardExpr + rsemCannotBeRaised + rsemCannotRaiseNonException + rsemExceptionAlreadyHandled + rsemCannotExceptNativeAndImported + rsemExpectedSingleFinally + rsemExpectedSingleGeneralExcept + rsemCannotConvertToRange + rsemUsingRequiresType + rsemUsingDisallowsAssign + rsemDifferentTypeForReintroducedSymbol + rsemImplicitFieldConstructinoRequiresPartial + rsemCannotInferTypeOfLiteral + rsemCannotInferTypeOfParameter + rsemProcHasNoConcreteType + rsemThreadvarCannotInit + rsemLetNeedsInit + rsemConstExpressionExpected + rsemFieldsIteratorCannotContinue + rsemParallelFieldsDisallowsCase + rsemNoObjectOrTupleType + rsemForExpectsIterator + rsemSelectorMustBeOfCertainTypes + rsemTypeCannotBeForwarded + rsemDoubleCompletionOf + rsemExpectedInvariantParam + rsemCovariantUsedAsNonCovariant + rsemContravariantUsedAsNonCovariant + rsemNonInvariantCannotBeUsedWith + rsemNonInvariantCnnnotBeUsedInConcepts + rsemIncorrectResultProcSymbol + rsemRebidingImplicitDestructor + rsemRebidingDestructor + rsemRebidingDeepCopy + rsemInseparableTypeBoundOp + rsemUnexpectedTypeBoundOpSignature + rsemExpectedDestroyOrDeepCopyForOverride + rsemExpectedObjectForMethod + rsemUnexpectedPragmaInDefinitionOf + rsemMisplacedRunnableExample + + # Expressions + rsemConstantOfTypeHasNoValue + rsemTypeConversionArgumentMismatch + rsemUnexpectedEqInObjectConstructor + rsemIllegalConversion + rsemCannotBeConvertedTo + rsemCannotCastToNonConcrete + rsemCannotCastTypes + rsemExpectedTypeOrValue + rsemInvalidArgumentFor + rsemNoTupleTypeForConstructor + rsemInvalidTupleConstructor + rsemUnknownIdentifier + rsemIndexOutOfBounds + rsemInvalidOrderInArrayConstructor + rsemVarForOutParamNeeded + rsemStackEscape + rsemExprHasNoAddress + rsemUnknownTrait + rsemStringOrIdentNodeExpected + rsemExpectedObjectForOf + rsemCannotBeOfSubtype + rsemQuantifierInRangeExpected + rsemOldTakesParameterName + rsemOldDoesNotBelongTo + rsemCannotFindPlugin + rsemExpectedProcReferenceForFinalizer + rsemCannotIsolate + rsemCannotInterpretNode + rsemRecursiveDependencyIterator + rsemIllegalNimvmContext + rsemDisallowedNilDeref + rsemInvalidTupleSubscript + rsemLocalEscapesStackFrame + rsemImplicitAddrIsNotFirstParam + rsemExpectedOwnerReturn + rsemExpectedUnownedRef + rsemCannotAssignTo + rsemNoReturnTypeDeclared + rsemReturnNotAllowed + rsemCannotInferReturnType + rsemExpectedValueForYield + rsemUnexpectedYield + rsemCannotReturnTypeless + rsemExpectedMacroOrTemplate + rsemAmbiguousGetAst + rsemExpectedTemplateWithNArgs + rsemExpectedCallForGetAst + rsemWrongNumberOfQuoteArguments + rsemEnableExperimentalParallel + rsemExpectedExpressionForSpawn + rsemNamedExprExpected + rsemNamedExprNotAllowed + rsemFieldInitTwice + rsemDisallowedTypedescForTupleField + rsemDisjointFields + rsemUnsafeRuntimeDiscriminantInit + rsemConflictingDiscriminantInit + rsemConflictingDiscriminantValues + rsemRuntimeDiscriminantInitCap + rsemRuntimeDiscriminantMustBeImmutable + rsemRuntimeDiscriminantRequiresElif + rsemObjectRequiresFieldInit + rsemObjectRequiresFieldInitNoDefault + rsemDistinctDoesNotHaveDefaultValue + rsemExpectedModuleNameForImportExcept + rsemCannotExport + rsemCannotMixTypesAndValuesInTuple + rsemExpectedTypelessDeferBody + rsemInvalidBindContext + rsemCannotCreateImplicitOpenarray + rsemCannotAssignToDiscriminantWithCustomDestructor + rsemUnavailableTypeBound + + rsemParallelInvalidControlFlow + rsemParallelCannotProveDisjoint + rsemParallelCounterAfterIncrement + rsemParallelWithoutSpawn + rsemSpawnInvalidContext + + # Identifier Lookup + rsemUndeclaredIdentifier + rsemExpectedIdentifier + rsemExpectedIdentifierInExpr + + # Object and Object Construction + rsemFieldNotAccessible + ## object field is not accessible + rsemFieldAssignmentInvalid + ## object field assignment invalid syntax + rsemFieldOkButAssignedValueInvalid + ## object field assignment, where the field name is ok, but value is not + rsemObjectConstructorIncorrect + ## one or more issues encountered with object constructor + + # General Type Checks + rsemExpressionHasNoType + ## an expression has not type or is ambiguous + + rsemRawTypeMismatch + + rsemCannotConvertTypes + rsemUnresolvedGenericParameter + rsemCannotCreateFlowVarOfType + rsemTypeNotAllowed + + # Literals + rsemIntLiteralExpected + ## int literal node was expected, but got something else + rsemStringLiteralExpected + ## string literal node was expected, but got something else + + rsemOnOrOffExpected + rsemCallconvExpected + rsemInnerCodeReordering + rsemUnknownExperimental + rsemDuplicateCaseLabel + + # view types + rsemExpressionIsNotAPath + rsemResultMustBorrowFirst + rsemCannotDetermineBorrowTarget # TODO DOC need better explanation for + # reasons of this error, right now it looks like a hacked-in check. + rsemCannotBorrow + rsemBorrowOutlivesSource + rsemImmutableBorrowMutation + + # VM + rsemVmOpcParseExpectedExpression + rsemTooManyRegistersRequired + rsemVmCannotFindBreakTarget + rsemVmNotUnused + rsemNotAFieldSymbol + rsemVmTooLargetOffset + rsemVmUnhandledException + rsemVmCannotGenerateCode + rsemVmCannotCast + rsemVmGlobalError ## Error report that was declared as 'global' in the + ## VM - with current 'globalError-is-a-control-flow-mechanism' approach + ## this report is largely meaningless, and used only to raise exception. + rsemVmInvalidBindSym + rsemVmBadExpandToAst + rsemVmCannotEvaluateAtComptime + rsemVmCannotImportc + rsemVmEnableFFIToImportc + rsemVmCannotCreateNullElement + rsemVmInvalidObjectConstructor + rsemVmNoClosureIterators + rsemVmCannotCallMethod + rsemVmCallingNonRoutine + rsemVmCannotModifyTypechecked + rsemVmNilAccess + rsemVmDerefUnsupportedPtr + rsemVmErrInternal + rsemVmIndexError + rsemVmOutOfRange + rsemVmOverOrUnderflow + rsemVmDivisionByConstZero + rsemVmNodeNotASymbol + rsemVmNodeNotAProcSymbol + rsemVmNodeNotAFieldSymbol + rsemVmIllegalConv + rsemVmMissingCacheKey + rsemVmCacheKeyAlreadyExists + rsemVmFieldNotFound + rsemVmFieldInavailable + rsemVmCannotSetChild + rsemVmCannotAddChild + rsemVmCannotGetChild + rsemVmNoType + rsemVmNotAField + + rsemVmTooManyIterations + + rsemMissingImportcCompleteStruct + + rsemCyclicTree + rsemCyclicDependency + rsemConstExprExpected + + # Codegen + rsemRttiRequestForIncompleteObject + rsemExpectedNimcallProc + rsemExpectedExhaustiveCaseForComputedGoto + rsemExpectedUnholyEnumForComputedGoto + rsemTooManyEntriesForComputedGoto + rsemExpectedLow0ForComputedGoto + rsemExpectedCaseForComputedGoto + rsemDisallowedRangeForComputedGoto + rsemExpectedCallForCxxPattern + rsemExpectedParameterForCxxPattern + rsemExpectedLiteralForGoto + rsemRequiresDeepCopyEnabled + rsemDisallowedOfForPureObjects + rsemDisallowedReprForNewruntime + rsemCannotCodegenCompiletimeProc + + # Pragma + rsemInvalidPragma + ## suplied pragma is invalid + rsemCannotAttachPragma + rsemUnexpectedPragma + rsemPropositionExpected + rsemIllegalCustomPragma + ## supplied pragma is not a legal custom pragma, and cannot be attached + rsemNoReturnHasReturn + ## a routine marked as no return, has a return type + rsemImplicitPragmaError + ## a symbol encountered an error when processing implicit pragmas, this + ## should be applied to symbols and treated as a wrapper for the purposes + ## of reporting. the original symbol is stored as the first argument + rsemPragmaDynlibRequiresExportc + ## much the same as `ImplicitPragmaError`, except it's a special case + ## where dynlib pragma requires an importc pragma to exist on the same + ## symbol + ## xxx: pragmas shouldn't require each other, that's just bad design + + rsemWrappedError + ## there is no meaningful error to construct, but there is an error + ## further down the AST that invalidates the whole + + rsemSymbolKindMismatch + rsemIllformedAst + rsemInitHereNotAllowed + rsemIdentExpectedInExpr + rsemTypeExpected + rsemGenericTypeExpected + rsemTypeInvalid + rsemWrongIdent + rsemPragmaOptionExpected + rsemUnexpectedPushArgument + rsemCannotPushCast + rsemCastRequiresStatement + rsemExportcppRequiresCpp + rsemDynlibRequiresExportc + rsemImportjsRequiresJs + rsemImportjsRequiresPattern + rsemBitsizeRequires1248 + rsemBitsizeRequiresPositive + rsemAlignRequiresPowerOfTwo + rsemPragmaRecursiveDependency + rsemMisplacedDeprecation + rsemNoUnionForJs + + rsemThisPragmaRequires01Args + rsemMismatchedPopPush + rsemExcessiveCompilePragmaArgs + rsemLinePragmaExpectsTuple + rsemRaisesPragmaExpectsObject + + # -- locking + rsemLocksPragmaExpectsList + rsemLocksPragmaBadLevel + rsemLocksRequiresArgs + rsemMultilockRequiresSameLevel + rsemInvalidNestedLocking + rsemUnguardedAccess + rsemInvalidGuardField + + rsemDrNimRequiresUsesMissingResult + rsemDrnimCannotProveLeq + rsemDrnimCannotPorveGe + + rsemErrGcUnsafeListing + rsemBorrowPragmaNonDot + rsemInvalidExtern + rsemInvalidPragmaBlock + rsemBadDeprecatedArgs + rsemMisplacedEffectsOf + rsemMissingPragmaArg + rsemErrGcUnsafe + rsemEmptyAsm + + + # end + + # Semantic warnings begin + rsemUserWarning = "User" ## `{.warning: }` + rsemUnknownMagic = "UnknownMagic" + rsemUnusedImport = "UnusedImport" + rsemDeprecated = "Deprecated" + rsemLockLevelMismatch = "LockLevel" + rsemTypelessParam = "TypelessParam" + + rsemWarnUnlistedRaises = "Effect" ## `sempass2.checkRaisesSpec` had + ## `emitWarnings: bool` parameter which was supposedly used to control + ## whether `strictEffects` warnings actually generated an error, or + ## just a warning. But all four uses of this proc had constant `false` + ## written to this field, so for now it does not mean anything and all + ## mismatched raises are routed as errors. + + rsemDotForModuleImport + rsemReorderingFail + rsemProveField = "ProveField" + rsemStrictNotNilExpr = "StrictNotNil" + rsemStrictNotNilResult = "StrictNotNil" + rsemWarnGcUnsafe = "GcUnsafe" + rsemWarnGcUnsafeListing = "GcUnsafe2" + rsemProveInit = "ProveInit" + rsemUninit = "Uninit" + rsemWarnUnsafeCode = "UnsafeCode" + rsemImplicitCstringConvert = "CStringConv" + rsemHoleEnumConvert = "HoleEnumConv" + rsemAnyEnumConvert = "AnyEnumConv" + rsemMethodLockMismatch + rsemUseBase = "UseBase" + rsemUnreachableElse = "UnreachableElse" + rsemUnreachableCode = "UnreachableCode" + rsemInheritFromException = "InheritFromException" + rsemPtrRegionIsDeprecated + rsemTypedReturnDeprecated + rsemEachIdentIsTuple = "EachIdentIsTuple" + rsemResultShadowed = "ResultShadowed" + rsemResultUsed = "ResultUsed" + rsemGenericMethodsDeprecated + rsemSuspiciousEnumConv = "EnumConv" + rsemUnsafeSetLen = "UnsafeSetLen" + rsemUnsafeDefault = "UnsafeDefault" + rsemBindDeprecated + rsemUncollectableRefCycle = "CycleCreated" + rsemParallelWarnCannotProve + rsemParallelWarnCanProve + rsemParallelWarnNotDisjoint + rsemObservableStores = "ObservableStores" + rsemCaseTransition = "CaseTransition" + rsemUseOfGc = "GcMem" # last ! + # end + + # trace + rsemVmStackTrace + # trace + + # Semantic hints begin + rsemUserHint = "User" ## `{.hint: .}` pragma encountereed + rsemLinterReport = "Name" + rsemLinterReportUse = "Name" + rsemHintLibDependency + rsemXDeclaredButNotUsed = "XDeclaredButNotUsed" + rsemDuplicateModuleImport = "DuplicateModuleImport" + rsemXCannotRaiseY = "XCannotRaiseY" + rsemConvToBaseNotNeeded = "ConvToBaseNotNeeded" + rsemConvFromXtoItselfNotNeeded = "ConvFromXtoItselfNotNeeded" + + rsemProcessing = "Processing" ## Processing module + rsemProcessingStmt = "ProcessingStmt" ## Processing toplevel statement + + rsemExprAlwaysX = "ExprAlwaysX" ## Expression always evaluates to "X" + rsemConditionAlwaysTrue = "CondTrue" ## Condition is always true + rsemConditionAlwaysFalse = "CondFalse" ## Condition is always false + + rsemPattern = "Pattern" ## Term rewriting pattern has been triggered + rsemCannotMakeSink ## Argument could not be turned into a sink + ## parameter. Generated once in the whole compiler + ## `sinkparameter_inference.nim` + rsemCopiesToSink ## Passing data to the `sink` parameter still copies + ## due to control flow in the code + + rsemGlobalVar = "GlobalVar" ## Track global variable declarations? + + rsemEffectsListingHint + rsemExpandMacro = "ExpandMacro" ## Trace macro expansion progress + rsemExpandArc = "ExpandArc" + + rsemCompilesReport + rsemNonMatchingCandidates + rsemUserRaw = "UserRaw" # REVIEW - Used in + # `semcall.semOverloadedCall()` and `extccomp.getCompileCFileCmd()`. + # Seems like this one should be removed, it spans multiple compiler + # subsystems. Can't understand what it is doing. + + rsemExtendedContext = "ExtendedContext" ## Extended contextual + ## information. Used in `ccgstmts.genStmts()` and + ## `semexprs.semExprNoType()` + rsemImplicitObjConv = "ImplicitObjConv" + # end + + + #------------------------ Command report kinds -------------------------# + # errors + rcmdFailedExecution + # errors end + + # hints + rcmdCompiling = "CC" + rcmdLinking = "Link" + rcmdExecuting = "Exec" + rcmdRunnableExamplesSuccess + # hints end + + + #---------------------------- Debug reports ----------------------------# + rdbgVmExecTraceFull + rdbgVmExecTraceMinimal + rdbgVmCodeListing + + rdbgTraceDefined # first ! tracer begin + rdbgTraceUndefined + rdbgTraceStart + rdbgTraceStep + rdbgTraceLine + rdbgTraceEnd # last ! tracer end + + rdbgStartingConfRead + rdbgFinishedConfRead + rdbgCfgTrace + + rdbgOptionsPush + rdbgOptionsPop + + #--------------------------- Backend reports ---------------------------# + # errors start + rbackCannotWriteScript ## Cannot write build script to a cache file + rbackCannotWriteMappingFile ## Canot write module compilation mapping + ## file to cache directory + rbackTargetNotSupported ## C compiler does not support requested target + rbackJsTooCaseTooLarge + rbackJsUnsupportedClosureIter + rbackJsonScriptMismatch # ??? used in `extccomp.nim`, TODO figure out + # what the original mesage was responsible for exactly + + rbackRstCannotOpenFile + rbackRstExpected + rbackRstGridTableNotImplemented + rbackRstMarkdownIllformedTable + rbackRstNewSectionExpected + rbackRstGeneralParseError + rbackRstInvalidDirective + rbackRstInvalidField + rbackRstFootnoteMismatch + + rbackCannotProduceAssembly + # errors end + + # warnings start + rbackRstTestUnsupported + rbackRstRedefinitionOfLabel = "RedefinitionOfLabel" + rbackRstUnknownSubstitution = "UnknownSubstitutionX" + rbackRstBrokenLink = "BrokenLink" + rbackRstUnsupportedLanguage = "LanguageXNotSupported" + rbackRstUnsupportedField = "FieldXNotSupported" + rbackRstRstStyle = "warnRstStyle" + + # warnings end + + # hints start + rbackProducedAssembly + rbackCompiling = "Compiling" + rbackLinking = "Link" + # hints end + + ReportKinds* = set[ReportKind] + + +const rstWarnings* = {rbackRstTestUnsupported .. rbackRstRstStyle} + +type + LexerReportKind* = range[rlexMalformedUnderscores .. rlexSyntaxesCode] + ParserReportKind* = range[rparInvalidIndentation .. rparName] + + SemReportKind* = range[rsemFatalError .. rsemImplicitObjConv] + SemReportErrorKind* = range[rsemUserError .. rsemWrappedError] + + CmdReportKind* = range[rcmdFailedExecution .. rcmdRunnableExamplesSuccess] + + DebugReportKind* = range[rdbgVmExecTraceFull .. rdbgOptionsPop] + + BackendReportKind* = range[rbackCannotWriteScript .. rbackLinking] + + ExternalReportKind* = range[rextUnknownCCompiler .. rextPath] + + InternalReportKind* = range[rintUnknown .. rintEchoMessage] + + +const + #-------------------------------- lexer --------------------------------# + repLexerKinds* = {low(LexerReportKind) .. high(LexerReportKind)} + rlexHintKinds* = {rlexLineTooLong .. rlexSyntaxesCode} + rlexWarningKinds* = {rlexDeprecatedOctalPrefix .. rlexDeprecatedOctalPrefix} + rlexErrorKinds* = {rlexMalformedUnderscores .. rlexUnclosedComment} + + + #------------------------------- parser --------------------------------# + repParserKinds* = {low(ParserReportKind) .. high(ParserReportKind)} + rparHintKinds* = {rparName} + rparErrorKinds* = {rparInvalidIndentation .. rparInvalidFilter} + rparWarningKinds* = { + rparInconsistentSpacing .. rparPragmaBeforeGenericParameters} + + #--------------------------------- sem ---------------------------------# + repSemKinds* = {low(SemReportKind) .. high(SemReportKind)} + rsemErrorKinds* = {rsemUserError .. rsemEmptyAsm} + rsemWarningKinds* = {rsemUserWarning .. rsemUseOfGc} + rsemHintKinds* = {rsemUserHint .. rsemImplicitObjConv} + + # Separated into standalone set to reuse in the `options.severity` + # checking - `--styleCheck=error` is set up as a global option. + repLinterKinds* = {rlexLinterReport, rsemLinterReport, rsemLinterReportUse} + + # `--experimental=strictNotNil` and `{.experimental: "strictNotNil".}` + repNilcheckKinds* = {rsemStrictNotNilExpr, rsemStrictNotNilResult} + + #--------------------------------- cmd ---------------------------------# + repCmdKinds* = {low(CmdReportKind) .. high(CmdReportKind)} + rcmdErrorKinds* = {rcmdFailedExecution} + rcmdWarningKinds* = default(set[ReportKind]) + rcmdHintKinds* = {rcmdCompiling .. rcmdRunnableExamplesSuccess} + + #-------------------------------- debug --------------------------------# + repDebugKinds* = {low(DebugReportKind) .. high(DebugReportKind)} + + #------------------------------- backend -------------------------------# + repBackendKinds* = {low(BackendReportKind) .. high(BackendReportKind)} + rbackErrorKinds* = {rbackCannotWriteScript .. rbackCannotProduceAssembly} + rbackWarningKinds* = {rbackRstTestUnsupported .. rbackRstRstStyle} + rbackHintKinds* = {rbackProducedAssembly .. rbackLinking} + + #------------------------------ external -------------------------------# + repExternalKinds* = {low(ExternalReportKind) .. high(ExternalReportKind)} + rextErrorKinds* = {rextUnknownCCompiler .. rextInvalidPackageName} + rextWarningKinds* = {rextDeprecated} + rextHintKinds* = {rextConf .. rextPath} + + + #------------------------------ internal -------------------------------# + repInternalKinds*: ReportKinds = { + low(InternalReportKind) .. high(InternalReportKind)} + + rintFatalKinds* = {rintUnknown .. rintIce} ## Fatal internal compilation + ## reports + rintErrorKinds* = {rintCannotOpenFile .. rintNotImplemented} + rintWarningKinds* = {rintWarnCannotOpenFile .. rintWarnFileChanged} + rintHintKinds* = {rintSource .. rintSuccessX} + rintDataPassKinds* = {rintStackTrace .. rintEchoMessage} + rintCliKinds* = {rintCliHelp .. rintCliAdvancedUsage} + + +const + repWarningKinds*: ReportKinds = + rsemWarningKinds + + rlexWarningKinds + + rparWarningKinds + + rbackWarningKinds + + rextWarningKinds + + rcmdWarningKinds + + rintWarningKinds + + repTraceKinds*: ReportKinds = {rsemVmStackTrace, rintStackTrace} + + repHintKinds*: ReportKinds = + rsemHintKinds + + rlexHintKinds + + rparHintKinds + + rbackHintKinds + + rextHintKinds + + rcmdHintKinds + + rintHintKinds + + repErrorKinds*: ReportKinds = + rsemErrorKinds + + rlexErrorKinds + + rparErrorKinds + + rbackErrorKinds + + rextErrorKinds + + rcmdErrorKinds + + rintErrorKinds + + repFatalKinds*: ReportKinds = rintFatalKinds + repAllKinds* = {low(ReportKind) .. high(ReportKind)} + + + +const + rsemReportTwoSym* = { + rsemConflictingExportnims, + rsemBorrowOutlivesSource, + rsemImmutableBorrowMutation, + rsemRedefinitionOf, + rsemInvalidMethodDeclarationOrder, # [s, witness] + rsemIllegalCallconvCapture, # [symbol, owner] + rsemDeprecated # [symbol, use-instead] + } + + rsemReportOneSym* = { + rsemUnexpectedPragmaInDefinitionOf, + rsemDoubleCompletionOf, + + rsemIllegalMemoryCapture, + rsemOverrideSafetyMismatch, + rsemOverrideLockMismatch + } + + rsemReportListSym* = { + rsemAmbiguous, + rsemAmbiguousIdent, + rsemObjectRequiresFieldInit, + rsemObjectRequiresFieldInitNoDefault + } + + rsemReportCountMismatch* = { + rsemWrongNumberOfArguments, + rsemWrongNumberOfGenericParams, + rsemInvalidOrderInEnum, + rsemSetTooBig, + rsemArrayExpectsPositiveRange, + rsemExpectedLow0Discriminant, + rsemInvalidOrderInArrayConstructor, + rsemTypeConversionArgumentMismatch, + rsemInvalidTupleSubscript, + rsemExpectedTemplateWithNArgs, + rsemExpectedParameterForCxxPattern, + rsemWrongNumberOfQuoteArguments, + rsemIndexOutOfBounds, + rsemExpectedHighCappedDiscriminant + } diff --git a/compiler/ast/reports.nim b/compiler/ast/reports.nim index 8a32d1472e4..13f4536e6cf 100644 --- a/compiler/ast/reports.nim +++ b/compiler/ast/reports.nim @@ -29,944 +29,13 @@ export options.Option, int128.toInt128 + +from front/in_options import TOption, TOptions type InstantiationInfo* = typeof(instantiationInfo()) +import report_enums +export report_enums -type - ReportCategory* = enum - ## Kinds of the toplevel reports. Only dispatches on report topics, - ## such as sem, parse, macro (for `echo` in compile-time code) and so - ## on. Subdivision is based on different phases of the compiler - ## operation, and not on report's state itself, as those are completely - ## orthogonal to each other (lexer might provide errors and hints, - ## parser can provide errors, hints and warnings) - - repParser = "Parser" - repLexer = "Lexer" ## Report generated by lexer - bad tokens, lines - ## that are too long etc. - - repSem = "Sem" ## Report produced directly by semantic analysis - - ## compilation errors, warnings and hints - - repCmd = "Cmd" ## Report related to execution of the external command - - ## start of the command, execution failure, succes and so on. - - repDebug = "Debug" ## Side channel for the compiler debug report. Sem - ## expansion traces and other helper messages designed specifically to - ## aid development of the compiler - - repInternal = "Internal" ## Reports constructed during hanling of the - ## internal compilation errors. Separate from debugging reports since - ## they always exist - ICE, internal fatal errors etc. - - repBackend = "Backend" ## Backend-specific reports. - - repExternal = "External" ## Report constructed during handling of the - ## external configuration, command-line flags, packages, modules. - - - ReportKind* = enum - ## Toplevel enum for different categories. Order of definitions is - ## really important - elements are first separated into categories - ## (internal reports, backend reports and so on) and can be further - ## split into severity levels. - ## - ## Different naming scheme is used for a reports with different - ## categories - this enum exists only to make it easier to work with - ## different report kinds, without having to manage seven different - ## enum types. - - repNone - - #-------------------------- Internal reports ---------------------------# - # Internal reports being - # fatal errors begin - rintUnknown ## Unknown internal report kind - rintFatal ## Explicitly fatal compiler error - - rintUnreachable ## State in the compiler code that must not be reached - rintAssert ## Failed internal assert in the compiler - - - rintIce ## Internal compilation error - # fatal end - - # errors being - rintCannotOpenFile - rintUsingLeanCompiler - rintNotUsingNimcore - rintNotImplemented - # errors end - - # warnings begin - rintWarnCannotOpenFile - rintUnexpected - rintWarnFileChanged - # warnings end - - # hints start - rintSource = "Source" ## Show source in the report - # REFACTOR this is a global configuration option, - # not a hint. - - - rintGCStats = "GCStats" ## Print GC statistics for the compiler run - rintQuitCalled = "QuitCalled" ## `quit()` called by the macro code - ## compilation error handling and similar - rintMissingStackTrace ## Stack trace would've been generated in the - ## debug compiler build - rintMsgOrigin = "MsgOrigin" - rintErrKind = "ErrKind" ## Show report kind in error messages - - rintSuccessX = "SuccessX" ## Succesfull compilation - # hints end - - rintStackTrace = "StackTrace" ## Stack trace during internal - rintNimconfWrite - rintListWarnings - rintListHints - - rintCliHelp # cli report first! - rintCliFullHelp - rintCliVersion - rintCliAdvancedUsage # cli report last! - - rintDumpState - rintEchoMessage # last ! - - # internal reports end - - #-------------------------- External reports ---------------------------# - # External reports - # errors begin - rextUnknownCCompiler - - # malformed cmdline parameters begin - rextInvalidHint - rextInvalidWarning - rextInvalidCommandLineOption ## Invalid command-line option passed to - ## the compiler - rextOnlyAllOffSupported ## Only `all:off` is supported for mass - ## hint/warning modification. Separate diagnostics must be enabled on - ## one-by-one basis. - rextExpectedOnOrOff ## Command-line option expected 'on' or 'off' value - rextExpectedOnOrOffOrList ## Command-line option expected 'on', 'off' - ## or 'list' value. - rextExpectedCmdArgument ## Command-line option expected argument - rextExpectedNoCmdArgument ## Command-line option expected no arguments - rextInvalidNumber ## Command-line switch expected a number - rextInvalidValue - rextUnexpectedValue ## Command-line argument had value, but it did not - ## match with any expected. - - rextIcUnknownFileName - rextIcNoSymbolAtPosition - - rextExpectedCbackendForRun - rextExpectedTinyCForRun - rextInvalidCommand - rextCommandMissing - rextExpectedRunOptForArgs - rextUnexpectedRunOpt - rextInvalidPath ## Invalid path for a command-line argument - - rextInvalidPackageName ## When adding packages from the `--nimbleDir` - ## (or it's default value), names are validated. This error is - ## generated if package name is not correct. - # errors end - - # warnings begin - rextDeprecated ## Report about use of the deprecated feature that is - ## not in the semantic pass. Things like deprecated flags, compiler - ## commands and so on. - # warnings end - - # hints start - rextConf = "Conf" ## Processing user configutation file - rextPath = "Path" ## Add nimble path - # hints end - - # external reports end - - #---------------------------- Lexer reports ----------------------------# - # Lexer report begin - # errors begin - rlexMalformedUnderscores - rlexMalformedTrailingUnderscre - rlexInvalidToken - rlexNoTabs - - # numbers - rlexInvalidIntegerPrefix - rlexInvalidIntegerSuffix - rlexNumberNotInRange - rlexExpectedHex - rlexInvalidIntegerLiteral - - # char - rlexInvalidCharLiteral - rlexMissingClosingApostrophe - rlexInvalidUnicodeCodepoint - - # string - rlexUnclosedTripleString - rlexUnclosedSingleString - - rlexExpectedToken - rlexCfgInvalidDirective - - # comments - rlexUnclosedComment - - # errors end - - # warnings begin - rlexDeprecatedOctalPrefix = "OctalEscape" - # warnings end - - # hints begin - rlexLineTooLong = "LineTooLong" - rlexLinterReport = "Name" - - rlexSyntaxesCode - # hints end - - # Lexer report end - - #--------------------------- Parser reports ----------------------------# - # errors begin - # regular nim parser - rparInvalidIndentation - rparNestableRequiresIndentation - - rparIdentExpected - rparIdentOrKwdExpected - rparExprExpected - rparMissingToken - rparUnexpectedToken - rparUnexpectedTokenKind - - rparFuncNotAllowed - rparTupleTypeWithPar - rparMisplacedParameterVar - rparConceptNotinType - rparRotineExpected - rparPragmaAlreadyPresent - rparMisplacedExport - - # template parser `filter_tmpl.nim` - rparTemplMissingEndClose - rparTemplInvalidExpression - - rparInvalidFilter - - # erorrs end - - # warnings begin - rparInconsistentSpacing = "Spacing" - rparEnablePreviewDotOps = "DotLikeOps" - rparPragmaNotFollowingTypeName - rparPragmaBeforeGenericParameters - # warnings end - - rparName = "Name" ## Linter report about used identifier - - #----------------------------- Sem reports -----------------------------# - # semantic fatal - rsemFatalError - # end - - # Semantic errors begin - rsemUserError = "UserError" ## `{.error: }` - rsemUsageIsError - - rsemCompilesError - - rsemCustomError - rsemCustomPrintMsgAndNodeError - ## just like custom error, prints a message and renders wrongNode - rsemTypeMismatch - rsemTypeKindMismatch - rsemAmbiguous - rsemAmbiguousIdent - - rsemCustomUserError - ## just like customer error, but reported as a errUser in msgs - - rsemNodeNotAllowed - ## Generated in `filters.nim` - - rsemCannotProveNotNil - rsemProvablyNil - - # nimsuggest - rsemSugNoSymbolAtPosition - - # Global Errors - rsemCustomGlobalError - ## just like custom error, but treat it like a "raise" and fast track the - ## "graceful" abort of this compilation run, used by `errorreporting` to - ## bridge into the existing `msgs.liMessage` and `msgs.handleError`. - - # Module errors - rsemSystemNeeds - rsemInvalidModulePath - rsemInvalidModuleName - rsemCannotImportItself - rsemRecursiveInclude - rsemRecursiveImport - rsemCannotOpenFile - rsemExportRequiresToplevel - rsemExperimentalRequiresToplevel - rsemMethodRequiresToplevel - rsemPackageRequiresToplevel - rsemConverterRequiresToplevel - rsemImportRequiresToplevel - rsemUnexpectedToplevelDefer - rsemUsingRequiresToplevel - rsemInvalidVisibility - rsemUnknownPackageName - rsemUnexpectedInfixInInclude - - # .. - rsemConflictingExportnims - rsemNoMagicEqualsForType - rsemCantConvertLiteralToType - rsemCantConvertLiteralToRange - rsemCantComputeOffsetof - rsemStaticOutOfBounds ## Error generated when semfold or static bound - ## checking sees and out-of-bounds index error. - rsemStaticFieldNotFound # TODO DOC generated in `semfold.nim`, need - # better documentation, right now I don't know what exactly this error - # means and how to reproduce it in the example code. - rsemSemfoldOverflow - rsemSemfoldDivByZero - rsemSemfoldInvalidConversion - rsemInvalidIntdefine - rsemInvalidBooldefine - - - # Type definitions - rsemCaseInUnion ## `{.union.}` type cannot use `case:` statements - rsemOffsetInUnion ## `{.union.}` type cannot use inheritance and any - ## other features that add implicit chunk of data before the actually - ## listed fields. - rsemUnexpectedInNewConcept - rsemTooNestedConcept - rsemIllegalRecursion - rsemCannotInferStaticValue - - rsemVarVarNotAllowed ## `var lent`, `var var` etc. are not allowed in - ## types - rsemInvalidOrderInEnum - rsemSetTooBig - rsemTIsNotAConcreteType - rsemProcIsNotAConcreteType - rsemRangeIsEmpty - - rsemCannotInstantiate - rsemCannotInstantiateWithParameter - rsemCannotGenerateGenericDestructor - rsemUndeclaredField - rsemInheritanceOnlyWorksWithAnEnum # I have **//ABSOLUTELY NO IDEA//** - # what this error means. I think I might need to add something like - # `rsemWTF` - rsemExpectedOrdinal - rsemExpectedOrdinalOrFloat - rsemExpectedUnholyEnum # yes - rsemExpectedLow0Discriminant - rsemExpectedHighCappedDiscriminant - rsemMissingCaseBranches - rsemRangeDoesNotSupportNan - rsemRangeRequiresDotDot - rsemExpectedRange - rsemArrayExpectsPositiveRange - rsemExpectObjectForBase - rsemExpectNonFinalForBase - - rsemTVoidNotAllowed - rsemExpectedObjectForRegion - rsemUnexpectedVoidType - rsemUnexpectedArrayAssignForCstring - rsemMacroBodyDependsOnGenericTypes - rsemMalformedNotNilType - rsemEnableNotNilExperimental - rsemEnableDotOperatorsExperimental - rsemEnableCallOperatorExperimental - rsemExpectedObjectType - rsemExpectedImportedType - rsemUnexpectedExportcInAlias - rsemExpectedDistinctForBorrow - rsemBorrowTargetNotFound - rsemConceptInferenceFailed - rsemConceptPredicateFailed - - # Procedure definition and instantiation - rsemImplementationNotAllowed - rsemImplementationExpected - rsemRedefinitionOf - rsemDefaultParamIsIncompatible - rsemDeclarationVisibilityMismatch - rsemGenericLambdaNowAllowed - rsemUnexpectedAutoInForwardDeclaration - rsemUnexpectedClosureOnToplevelProc - rsemExpectedReturnTypeForIterator - rsemExpectedReturnTypeForConverter - rsemExpectedOneArgumentForConverter - rsemIncompatibleDefaultExpr - - # Call and procedures - rsemCallTypeMismatch - rsemCallIndirectTypeMismatch - rsemCallNotAProcOrField ## unknown or semantically invalid `obj.field`, - ## `obj.call()` - rsemExpressionCannotBeCalled - rsemWrongNumberOfArguments - rsemWrongNumberOfVariables - rsemWrongNumberOfGenericParams - rsemNoGenericParamsAllowed - rsemAmbiguousCall - rsemCallingConventionMismatch - rsemHasSideEffects - rsemCantPassProcvar - rsemUnlistedRaises - rsemUnlistedEffects - rsemOverrideSafetyMismatch - rsemOverrideLockMismatch - rsemMissingMethodDispatcher - rsemNotABaseMethod - rsemIllegalCallconvCapture - rsemIllegalMemoryCapture - rsemIgnoreInvalidForLoop - rsemMissingGenericParamsForTemplate - rsemMisplacedMagicType - rsemCannotInferParameterType - rsemParameterRequiresAType - rsemParameterRedefinition - rsemInvalidExpression - rsemExpectedNonemptyPattern - - rsemTemplateInstantiationTooNested - rsemMacroInstantiationTooNested - rsemGenericInstantiationTooNested # TODO write out list of generic, - # macro or template instantiations. There is a `pushOwner` called for - # each generic instantiation - can this be reused? - - rsemCannotSpawnProcWithVar - rsemCannotSpawnMagicProc - rsemCannotDiscardSpawn - rsemSpawnRequiresCall - rsemSpawnRequiresGcSafe - rsemSpawnForbidsClosure - rsemSpawnForbidsIterator - - rsemInvalidMethodDeclarationOrder # Right now I have no idea what this - # error means exactly. It /does/ have a 'sort of' reproducible example - # - https://github.com/nim-lang/Nim/issues/5325. No real tests for this - # one of course, I mean who needs this, right? - rsemIsNotParameterOf - rsemParameterNotPointerToPartial - - # Statements - rsemDiscardingVoid - rsemDiscardingProc - rsemInvalidControlFlow - rsemContinueCannotHaveLabel - rsemUseOrDiscard - rsemUseOrDiscardExpr - rsemCannotBeRaised - rsemCannotRaiseNonException - rsemExceptionAlreadyHandled - rsemCannotExceptNativeAndImported - rsemExpectedSingleFinally - rsemExpectedSingleGeneralExcept - rsemCannotConvertToRange - rsemUsingRequiresType - rsemUsingDisallowsAssign - rsemDifferentTypeForReintroducedSymbol - rsemImplicitFieldConstructinoRequiresPartial - rsemCannotInferTypeOfLiteral - rsemCannotInferTypeOfParameter - rsemProcHasNoConcreteType - rsemThreadvarCannotInit - rsemLetNeedsInit - rsemConstExpressionExpected - rsemFieldsIteratorCannotContinue - rsemParallelFieldsDisallowsCase - rsemNoObjectOrTupleType - rsemForExpectsIterator - rsemSelectorMustBeOfCertainTypes - rsemTypeCannotBeForwarded - rsemDoubleCompletionOf - rsemExpectedInvariantParam - rsemCovariantUsedAsNonCovariant - rsemContravariantUsedAsNonCovariant - rsemNonInvariantCannotBeUsedWith - rsemNonInvariantCnnnotBeUsedInConcepts - rsemIncorrectResultProcSymbol - rsemRebidingImplicitDestructor - rsemRebidingDestructor - rsemRebidingDeepCopy - rsemInseparableTypeBoundOp - rsemUnexpectedTypeBoundOpSignature - rsemExpectedDestroyOrDeepCopyForOverride - rsemExpectedObjectForMethod - rsemUnexpectedPragmaInDefinitionOf - rsemMisplacedRunnableExample - - # Expressions - rsemConstantOfTypeHasNoValue - rsemTypeConversionArgumentMismatch - rsemUnexpectedEqInObjectConstructor - rsemIllegalConversion - rsemCannotBeConvertedTo - rsemCannotCastToNonConcrete - rsemCannotCastTypes - rsemExpectedTypeOrValue - rsemInvalidArgumentFor - rsemNoTupleTypeForConstructor - rsemInvalidTupleConstructor - rsemUnknownIdentifier - rsemIndexOutOfBounds - rsemInvalidOrderInArrayConstructor - rsemVarForOutParamNeeded - rsemStackEscape - rsemExprHasNoAddress - rsemUnknownTrait - rsemStringOrIdentNodeExpected - rsemExpectedObjectForOf - rsemCannotBeOfSubtype - rsemQuantifierInRangeExpected - rsemOldTakesParameterName - rsemOldDoesNotBelongTo - rsemCannotFindPlugin - rsemExpectedProcReferenceForFinalizer - rsemCannotIsolate - rsemCannotInterpretNode - rsemRecursiveDependencyIterator - rsemIllegalNimvmContext - rsemDisallowedNilDeref - rsemInvalidTupleSubscript - rsemLocalEscapesStackFrame - rsemImplicitAddrIsNotFirstParam - rsemExpectedOwnerReturn - rsemExpectedUnownedRef - rsemCannotAssignTo - rsemNoReturnTypeDeclared - rsemReturnNotAllowed - rsemCannotInferReturnType - rsemExpectedValueForYield - rsemUnexpectedYield - rsemCannotReturnTypeless - rsemExpectedMacroOrTemplate - rsemAmbiguousGetAst - rsemExpectedTemplateWithNArgs - rsemExpectedCallForGetAst - rsemWrongNumberOfQuoteArguments - rsemEnableExperimentalParallel - rsemExpectedExpressionForSpawn - rsemNamedExprExpected - rsemNamedExprNotAllowed - rsemFieldInitTwice - rsemDisallowedTypedescForTupleField - rsemDisjointFields - rsemUnsafeRuntimeDiscriminantInit - rsemConflictingDiscriminantInit - rsemConflictingDiscriminantValues - rsemRuntimeDiscriminantInitCap - rsemRuntimeDiscriminantMustBeImmutable - rsemRuntimeDiscriminantRequiresElif - rsemObjectRequiresFieldInit - rsemObjectRequiresFieldInitNoDefault - rsemDistinctDoesNotHaveDefaultValue - rsemExpectedModuleNameForImportExcept - rsemCannotExport - rsemCannotMixTypesAndValuesInTuple - rsemExpectedTypelessDeferBody - rsemInvalidBindContext - rsemCannotCreateImplicitOpenarray - rsemCannotAssignToDiscriminantWithCustomDestructor - rsemUnavailableTypeBound - - rsemParallelInvalidControlFlow - rsemParallelCannotProveDisjoint - rsemParallelCounterAfterIncrement - rsemParallelWithoutSpawn - rsemSpawnInvalidContext - - # Identifier Lookup - rsemUndeclaredIdentifier - rsemExpectedIdentifier - rsemExpectedIdentifierInExpr - - # Object and Object Construction - rsemFieldNotAccessible - ## object field is not accessible - rsemFieldAssignmentInvalid - ## object field assignment invalid syntax - rsemFieldOkButAssignedValueInvalid - ## object field assignment, where the field name is ok, but value is not - rsemObjectConstructorIncorrect - ## one or more issues encountered with object constructor - - # General Type Checks - rsemExpressionHasNoType - ## an expression has not type or is ambiguous - - rsemRawTypeMismatch - - rsemCannotConvertTypes - rsemUnresolvedGenericParameter - rsemCannotCreateFlowVarOfType - rsemTypeNotAllowed - - # Literals - rsemIntLiteralExpected - ## int literal node was expected, but got something else - rsemStringLiteralExpected - ## string literal node was expected, but got something else - - rsemOnOrOffExpected - rsemCallconvExpected - rsemInnerCodeReordering - rsemUnknownExperimental - rsemDuplicateCaseLabel - - # view types - rsemExpressionIsNotAPath - rsemResultMustBorrowFirst - rsemCannotDetermineBorrowTarget # TODO DOC need better explanation for - # reasons of this error, right now it looks like a hacked-in check. - rsemCannotBorrow - rsemBorrowOutlivesSource - rsemImmutableBorrowMutation - - # VM - rsemVmOpcParseExpectedExpression - rsemTooManyRegistersRequired - rsemVmCannotFindBreakTarget - rsemVmNotUnused - rsemNotAFieldSymbol - rsemVmTooLargetOffset - rsemVmUnhandledException - rsemVmCannotGenerateCode - rsemVmCannotCast - rsemVmGlobalError ## Error report that was declared as 'global' in the - ## VM - with current 'globalError-is-a-control-flow-mechanism' approach - ## this report is largely meaningless, and used only to raise exception. - rsemVmInvalidBindSym - rsemVmBadExpandToAst - rsemVmCannotEvaluateAtComptime - rsemVmCannotImportc - rsemVmEnableFFIToImportc - rsemVmCannotCreateNullElement - rsemVmInvalidObjectConstructor - rsemVmNoClosureIterators - rsemVmCannotCallMethod - rsemVmCallingNonRoutine - rsemVmCannotModifyTypechecked - rsemVmNilAccess - rsemVmDerefUnsupportedPtr - rsemVmErrInternal - rsemVmIndexError - rsemVmOutOfRange - rsemVmOverOrUnderflow - rsemVmDivisionByConstZero - rsemVmNodeNotASymbol - rsemVmNodeNotAProcSymbol - rsemVmNodeNotAFieldSymbol - rsemVmIllegalConv - rsemVmMissingCacheKey - rsemVmCacheKeyAlreadyExists - rsemVmFieldNotFound - rsemVmFieldInavailable - rsemVmCannotSetChild - rsemVmCannotAddChild - rsemVmCannotGetChild - rsemVmNoType - rsemVmNotAField - - rsemVmTooManyIterations - - rsemMissingImportcCompleteStruct - - rsemCyclicTree - rsemCyclicDependency - rsemConstExprExpected - - # Codegen - rsemRttiRequestForIncompleteObject - rsemExpectedNimcallProc - rsemExpectedExhaustiveCaseForComputedGoto - rsemExpectedUnholyEnumForComputedGoto - rsemTooManyEntriesForComputedGoto - rsemExpectedLow0ForComputedGoto - rsemExpectedCaseForComputedGoto - rsemDisallowedRangeForComputedGoto - rsemExpectedCallForCxxPattern - rsemExpectedParameterForCxxPattern - rsemExpectedLiteralForGoto - rsemRequiresDeepCopyEnabled - rsemDisallowedOfForPureObjects - rsemDisallowedReprForNewruntime - rsemCannotCodegenCompiletimeProc - - # Pragma - rsemInvalidPragma - ## suplied pragma is invalid - rsemCannotAttachPragma - rsemUnexpectedPragma - rsemPropositionExpected - rsemIllegalCustomPragma - ## supplied pragma is not a legal custom pragma, and cannot be attached - rsemNoReturnHasReturn - ## a routine marked as no return, has a return type - rsemImplicitPragmaError - ## a symbol encountered an error when processing implicit pragmas, this - ## should be applied to symbols and treated as a wrapper for the purposes - ## of reporting. the original symbol is stored as the first argument - rsemPragmaDynlibRequiresExportc - ## much the same as `ImplicitPragmaError`, except it's a special case - ## where dynlib pragma requires an importc pragma to exist on the same - ## symbol - ## xxx: pragmas shouldn't require each other, that's just bad design - - rsemWrappedError - ## there is no meaningful error to construct, but there is an error - ## further down the AST that invalidates the whole - - rsemSymbolKindMismatch - rsemIllformedAst - rsemInitHereNotAllowed - rsemIdentExpectedInExpr - rsemTypeExpected - rsemGenericTypeExpected - rsemTypeInvalid - rsemWrongIdent - rsemPragmaOptionExpected - rsemUnexpectedPushArgument - rsemCannotPushCast - rsemCastRequiresStatement - rsemExportcppRequiresCpp - rsemDynlibRequiresExportc - rsemImportjsRequiresJs - rsemImportjsRequiresPattern - rsemBitsizeRequires1248 - rsemBitsizeRequiresPositive - rsemAlignRequiresPowerOfTwo - rsemPragmaRecursiveDependency - rsemMisplacedDeprecation - rsemNoUnionForJs - - rsemThisPragmaRequires01Args - rsemMismatchedPopPush - rsemExcessiveCompilePragmaArgs - rsemLinePragmaExpectsTuple - rsemRaisesPragmaExpectsObject - - # -- locking - rsemLocksPragmaExpectsList - rsemLocksPragmaBadLevel - rsemLocksRequiresArgs - rsemMultilockRequiresSameLevel - rsemInvalidNestedLocking - rsemUnguardedAccess - rsemInvalidGuardField - - rsemDrNimRequiresUsesMissingResult - rsemDrnimCannotProveLeq - rsemDrnimCannotPorveGe - - rsemErrGcUnsafeListing - rsemBorrowPragmaNonDot - rsemInvalidExtern - rsemInvalidPragmaBlock - rsemBadDeprecatedArgs - rsemMisplacedEffectsOf - rsemMissingPragmaArg - rsemErrGcUnsafe - rsemEmptyAsm - - - # end - - # Semantic warnings begin - rsemUserWarning = "User" ## `{.warning: }` - rsemUnknownMagic = "UnknownMagic" - rsemUnusedImport = "UnusedImport" - rsemDeprecated = "Deprecated" - rsemLockLevelMismatch = "LockLevel" - rsemTypelessParam = "TypelessParam" - - rsemWarnUnlistedRaises = "Effect" ## `sempass2.checkRaisesSpec` had - ## `emitWarnings: bool` parameter which was supposedly used to control - ## whether `strictEffects` warnings actually generated an error, or - ## just a warning. But all four uses of this proc had constant `false` - ## written to this field, so for now it does not mean anything and all - ## mismatched raises are routed as errors. - - rsemDotForModuleImport - rsemReorderingFail - rsemProveField = "ProveField" - rsemStrictNotNilExpr = "StrictNotNil" - rsemStrictNotNilResult = "StrictNotNil" - rsemWarnGcUnsafe = "GcUnsafe" - rsemWarnGcUnsafeListing = "GcUnsafe2" - rsemProveInit = "ProveInit" - rsemUninit = "Uninit" - rsemWarnUnsafeCode = "UnsafeCode" - rsemImplicitCstringConvert = "CStringConv" - rsemHoleEnumConvert = "HoleEnumConv" - rsemAnyEnumConvert = "AnyEnumConv" - rsemMethodLockMismatch - rsemUseBase = "UseBase" - rsemUnreachableElse = "UnreachableElse" - rsemUnreachableCode = "UnreachableCode" - rsemInheritFromException = "InheritFromException" - rsemPtrRegionIsDeprecated - rsemTypedReturnDeprecated - rsemEachIdentIsTuple = "EachIdentIsTuple" - rsemResultShadowed = "ResultShadowed" - rsemResultUsed = "ResultUsed" - rsemGenericMethodsDeprecated - rsemSuspiciousEnumConv = "EnumConv" - rsemUnsafeSetLen = "UnsafeSetLen" - rsemUnsafeDefault = "UnsafeDefault" - rsemBindDeprecated - rsemUncollectableRefCycle = "CycleCreated" - rsemParallelWarnCannotProve - rsemParallelWarnCanProve - rsemParallelWarnNotDisjoint - rsemObservableStores = "ObservableStores" - rsemCaseTransition = "CaseTransition" - rsemUseOfGc = "GcMem" # last ! - # end - - # trace - rsemVmStackTrace - # trace - - # Semantic hints begin - rsemUserHint = "User" ## `{.hint: .}` pragma encountereed - rsemLinterReport = "Name" - rsemLinterReportUse = "Name" - rsemHintLibDependency - rsemXDeclaredButNotUsed = "XDeclaredButNotUsed" - rsemDuplicateModuleImport = "DuplicateModuleImport" - rsemXCannotRaiseY = "XCannotRaiseY" - rsemConvToBaseNotNeeded = "ConvToBaseNotNeeded" - rsemConvFromXtoItselfNotNeeded = "ConvFromXtoItselfNotNeeded" - - rsemProcessing = "Processing" ## Processing module - rsemProcessingStmt = "ProcessingStmt" ## Processing toplevel statement - - rsemExprAlwaysX = "ExprAlwaysX" ## Expression always evaluates to "X" - rsemConditionAlwaysTrue = "CondTrue" ## Condition is always true - rsemConditionAlwaysFalse = "CondFalse" ## Condition is always false - - rsemPattern = "Pattern" ## Term rewriting pattern has been triggered - rsemCannotMakeSink ## Argument could not be turned into a sink - ## parameter. Generated once in the whole compiler - ## `sinkparameter_inference.nim` - rsemCopiesToSink ## Passing data to the `sink` parameter still copies - ## due to control flow in the code - - rsemGlobalVar = "GlobalVar" ## Track global variable declarations? - - rsemEffectsListingHint - rsemExpandMacro = "ExpandMacro" ## Trace macro expansion progress - rsemExpandArc = "ExpandArc" - - rsemCompilesReport - rsemNonMatchingCandidates - rsemUserRaw = "UserRaw" # REVIEW - Used in - # `semcall.semOverloadedCall()` and `extccomp.getCompileCFileCmd()`. - # Seems like this one should be removed, it spans multiple compiler - # subsystems. Can't understand what it is doing. - - rsemExtendedContext = "ExtendedContext" ## Extended contextual - ## information. Used in `ccgstmts.genStmts()` and - ## `semexprs.semExprNoType()` - rsemImplicitObjConv = "ImplicitObjConv" - # end - - - #------------------------ Command report kinds -------------------------# - # errors - rcmdFailedExecution - # errors end - - # hints - rcmdCompiling = "CC" - rcmdLinking = "Link" - rcmdExecuting = "Exec" - rcmdRunnableExamplesSuccess - # hints end - - - #---------------------------- Debug reports ----------------------------# - rdbgVmExecTraceFull - rdbgVmExecTraceMinimal - rdbgVmCodeListing - - rdbgTraceDefined # first ! tracer begin - rdbgTraceUndefined - rdbgTraceStart - rdbgTraceStep - rdbgTraceLine - rdbgTraceEnd # last ! tracer end - - rdbgStartingConfRead - rdbgFinishedConfRead - rdbgCfgTrace - - rdbgOptionsPush - rdbgOptionsPop - - #--------------------------- Backend reports ---------------------------# - # errors start - rbackCannotWriteScript ## Cannot write build script to a cache file - rbackCannotWriteMappingFile ## Canot write module compilation mapping - ## file to cache directory - rbackTargetNotSupported ## C compiler does not support requested target - rbackJsTooCaseTooLarge - rbackJsUnsupportedClosureIter - rbackJsonScriptMismatch # ??? used in `extccomp.nim`, TODO figure out - # what the original mesage was responsible for exactly - - rbackRstCannotOpenFile - rbackRstExpected - rbackRstGridTableNotImplemented - rbackRstMarkdownIllformedTable - rbackRstNewSectionExpected - rbackRstGeneralParseError - rbackRstInvalidDirective - rbackRstInvalidField - rbackRstFootnoteMismatch - - rbackCannotProduceAssembly - # errors end - - # warnings start - rbackRstTestUnsupported - rbackRstRedefinitionOfLabel = "RedefinitionOfLabel" - rbackRstUnknownSubstitution = "UnknownSubstitutionX" - rbackRstBrokenLink = "BrokenLink" - rbackRstUnsupportedLanguage = "LanguageXNotSupported" - rbackRstUnsupportedField = "FieldXNotSupported" - rbackRstRstStyle = "warnRstStyle" - - # warnings end - - # hints start - rbackProducedAssembly - rbackCompiling = "Compiling" - rbackLinking = "Link" - # hints end - - ReportKinds* = set[ReportKind] - -const rstWarnings* = {rbackRstTestUnsupported .. rbackRstRstStyle} type ReportLineInfo* = object @@ -1018,7 +87,6 @@ type ## report type - LexerReportKind* = range[rlexMalformedUnderscores .. rlexSyntaxesCode] LexerReport* = object of ReportBase msg*: string case kind*: ReportKind @@ -1030,11 +98,6 @@ type discard -const - repLexerKinds* = {low(LexerReportKind) .. high(LexerReportKind)} - rlexHintKinds* = {rlexLineTooLong .. rlexSyntaxesCode} - rlexWarningKinds* = {rlexDeprecatedOctalPrefix .. rlexDeprecatedOctalPrefix} - rlexErrorKinds* = {rlexMalformedUnderscores .. rlexUnclosedComment} func severity*(rep: LexerReport): ReportSeverity = case LexerReportKind(rep.kind): @@ -1043,7 +106,6 @@ func severity*(rep: LexerReport): ReportSeverity = of rlexWarningKinds: rsevWarning type - ParserReportKind* = range[rparInvalidIndentation .. rparName] ParserReport* = object of ReportBase msg*: string found*: string @@ -1059,66 +121,13 @@ type -const - repParserKinds* = {low(ParserReportKind) .. high(ParserReportKind)} - rparHintKinds* = {rparName} - rparErrorKinds* = {rparInvalidIndentation .. rparInvalidFilter} - rparWarningKinds* = { - rparInconsistentSpacing .. rparPragmaBeforeGenericParameters} - func severity*(parser: ParserReport): ReportSeverity = case ParserReportKind(parser.kind): of rparHintKinds: rsevHint of rparWarningKinds: rsevWarning of rparErrorKinds: rsevError -const - rsemReportTwoSym* = { - rsemConflictingExportnims, - rsemBorrowOutlivesSource, - rsemImmutableBorrowMutation, - rsemRedefinitionOf, - rsemInvalidMethodDeclarationOrder, # [s, witness] - rsemIllegalCallconvCapture, # [symbol, owner] - rsemDeprecated # [symbol, use-instead] - } - - rsemReportOneSym* = { - rsemUnexpectedPragmaInDefinitionOf, - rsemDoubleCompletionOf, - - rsemIllegalMemoryCapture, - rsemOverrideSafetyMismatch, - rsemOverrideLockMismatch - } - - rsemReportListSym* = { - rsemAmbiguous, - rsemAmbiguousIdent, - rsemObjectRequiresFieldInit, - rsemObjectRequiresFieldInitNoDefault - } - - rsemReportCountMismatch* = { - rsemWrongNumberOfArguments, - rsemWrongNumberOfGenericParams, - rsemInvalidOrderInEnum, - rsemSetTooBig, - rsemArrayExpectsPositiveRange, - rsemExpectedLow0Discriminant, - rsemInvalidOrderInArrayConstructor, - rsemTypeConversionArgumentMismatch, - rsemInvalidTupleSubscript, - rsemExpectedTemplateWithNArgs, - rsemExpectedParameterForCxxPattern, - rsemWrongNumberOfQuoteArguments, - rsemIndexOutOfBounds, - rsemExpectedHighCappedDiscriminant - } - type - SemReportKind* = range[rsemFatalError .. rsemImplicitObjConv] - SemReportErrorKind* = range[rsemUserError .. rsemWrappedError] SemGcUnsafetyKind* = enum sgcuCallsUnsafe @@ -1349,18 +358,6 @@ type discard const - repSemKinds* = {low(SemReportKind) .. high(SemReportKind)} - rsemErrorKinds* = {rsemUserError .. rsemEmptyAsm} - rsemWarningKinds* = {rsemUserWarning .. rsemUseOfGc} - rsemHintKinds* = {rsemUserHint .. rsemImplicitObjConv} - - # Separated into standalone set to reuse in the `options.severity` - # checking - `--styleCheck=error` is set up as a global option. - repLinterKinds* = {rlexLinterReport, rsemLinterReport, rsemLinterReportUse} - - # `--experimental=strictNotNil` and `{.experimental: "strictNotNil".}` - repNilcheckKinds* = {rsemStrictNotNilExpr, rsemStrictNotNilResult} - rsemMultiNamed* = @{ "Performance": {rsemCopiesToSink, rsemCannotMakeSink}, "Name": repLinterKinds, @@ -1436,7 +433,6 @@ template tern*(predicate: bool, tBranch: untyped, fBranch: untyped): untyped = type - CmdReportKind* = range[rcmdFailedExecution .. rcmdRunnableExamplesSuccess] CmdReport* = object of ReportBase cmd*: string msg*: string @@ -1448,12 +444,6 @@ type else: discard -const - repCmdKinds* = {low(CmdReportKind) .. high(CmdReportKind)} - rcmdErrorKinds* = {rcmdFailedExecution} - rcmdWarningKinds* = default(set[ReportKind]) - rcmdHintKinds* = {rcmdCompiling .. rcmdRunnableExamplesSuccess} - func severity*(report: CmdReport): ReportSeverity = case CmdReportKind(report.kind): of rcmdHintKinds: rsevHint @@ -1461,7 +451,6 @@ func severity*(report: CmdReport): ReportSeverity = of rcmdErrorKinds: rsevError type - DebugReportKind* = range[rdbgVmExecTraceFull .. rdbgOptionsPop] DebugSemStepDirection* = enum semstepEnter, semstepLeave DebugSemStepKind* = enum @@ -1557,14 +546,10 @@ type else: discard -const - repDebugKinds* = {low(DebugReportKind) .. high(DebugReportKind)} - func severity*(report: DebugReport): ReportSeverity = rsevDebug type - BackendReportKind* = range[rbackCannotWriteScript .. rbackLinking] BackendReport* = object of ReportBase msg*: string usedCompiler*: string @@ -1584,13 +569,6 @@ type else: discard -const - repBackendKinds* = {low(BackendReportKind) .. high(BackendReportKind)} - rbackErrorKinds* = {rbackCannotWriteScript .. rbackCannotProduceAssembly} - rbackWarningKinds* = {rbackRstTestUnsupported .. rbackRstRstStyle} - rbackHintKinds* = {rbackProducedAssembly .. rbackLinking} - - func severity*(report: BackendReport): ReportSeverity = case BackendReportKind(report.kind): @@ -1599,7 +577,6 @@ func severity*(report: BackendReport): ReportSeverity = of rbackWarningKinds: rsevWarning type - ExternalReportKind* = range[rextUnknownCCompiler .. rextPath] ExternalReport* = object of ReportBase ## Report about external environment reads, passed configuration ## options etc. @@ -1625,33 +602,12 @@ type else: discard -const - repExternalKinds* = {low(ExternalReportKind) .. high(ExternalReportKind)} - rextErrorKinds* = {rextUnknownCCompiler .. rextInvalidPackageName} - rextWarningKinds* = {rextDeprecated} - rextHintKinds* = {rextConf .. rextPath} - func severity*(report: ExternalReport): ReportSeverity = case ExternalReportKind(report.kind): of rextErrorKinds: rsevError of rextWarningKinds: rsevWarning of rextHintKinds: rsevHint -type - InternalReportKind* = range[rintUnknown .. rintEchoMessage] - -const - repInternalKinds*: ReportKinds = { - low(InternalReportKind) .. high(InternalReportKind)} - - rintFatalKinds* = {rintUnknown .. rintIce} ## Fatal internal compilation - ## reports - rintErrorKinds* = {rintCannotOpenFile .. rintNotImplemented} - rintWarningKinds* = {rintWarnCannotOpenFile .. rintWarnFileChanged} - rintHintKinds* = {rintSource .. rintSuccessX} - rintDataPassKinds* = {rintStackTrace .. rintEchoMessage} - rintCliKinds* = {rintCliHelp .. rintCliAdvancedUsage} - type UsedBuildParams* = object project*: string @@ -1735,38 +691,6 @@ func severity*(report: InternalReport): ReportSeverity = of rintErrorKinds: rsevError of rintDataPassKinds: rsevTrace -const - repWarningKinds*: ReportKinds = - rsemWarningKinds + - rlexWarningKinds + - rparWarningKinds + - rbackWarningKinds + - rextWarningKinds + - rcmdWarningKinds + - rintWarningKinds - - repTraceKinds*: ReportKinds = {rsemVmStackTrace, rintStackTrace} - - repHintKinds*: ReportKinds = - rsemHintKinds + - rlexHintKinds + - rparHintKinds + - rbackHintKinds + - rextHintKinds + - rcmdHintKinds + - rintHintKinds - - repErrorKinds*: ReportKinds = - rsemErrorKinds + - rlexErrorKinds + - rparErrorKinds + - rbackErrorKinds + - rextErrorKinds + - rcmdErrorKinds + - rintErrorKinds - - repFatalKinds*: ReportKinds = rintFatalKinds - repAllKinds* = {low(ReportKind) .. high(ReportKind)} diff --git a/compiler/backend/extccomp.nim b/compiler/backend/extccomp.nim index 3d468d39cad..462d42cb26a 100644 --- a/compiler/backend/extccomp.nim +++ b/compiler/backend/extccomp.nim @@ -13,12 +13,31 @@ ## compile nim files. import - utils/[ropes, platform, pathutils], - ast/[lineinfos, reports], - front/[condsyms, options, msgs], + utils/[ + ropes, + platform, + pathutils + ], + ast/[ + lineinfos, + reports + ], + front/[ + options, + msgs + ], std/[ - os, strutils, osproc, sha1, streams, sequtils, - times, strtabs, json, jsonutils, sugar + os, + strutils, + osproc, + sha1, + streams, + sequtils, + times, + strtabs, + json, + jsonutils, + sugar ] # import ropes, platform, condsyms, options, msgs, lineinfos, pathutils, reports @@ -350,9 +369,9 @@ proc setCC*(conf: ConfigRef; ccname: string; info: TLineInfo) = conf.cCompilerPath = getConfigVar(conf, conf.cCompiler, ".path") for c in CC: - undefSymbol(conf.symbols, c.name) + undefSymbol(conf, c.name) - defineSymbol(conf.symbols, CC[conf.cCompiler].name) + defineSymbol(conf, CC[conf.cCompiler].name) proc addOpt(dest: var string, src: string) = if dest.len == 0 or dest[^1] != ' ': dest.add(" ") @@ -366,15 +385,17 @@ proc addCompileOption*(conf: ConfigRef; option: string) = addOpt(conf.compileOptions, option) proc addLinkOptionCmd*(conf: ConfigRef; option: string) = - addOpt(conf.linkOptionsCmd, option) + conf.linkOptionsCmdAdd option proc addCompileOptionCmd*(conf: ConfigRef; option: string) = - conf.compileOptionsCmd.add(option) + conf.compileOptionsCmdAdd option proc initVars*(conf: ConfigRef) = # we need to define the symbol here, because ``CC`` may have never been set! - for c in CC: undefSymbol(conf.symbols, c.name) - defineSymbol(conf.symbols, CC[conf.cCompiler].name) + for c in CC: + undefSymbol(conf, c.name) + + defineSymbol(conf, CC[conf.cCompiler].name) addCompileOption(conf, getConfigVar(conf, conf.cCompiler, ".options.always")) #addLinkOption(getConfigVar(cCompiler, ".options.linker")) if conf.cCompilerPath.len == 0: @@ -489,7 +510,7 @@ proc vccplatform(conf: ConfigRef): string = else: "" proc getLinkOptions(conf: ConfigRef): string = - result = conf.linkOptions & " " & conf.linkOptionsCmd & " " + result = conf.linkOptions & " " & conf.linkOptionsCmd.join(" ") & " " for linkedLib in items(conf.cLinkedLibs): result.add(CC[conf.cCompiler].linkLibCmd % linkedLib.quoteShell) for libDir in items(conf.cLibs): diff --git a/compiler/front/cli_reporter.nim b/compiler/front/cli_reporter.nim index 14fc0b2c79a..fe2a2ec8c9f 100644 --- a/compiler/front/cli_reporter.nim +++ b/compiler/front/cli_reporter.nim @@ -3538,10 +3538,10 @@ proc rotatedTrace(conf: ConfigRef, r: Report) = inc traceIndex else: - conf.globalOptions.excl optUseColors + conf.excl optUseColors traceFile.write(conf.reportFull(r)) traceFile.write("\n") - conf.globalOptions.incl optUseColors + conf.incl optUseColors proc reportHook*(conf: ConfigRef, r: Report): TErrorHandling = diff --git a/compiler/front/cmdlinehelper.nim b/compiler/front/cmdlinehelper.nim index bbb48cf4bb3..c3dad27fddf 100644 --- a/compiler/front/cmdlinehelper.nim +++ b/compiler/front/cmdlinehelper.nim @@ -50,7 +50,7 @@ type proc initDefinesProg*(self: NimProg, conf: ConfigRef, name: string) = condsyms.initDefines(conf.symbols) - defineSymbol conf.symbols, name + defineSymbol conf, name proc processCmdLineAndProjectPath*(self: NimProg, conf: ConfigRef, cmd: string = "") = self.processCmdLine(passCmd1, cmd, conf) @@ -70,7 +70,7 @@ proc loadConfigsAndProcessCmdLine*(self: NimProg, cache: IdentCache; conf: Confi if self.suggestMode: conf.setCmd cmdIdeTools if conf.cmd == cmdNimscript: - incl(conf.globalOptions, optWasNimscript) + incl(conf, optWasNimscript) loadConfigs(DefaultConfig, cache, conf, graph.idgen) # load all config files diff --git a/compiler/front/commands.nim b/compiler/front/commands.nim index a259b7e49c2..d287d9419f7 100644 --- a/compiler/front/commands.nim +++ b/compiler/front/commands.nim @@ -43,7 +43,6 @@ import wordrecg, ], front/[ - condsyms, options, msgs ], @@ -238,8 +237,8 @@ proc processOnOffSwitchOrList(conf: ConfigRef; op: TOptions, arg: string, pass: proc processOnOffSwitchG(conf: ConfigRef; op: TGlobalOptions, arg: string, pass: TCmdLinePass, info: TLineInfo, switch: string) = case arg.normalize - of "", "on": conf.globalOptions.incl op - of "off": conf.globalOptions.excl op + of "", "on": conf.incl op + of "off": conf.excl op else: conf.localReport ExternalReport( kind: rextExpectedOnOrOff, cmdlineProvided: arg, cmdlineSwitch: switch) @@ -660,13 +659,13 @@ proc specialDefine(conf: ConfigRef, key: string; pass: TCmdLinePass) = elif cmpIgnoreStyle(key, "release") == 0 or cmpIgnoreStyle(key, "danger") == 0: if pass in {passCmd1, passPP}: conf.excl {optStackTrace, optLineTrace, optLineDir, optOptimizeSize} - conf.globalOptions.excl {optExcessiveStackTrace, optCDebug} + conf.excl {optExcessiveStackTrace, optCDebug} conf.incl optOptimizeSpeed if cmpIgnoreStyle(key, "danger") == 0 or cmpIgnoreStyle(key, "quick") == 0: if pass in {passCmd1, passPP}: conf.excl {optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck, optOverflowCheck, optAssert, optStackTrace, optLineTrace, optLineDir} - conf.globalOptions.excl {optCDebug} + conf.excl {optCDebug} proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; conf: ConfigRef) = @@ -715,8 +714,8 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; of "excludepath": expectArg(conf, switch, arg, pass, info) let path = processPath(conf, arg, info, switch) - conf.searchPaths.keepItIf(it != path) - conf.lazyPaths.keepItIf(it != path) + conf.searchPaths = conf.searchPaths.filterIt(it != path) + conf.lazyPaths = conf.lazyPaths.filterIt(it != path) of "nimcache": expectArg(conf, switch, arg, pass, info) var arg = arg @@ -752,13 +751,13 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; if {':', '='} in arg: splitSwitch(conf, arg, key, val, pass, info) specialDefine(conf, key, pass) - defineSymbol(conf.symbols, key, val) + defineSymbol(conf, key, val) else: specialDefine(conf, arg, pass) - defineSymbol(conf.symbols, arg) + defineSymbol(conf, arg) of "undef", "u": expectArg(conf, switch, arg, pass, info) - undefSymbol(conf.symbols, arg) + undefSymbol(conf, arg) of "compile": expectArg(conf, switch, arg, pass, info) if pass in {passCmd2, passPP}: processCompile(conf, arg) @@ -779,7 +778,8 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; of "forcebuild", "f": processOnOffSwitchG(conf, {optForceFullMake}, arg, pass, info, switch) of "project": - processOnOffSwitchG(conf, {optWholeProject, optGenIndex}, arg, pass, info, switch) + processOnOffSwitchG( + conf, {optWholeProject, optGenIndex}, arg, pass, info, switch) of "gc": if conf.backend == backendJs: return # for: bug #16033 expectArg(conf, switch, arg, pass, info) @@ -787,51 +787,51 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; case arg.normalize of "boehm": conf.selectedGC = gcBoehm - defineSymbol(conf.symbols, "boehmgc") - incl conf.globalOptions, optTlsEmulation # Boehm GC doesn't scan the real TLS + defineSymbol(conf, "boehmgc") + conf.incl optTlsEmulation # Boehm GC doesn't scan the real TLS of "refc": conf.selectedGC = gcRefc of "markandsweep": conf.selectedGC = gcMarkAndSweep - defineSymbol(conf.symbols, "gcmarkandsweep") + defineSymbol(conf, "gcmarkandsweep") of "destructors", "arc": conf.selectedGC = gcArc - defineSymbol(conf.symbols, "gcdestructors") - defineSymbol(conf.symbols, "gcarc") - incl conf.globalOptions, optSeqDestructors - incl conf.globalOptions, optTinyRtti + defineSymbol(conf, "gcdestructors") + defineSymbol(conf, "gcarc") + conf.incl optSeqDestructors + conf.incl optTinyRtti if pass in {passCmd2, passPP}: - defineSymbol(conf.symbols, "nimSeqsV2") - defineSymbol(conf.symbols, "nimV2") + defineSymbol(conf, "nimSeqsV2") + defineSymbol(conf, "nimV2") if conf.exc == excNone and conf.backend != backendCpp: conf.exc = excGoto of "orc": conf.selectedGC = gcOrc - defineSymbol(conf.symbols, "gcdestructors") - defineSymbol(conf.symbols, "gcorc") - incl conf.globalOptions, optSeqDestructors - incl conf.globalOptions, optTinyRtti + defineSymbol(conf, "gcdestructors") + defineSymbol(conf, "gcorc") + conf.incl optSeqDestructors + conf.incl optTinyRtti if pass in {passCmd2, passPP}: - defineSymbol(conf.symbols, "nimSeqsV2") - defineSymbol(conf.symbols, "nimV2") + defineSymbol(conf, "nimSeqsV2") + defineSymbol(conf, "nimV2") if conf.exc == excNone and conf.backend != backendCpp: conf.exc = excGoto of "hooks": conf.selectedGC = gcHooks - defineSymbol(conf.symbols, "gchooks") - incl conf.globalOptions, optSeqDestructors + defineSymbol(conf, "gchooks") + conf.incl optSeqDestructors processOnOffSwitchG(conf, {optSeqDestructors}, arg, pass, info, switch) if pass in {passCmd2, passPP}: - defineSymbol(conf.symbols, "nimSeqsV2") + defineSymbol(conf, "nimSeqsV2") of "go": conf.selectedGC = gcGo - defineSymbol(conf.symbols, "gogc") + defineSymbol(conf, "gogc") of "none": conf.selectedGC = gcNone - defineSymbol(conf.symbols, "nogc") + defineSymbol(conf, "nogc") of "stack", "regions": conf.selectedGC = gcRegions - defineSymbol(conf.symbols, "gcregions") + defineSymbol(conf, "gcregions") of "v2": warningOptionNoop(arg) else: conf.localReport( @@ -842,79 +842,107 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; listWarnings(conf) of "warning": processSpecificNote(arg, wWarning, pass, info, switch, conf) of "hint": processSpecificNote(arg, wHint, pass, info, switch, conf) - of "warningaserror": processSpecificNote(arg, wWarningAsError, pass, info, switch, conf) - of "hintaserror": processSpecificNote(arg, wHintAsError, pass, info, switch, conf) + of "warningaserror": + processSpecificNote(arg, wWarningAsError, pass, info, switch, conf) + of "hintaserror": + processSpecificNote(arg, wHintAsError, pass, info, switch, conf) of "hints": if processOnOffSwitchOrList(conf, {optHints}, arg, pass, info, switch): listHints(conf) of "threadanalysis": if conf.backend == backendJs: discard - else: processOnOffSwitchG(conf, {optThreadAnalysis}, arg, pass, info, switch) - of "stacktrace": processOnOffSwitch(conf, {optStackTrace}, arg, pass, info, switch) - of "stacktracemsgs": processOnOffSwitch(conf, {optStackTraceMsgs}, arg, pass, info, switch) - of "excessivestacktrace": processOnOffSwitchG(conf, {optExcessiveStackTrace}, arg, pass, info, switch) - of "linetrace": processOnOffSwitch(conf, {optLineTrace}, arg, pass, info, switch) + else: + processOnOffSwitchG(conf, {optThreadAnalysis}, arg, pass, info, switch) + of "stacktrace": + processOnOffSwitch(conf, {optStackTrace}, arg, pass, info, switch) + of "stacktracemsgs": + processOnOffSwitch(conf, {optStackTraceMsgs}, arg, pass, info, switch) + of "excessivestacktrace": + processOnOffSwitchG(conf, {optExcessiveStackTrace}, arg, pass, info, switch) + of "linetrace": + processOnOffSwitch(conf, {optLineTrace}, arg, pass, info, switch) of "debugger": case arg.normalize of "on", "native", "gdb": - conf.globalOptions.incl optCDebug + conf.incl optCDebug conf.incl optLineDir #defineSymbol(conf.symbols, "nimTypeNames") # type names are used in gdb pretty printing of "off": - conf.globalOptions.excl optCDebug + conf.excl optCDebug else: conf.localReport( info, invalidSwitchValue @["native", "gdb", "on", "off"]) of "g": # alias for --debugger:native - conf.globalOptions.incl optCDebug + conf.incl optCDebug conf.incl optLineDir #defineSymbol(conf.symbols, "nimTypeNames") # type names are used in gdb pretty printing of "profiler": processOnOffSwitch(conf, {optProfiler}, arg, pass, info, switch) - if optProfiler in conf.options: defineSymbol(conf.symbols, "profiler") - else: undefSymbol(conf.symbols, "profiler") + if optProfiler in conf.options: + defineSymbol(conf, "profiler") + else: + undefSymbol(conf, "profiler") of "memtracker": processOnOffSwitch(conf, {optMemTracker}, arg, pass, info, switch) - if optMemTracker in conf.options: defineSymbol(conf.symbols, "memtracker") - else: undefSymbol(conf.symbols, "memtracker") + if optMemTracker in conf.options: + defineSymbol(conf, "memtracker") + else: + undefSymbol(conf, "memtracker") of "hotcodereloading": processOnOffSwitchG(conf, {optHotCodeReloading}, arg, pass, info, switch) if conf.hcrOn: - defineSymbol(conf.symbols, "hotcodereloading") - defineSymbol(conf.symbols, "useNimRtl") + defineSymbol(conf, "hotcodereloading") + defineSymbol(conf, "useNimRtl") # hardcoded linking with dynamic runtime for MSVC for smaller binaries # should do the same for all compilers (wherever applicable) if isVSCompatible(conf): extccomp.addCompileOptionCmd(conf, "/MD") else: - undefSymbol(conf.symbols, "hotcodereloading") - undefSymbol(conf.symbols, "useNimRtl") - of "checks", "x": processOnOffSwitch(conf, ChecksOptions, arg, pass, info, switch) + undefSymbol(conf, "hotcodereloading") + undefSymbol(conf, "useNimRtl") + of "checks", "x": + processOnOffSwitch(conf, ChecksOptions, arg, pass, info, switch) of "floatchecks": - processOnOffSwitch(conf, {optNaNCheck, optInfCheck}, arg, pass, info, switch) - of "infchecks": processOnOffSwitch(conf, {optInfCheck}, arg, pass, info, switch) - of "nanchecks": processOnOffSwitch(conf, {optNaNCheck}, arg, pass, info, switch) - of "objchecks": processOnOffSwitch(conf, {optObjCheck}, arg, pass, info, switch) - of "fieldchecks": processOnOffSwitch(conf, {optFieldCheck}, arg, pass, info, switch) - of "rangechecks": processOnOffSwitch(conf, {optRangeCheck}, arg, pass, info, switch) - of "boundchecks": processOnOffSwitch(conf, {optBoundsCheck}, arg, pass, info, switch) + processOnOffSwitch( + conf, {optNaNCheck, optInfCheck}, arg, pass, info, switch) + of "infchecks": + processOnOffSwitch(conf, {optInfCheck}, arg, pass, info, switch) + of "nanchecks": + processOnOffSwitch(conf, {optNaNCheck}, arg, pass, info, switch) + of "objchecks": + processOnOffSwitch(conf, {optObjCheck}, arg, pass, info, switch) + of "fieldchecks": + processOnOffSwitch(conf, {optFieldCheck}, arg, pass, info, switch) + of "rangechecks": + processOnOffSwitch(conf, {optRangeCheck}, arg, pass, info, switch) + of "boundchecks": + processOnOffSwitch(conf, {optBoundsCheck}, arg, pass, info, switch) of "refchecks": processOnOffSwitch(conf, {optRefCheck}, arg, pass, info, switch) - of "overflowchecks": processOnOffSwitch(conf, {optOverflowCheck}, arg, pass, info, switch) - of "staticboundchecks": processOnOffSwitch(conf, {optStaticBoundsCheck}, arg, pass, info, switch) - of "stylechecks": processOnOffSwitch(conf, {optStyleCheck}, arg, pass, info, switch) - of "linedir": processOnOffSwitch(conf, {optLineDir}, arg, pass, info, switch) - of "assertions", "a": processOnOffSwitch(conf, {optAssert}, arg, pass, info, switch) + of "overflowchecks": + processOnOffSwitch(conf, {optOverflowCheck}, arg, pass, info, switch) + of "staticboundchecks": + processOnOffSwitch(conf, {optStaticBoundsCheck}, arg, pass, info, switch) + of "stylechecks": + processOnOffSwitch(conf, {optStyleCheck}, arg, pass, info, switch) + of "linedir": + processOnOffSwitch(conf, {optLineDir}, arg, pass, info, switch) + of "assertions", "a": + processOnOffSwitch(conf, {optAssert}, arg, pass, info, switch) of "threads": - if conf.backend == backendJs: discard - else: processOnOffSwitchG(conf, {optThreads}, arg, pass, info, switch) + if conf.backend == backendJs: + discard + else: + processOnOffSwitchG(conf, {optThreads}, arg, pass, info, switch) #if optThreads in conf.globalOptions: conf.setNote(warnGcUnsafe) - of "tlsemulation": processOnOffSwitchG(conf, {optTlsEmulation}, arg, pass, info, switch) + of "tlsemulation": + processOnOffSwitchG(conf, {optTlsEmulation}, arg, pass, info, switch) of "implicitstatic": processOnOffSwitch(conf, {optImplicitStatic}, arg, pass, info, switch) of "patterns", "trmacros": - if switch.normalize == "patterns": deprecatedAlias(switch, "trmacros") + if switch.normalize == "patterns": + deprecatedAlias(switch, "trmacros") processOnOffSwitch(conf, {optTrMacros}, arg, pass, info, switch) of "opt": expectArg(conf, switch, arg, pass, info) @@ -938,23 +966,23 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; expectArg(conf, switch, arg, pass, info) case arg.normalize of "gui": - incl(conf.globalOptions, optGenGuiApp) - defineSymbol(conf.symbols, "executable") - defineSymbol(conf.symbols, "guiapp") + conf.incl optGenGuiApp + defineSymbol(conf, "executable") + defineSymbol(conf, "guiapp") of "console": - excl(conf.globalOptions, optGenGuiApp) - defineSymbol(conf.symbols, "executable") - defineSymbol(conf.symbols, "consoleapp") + conf.excl optGenGuiApp + defineSymbol(conf, "executable") + defineSymbol(conf, "consoleapp") of "lib": - incl(conf.globalOptions, optGenDynLib) - excl(conf.globalOptions, optGenGuiApp) - defineSymbol(conf.symbols, "library") - defineSymbol(conf.symbols, "dll") + incl(conf, optGenDynLib) + excl(conf, optGenGuiApp) + defineSymbol(conf, "library") + defineSymbol(conf, "dll") of "staticlib": - incl(conf.globalOptions, optGenStaticLib) - excl(conf.globalOptions, optGenGuiApp) - defineSymbol(conf.symbols, "library") - defineSymbol(conf.symbols, "staticlib") + incl(conf, optGenStaticLib) + excl(conf, optGenGuiApp) + defineSymbol(conf, "library") + defineSymbol(conf, "staticlib") else: conf.localReport( info, invalidSwitchValue @["gui", "console", "lib", "staticlib"]) @@ -967,28 +995,31 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; of "cincludes": expectArg(conf, switch, arg, pass, info) if pass in {passCmd2, passPP}: - conf.cIncludes.add processPath(conf, arg, info, switch) + conf.cIncludesAdd processPath(conf, arg, info, switch) of "clibdir": expectArg(conf, switch, arg, pass, info) if pass in {passCmd2, passPP}: - conf.cLibs.add processPath(conf, arg, info, switch) + conf.cLibsAdd processPath(conf, arg, info, switch) of "clib": expectArg(conf, switch, arg, pass, info) if pass in {passCmd2, passPP}: - conf.cLinkedLibs.add processPath(conf, arg, info, switch).string + conf.cLinkedLibsAdd processPath(conf, arg, info, switch).string of "header": if conf != nil: conf.headerFile = arg - incl(conf.globalOptions, optGenIndex) + incl(conf, optGenIndex) of "index": processOnOffSwitchG(conf, {optGenIndex}, arg, pass, info, switch) of "import": expectArg(conf, switch, arg, pass, info) if pass in {passCmd2, passPP}: - conf.implicitImports.add findModule(conf, arg, toFullPath(conf, info)).string + conf.implicitImportsAdd findModule( + conf, arg, toFullPath(conf, info)).string of "include": expectArg(conf, switch, arg, pass, info) if pass in {passCmd2, passPP}: - conf.implicitIncludes.add findModule(conf, arg, toFullPath(conf, info)).string + conf.implicitIncludesAdd findModule( + conf, arg, toFullPath(conf, info)).string + of "listcmd": processOnOffSwitchG(conf, {optListCmd}, arg, pass, info, switch) of "asm": @@ -1002,7 +1033,8 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; conf.localReport( info, invalidSwitchValue platform.listOSnames()) else: - setTarget(conf.target, theOS, conf.target.targetCPU) + conf.target = conf.target.withIt do: + setTarget(it, theOS, conf.target.targetCPU) of "cpu": expectArg(conf, switch, arg, pass, info) let cpu = platform.nameToCPU(arg) @@ -1011,7 +1043,9 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; info, invalidSwitchValue platform.listCPUnames()) else: - setTarget(conf.target, conf.target.targetOS, cpu) + conf.target = conf.target.withIt do: + setTarget(it, conf.target.targetOS, cpu) + of "run", "r": processOnOffSwitchG(conf, {optRun}, arg, pass, info, switch) of "maxloopiterationsvm": @@ -1149,10 +1183,10 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; processOnOffSwitchG(conf, {optDynlibOverrideAll}, arg, pass, info, switch) of "experimental": if arg.len == 0: - conf.features.incl oldExperimentalFeatures + conf.incl oldExperimentalFeatures else: try: - conf.features.incl parseEnum[Feature](arg) + conf.incl parseEnum[Feature](arg) except ValueError: conf.localReport( info, invalidSwitchValue( @@ -1160,7 +1194,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; "unknown experimental feature")) of "legacy": try: - conf.legacyFeatures.incl parseEnum[LegacyFeature](arg) + conf.incl parseEnum[LegacyFeature](arg) except ValueError: conf.localReport( info, invalidSwitchValue( @@ -1169,7 +1203,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; of "nocppexceptions": expectNoArg(conf, switch, arg, pass, info) conf.exc = low(ExceptionSystem) - defineSymbol(conf.symbols, "noCppExceptions") + defineSymbol(conf, "noCppExceptions") of "exceptions": case arg.normalize of "cpp": conf.exc = excCpp @@ -1186,27 +1220,32 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; expectNoArg(conf, switch, arg, pass, info) if pass in {passCmd2, passPP}: doAssert(conf != nil) - incl(conf.features, destructor) - incl(conf.globalOptions, optTinyRtti) - incl(conf.globalOptions, optOwnedRefs) - incl(conf.globalOptions, optSeqDestructors) - defineSymbol(conf.symbols, "nimV2") + incl(conf, destructor) + incl(conf, optTinyRtti) + incl(conf, optOwnedRefs) + incl(conf, optSeqDestructors) + defineSymbol(conf, "nimV2") conf.selectedGC = gcHooks - defineSymbol(conf.symbols, "gchooks") - defineSymbol(conf.symbols, "nimSeqsV2") - defineSymbol(conf.symbols, "nimOwnedEnabled") + defineSymbol(conf, "gchooks") + defineSymbol(conf, "nimSeqsV2") + defineSymbol(conf, "nimOwnedEnabled") of "seqsv2": processOnOffSwitchG(conf, {optSeqDestructors}, arg, pass, info, switch) if pass in {passCmd2, passPP}: - defineSymbol(conf.symbols, "nimSeqsV2") + defineSymbol(conf, "nimSeqsV2") of "stylecheck": case arg.normalize - of "off": conf.globalOptions = conf.globalOptions - {optStyleHint, optStyleError} - of "hint": conf.globalOptions = conf.globalOptions + {optStyleHint} - {optStyleError} - of "error": conf.globalOptions = conf.globalOptions + {optStyleError} - of "usages": conf.globalOptions.incl optStyleUsages + of "off": + conf.globalOptions = conf.globalOptions - {optStyleHint, optStyleError} + of "hint": + conf.globalOptions = conf.globalOptions + {optStyleHint} - {optStyleError} + of "error": + conf.globalOptions = conf.globalOptions + {optStyleError} + of "usages": + conf.incl optStyleUsages else: - conf.localReport(info, invalidSwitchValue @["off", "hint", "error", "usages"]) + conf.localReport( + info, invalidSwitchValue @["off", "hint", "error", "usages"]) of "showallmismatches": processOnOffSwitchG(conf, {optShowAllMismatches}, arg, pass, info, switch) of "cppcompiletonamespace": @@ -1214,7 +1253,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; conf.cppCustomNamespace = arg else: conf.cppCustomNamespace = "Nim" - defineSymbol(conf.symbols, "cppCompileToNamespace", conf.cppCustomNamespace) + defineSymbol(conf, "cppCompileToNamespace", conf.cppCustomNamespace) of "docinternal": processOnOffSwitchG(conf, {optDocInternal}, arg, pass, info, switch) of "multimethods": @@ -1229,23 +1268,23 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; expectArg(conf, switch, arg, pass, info) case arg of "1.0": - defineSymbol(conf.symbols, "NimMajor", "1") - defineSymbol(conf.symbols, "NimMinor", "0") + defineSymbol(conf, "NimMajor", "1") + defineSymbol(conf, "NimMinor", "0") # old behaviors go here: - defineSymbol(conf.symbols, "nimOldRelativePathBehavior") - undefSymbol(conf.symbols, "nimDoesntTrackDefects") + defineSymbol(conf, "nimOldRelativePathBehavior") + undefSymbol(conf, "nimDoesntTrackDefects") ast.eqTypeFlags.excl {tfGcSafe, tfNoSideEffect} - conf.globalOptions.incl optNimV1Emulation + conf.incl optNimV1Emulation of "1.2": - defineSymbol(conf.symbols, "NimMajor", "1") - defineSymbol(conf.symbols, "NimMinor", "2") - conf.globalOptions.incl optNimV12Emulation + defineSymbol(conf, "NimMajor", "1") + defineSymbol(conf, "NimMinor", "2") + conf.incl optNimV12Emulation else: conf.localReport(info, invalidSwitchValue( @["1.0", "1.2"], "unknown Nim version; currently supported values are: `1.0`, `1.2`")) # always be compatible with 1.x.100: - defineSymbol(conf.symbols, "NimPatch", "100") + defineSymbol(conf, "NimPatch", "100") of "benchmarkvm": processOnOffSwitchG(conf, {optBenchmarkVM}, arg, pass, info, switch) of "profilevm": @@ -1258,9 +1297,9 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; of "panics": processOnOffSwitchG(conf, {optPanics}, arg, pass, info, switch) if optPanics in conf.globalOptions: - defineSymbol(conf.symbols, "nimPanics") + defineSymbol(conf, "nimPanics") of "sourcemap": # xxx document in --fullhelp - conf.globalOptions.incl optSourcemap + conf.incl optSourcemap conf.incl optLineDir of "deepcopy": processOnOffSwitchG(conf, {optEnableDeepCopy}, arg, pass, info, switch) @@ -1297,7 +1336,7 @@ proc processArgument*(pass: TCmdLinePass; p: OptParser; # nim filename.nims is the same as "nim e filename.nims": if p.key.endsWith(".nims"): config.setCmd cmdNimscript - incl(config.globalOptions, optWasNimscript) + incl(config, optWasNimscript) config.projectName = unixToNativePath(p.key) config.arguments = cmdLineRest(p) result = true diff --git a/compiler/front/condsyms.nim b/compiler/front/condsyms.nim index 60df248e97c..5d773cfbb3c 100644 --- a/compiler/front/condsyms.nim +++ b/compiler/front/condsyms.nim @@ -15,25 +15,11 @@ import from front/options import Feature import ast/reports -proc defineSymbol*(symbols: StringTableRef; symbol: string, value: string = "true") = - symbols[symbol] = value - -proc undefSymbol*(symbols: StringTableRef; symbol: string) = - symbols.del(symbol) - -#proc lookupSymbol*(symbols: StringTableRef; symbol: string): string = -# result = if isDefined(symbol): gSymbols[symbol] else: nil - -iterator definedSymbolNames*(symbols: StringTableRef): string = - for key, val in pairs(symbols): - yield key - -proc countDefinedSymbols*(symbols: StringTableRef): int = - symbols.len proc initDefines*(symbols: StringTableRef) = # for bootstrapping purposes and old code: - template defineSymbol(s) = symbols.defineSymbol(s) + template defineSymbol(s) = + symbols[s] = "true" defineSymbol("nimhygiene") # deadcode defineSymbol("niminheritable") # deadcode defineSymbol("nimmixin") # deadcode diff --git a/compiler/front/in_options.nim b/compiler/front/in_options.nim new file mode 100644 index 00000000000..9a57c750333 --- /dev/null +++ b/compiler/front/in_options.nim @@ -0,0 +1,318 @@ +## This module contains defintions of all types and configuration objects +## that are used to determine nim compiler inputs. + +import utils/[pathutils, platform] +import ast/[report_enums] +import std/[sets, strtabs] + +type + TGlobalOption* = enum + gloptNone + optForceFullMake + optWasNimscript ## redundant with `cmdNimscript`, could be + ## removed + optListCmd + optCompileOnly + optNoLinking + optCDebug ## turn on debugging information + optGenDynLib ## generate a dynamic library + optGenStaticLib ## generate a static library + optGenGuiApp ## generate a GUI application + optGenScript ## generate a script file to compile the *.c + ## files + optGenMapping ## generate a mapping file + optRun ## run the compiled project + optUseNimcache ## save artifacts (including binary) in $nimcache + optStyleHint ## check that the names adhere to NEP-1 + optStyleError ## enforce that the names adhere to NEP-1 + optStyleUsages ## only enforce consistent **usages** of the + ## symbol + optSkipSystemConfigFile ## skip the system's cfg/nims config file + optSkipProjConfigFile ## skip the project's cfg/nims config file + optSkipUserConfigFile ## skip the users's cfg/nims config file + optSkipParentConfigFiles ## skip parent dir's cfg/nims config files + optNoMain ## do not generate a "main" proc + optUseColors ## use colors for hints, warnings, and errors + optThreads ## support for multi-threading + optStdout ## output to stdout + optThreadAnalysis ## thread analysis pass + optTlsEmulation ## thread var emulation turned on + optGenIndex ## generate index file for documentation; + optEmbedOrigSrc ## embed the original source in the generated + ## code also: generate header file + optIdeDebug ## idetools: debug mode + optIdeTerse ## idetools: use terse descriptions + optExcessiveStackTrace ## fully qualified module filenames + optShowAllMismatches ## show all overloading resolution candidates + optWholeProject ## for 'doc': output any dependency + optDocInternal ## generate documentation for non-exported + ## symbols + optMixedMode ## true if some module triggered C++ codegen + optDeclaredLocs ## show declaration locations in messages + optNoNimblePath + optHotCodeReloading + optDynlibOverrideAll + optSeqDestructors ## active if the implementation uses the new + ## string/seq implementation based on destructors + optTinyRtti ## active if we use the new "tiny RTTI" + ## implementation + optOwnedRefs ## active if the Nim compiler knows about + ## 'owned'. + optMultiMethods + optBenchmarkVM ## Enables cpuTime() in the VM + optProduceAsm ## produce assembler code + optPanics ## turn panics (sysFatal) into a process + ## termination + optNimV1Emulation ## emulate Nim v1.0 + optNimV12Emulation ## emulate Nim v1.2 + optSourcemap + optProfileVM ## enable VM profiler + optEnableDeepCopy ## ORC specific: enable 'deepcopy' for all + ## types. + + TGlobalOptions* = set[TGlobalOption] + + + TGCMode* = enum # the selected GC + gcUnselected = "unselected" + gcNone = "none" + gcBoehm = "boehm" + gcRegions = "regions" + gcArc = "arc" + gcOrc = "orc" + gcMarkAndSweep = "markAndSweep" + gcHooks = "hooks" + gcRefc = "refc" + gcV2 = "v2" + gcGo = "go" + # gcRefc and the GCs that follow it use a write barrier, as far as + # usesWriteBarrier() is concerned + + TOption* = enum + ## + + # please make sure we have under 32 options (improves code efficiency + # a lot!) **keep binary compatible**. + optNone + optObjCheck ## `ccgenexprs.nim` generates `isObj` check if this options + ## is enabled for a procedure + optFieldCheck ## Codegen uses it to conditionally generate check for a + ## discriminant field + optRangeCheck ## Control generation of range checks in the backend + optBoundsCheck ## Control generation of the array boundary checks in + ## the backend + optOverflowCheck ## Integer overflow check control + optRefCheck ## Deprecated option, does something with refs in te + ## `liftdestructors.nim`, need to investigate further + optNaNCheck ## Raise float invalid defect C backend if operation + ## returned nan + optInfCheck ## Raise float overflow in C backend if operation reaturned + ## inf + optStaticBoundsCheck + optStyleCheck ## Check symbol for spelling consistency + optAssert + optLineDir + optWarns + optHints + optOptimizeSpeed + optOptimizeSize + optStackTrace ## stack tracing support + optStackTraceMsgs ## enable custom runtime msgs via `setFrameMsg` + optLineTrace ## line tracing support (includes stack tracing) + optByRef ## use pass by ref for objects + ## (for interfacing with C) + optProfiler ## profiler turned on + optImplicitStatic ## optimization: implicit at compile time + ## evaluation + optTrMacros ## en/disable pattern matching + optMemTracker + optSinkInference ## 'sink T' inference + optCursorInference + optImportHidden + + TOptions* = set[TOption] + + TBackend* = enum + ## Target compilation backend + backendInvalid = "" # for parseEnum + backendC = "c" + backendCpp = "cpp" + backendJs = "js" + backendObjc = "objc" + # backendNimscript = "nimscript" # this could actually work + # backendLlvm = "llvm" # probably not well supported; was cmdCompileToLLVM + + Command* = enum + ## Compiler execution command + cmdNone ## not yet processed command + cmdUnknown ## command unmapped + cmdCompileToC + cmdCompileToCpp + cmdCompileToOC + cmdCompileToJS + cmdCrun ## compile and run in nimache + cmdTcc ## run the project via TCC backend + cmdCheck ## semantic checking for whole project + cmdParse ## parse a single file (for debugging) + cmdRod ## .rod to some text representation (for debugging) + cmdIdeTools ## ide tools (e.g. nimsuggest) + cmdNimscript ## evaluate nimscript + cmdDoc0 + cmdDoc ## convert .nim doc comments to HTML + cmdDoc2tex ## convert .nim doc comments to LaTeX + cmdRst2html ## convert a reStructuredText file to HTML + cmdRst2tex ## convert a reStructuredText file to TeX + cmdJsondoc0 + cmdJsondoc + cmdCtags + cmdBuildindex + cmdGendepend + cmdDump + cmdInteractive ## start interactive session + cmdNop + cmdJsonscript ## compile a .json build file + cmdNimfix + # old unused: cmdInterpret, cmdDef: def feature (find definition for IDEs) + + FilenameOption* = enum + ## Filename formatting option + foAbs ## absolute path, e.g.: /pathto/bar/foo.nim + foRelProject ## relative to project path, e.g.: ../foo.nim + foCanonical ## canonical module name + foLegacyRelProj ## legacy, shortest of (foAbs, foRelProject) + foName ## lastPathPart, e.g.: foo.nim + foStacktrace ## if optExcessiveStackTrace: foAbs else: foName + + Feature* = enum ## experimental features; DO NOT RENAME THESE! + implicitDeref, + dotOperators, + callOperator, + parallel, + destructor, + notnil, + dynamicBindSym, + forLoopMacros, ## not experimental anymore; remains here for backwards + ## compatibility + caseStmtMacros, + codeReordering, + compiletimeFFI, + ## This requires building nim with `-d:nimHasLibFFI` + ## which itself requires `nimble install libffi`, see #10150 + ## Note: this feature can't be localized with {.push.} + vmopsDanger, + strictFuncs, + views, + strictNotNil, + overloadableEnums, + strictEffects, + unicodeOperators + + + LegacyFeature* = enum + allowSemcheckedAstModification, + ## Allows to modify a NimNode where the type has already been + ## flagged with nfSem. If you actually do this, it will cause + ## bugs. + checkUnsignedConversions + ## Historically and especially in version 1.0.0 of the language + ## conversions to unsigned numbers were checked. In 1.0.4 they + ## are not anymore. + + TSystemCC* = enum + ccNone, ccGcc, ccNintendoSwitch, ccLLVM_Gcc, ccCLang, ccBcc, ccVcc, + ccTcc, ccEnv, ccIcl, ccIcc, ccClangCl + + ExceptionSystem* = enum + excNone, ## no exception system selected yet + excSetjmp, ## setjmp based exception handling + excCpp, ## use C++'s native exception handling + excGoto, ## exception handling based on goto (should become the new default for C) + excQuirky ## quirky exception handling + + SymbolFilesOption* = enum + disabledSf ## disables Rod files and maybe packed AST features + writeOnlySf ## not really sure, beyond not reading rod files + readOnlySf ## we only read from rod files + v2Sf ## who knows, probably a bad idea + stressTest ## likely more bad ideas + +type + ConfNoteSet* = enum + cnCurrent ## notes after resolving all logic(defaults, + ## verbosity)/cmdline/configs + cnMainPackage + cnForeign + cnWarnAsError + cnHintAsError + cnCmdline ## notes that have been set/unset from cmdline + cnModifiedy ## notes that have been set/unset from either + ## cmdline/configs + +type + ActiveConf* = object + ## Active, 'input' compiler configuration that controls behavior of the + ## system. + backend*: TBackend ## set via `nim x` or `nim --backend:x` + target*: Target # (+) + localOptions*: TOptions # (+) + globalOptions*: TGlobalOptions # (+) + cppDefines*: HashSet[string] #[ (*) ]# ## `--cppdefine` ?? + features*: set[Feature] + legacyFeatures*: set[LegacyFeature] + + symbols*: StringTableRef ## We need to use a StringTableRef here as + ## defined symbols are always guaranteed to be style insensitive. + ## Otherwise hell would break lose. + + nimblePaths*: seq[AbsoluteDir] + searchPaths*: seq[AbsoluteDir] + lazyPaths*: seq[AbsoluteDir] + + macrosToExpand*: StringTableRef ## Table of the target macros to expand. + # Used as set for some reason, probably should actually be a set. + arcToExpand*: StringTableRef ## Table of function names to expand arc for + cmd*: Command ## raw command parsed as enum + selectedGC*: TGCMode ## the selected GC (+) + exc*: ExceptionSystem ## Selected exception system + cCompiler*: TSystemCC ## the used compiler + filenameOption*: FilenameOption # how to render paths in compiler messages + + noteSets*: array[ConfNoteSet, ReportKinds] ## All note sets used for + ## compilation. Active note set (`ConfNoteSet.cnCurrent`) can be + ## swapped (depending on the context - push/pop, target package) or + ## modified (via user configuration, command-line flags) + + isVmTrace*: bool ## Whether runtime vm tracing is enabled or not + + numberOfProcessors*: int ## number of processors. Can be set using + ## `--parallelbuild`, otherwise defaults to number of processors. + + outFile*: RelativeFile + outDir*: AbsoluteDir + + implicitImports*: seq[string] ## modules that are to be implicitly + ## imported + implicitIncludes*: seq[string] ## modules that are to be implicitly + ## included + + cIncludes*: seq[AbsoluteDir] ## directories to search for included files + cLibs*: seq[AbsoluteDir] ## directories to search for lib files + cLinkedLibs*: seq[string] ## libraries to link + + dllOverrides*: StringTableRef ## `--dynliboverride` + + # These fields have weird interlinked interactions - none of them are + # simply 'what was supplied as an argument'. `projectFull` is the + # closest one to that, but it still goes through the process of + # canonicialization in `options.setFromProjectName` + projectPath*: AbsoluteDir ## holds a path like + projectName*: string ## holds a name like 'nim' + ## /home/alice/projects/nim/compiler/ + projectFull*: AbsoluteFile ## projectPath/projectName + + + linkOptionsCmd*: seq[string] ## options passed from `passl` on the + ## command line. + compileOptionsCmd*: seq[string] ## `passc` on the command line + + cppCustomNamespace*: string diff --git a/compiler/front/main.nim b/compiler/front/main.nim index bd326304177..5fe30e02a3c 100644 --- a/compiler/front/main.nim +++ b/compiler/front/main.nim @@ -95,7 +95,7 @@ proc commandGenDepend(graph: ModuleGraph) = proc commandCheck(graph: ModuleGraph) = let conf = graph.config conf.setErrorMaxHighMaybe - defineSymbol(conf.symbols, "nimcheck") + defineSymbol(conf, "nimcheck") semanticPasses(graph) # use an empty backend for semantic checking only compileProject(graph) @@ -134,7 +134,7 @@ proc commandCompileToC(graph: ModuleGraph) = return if not extccomp.ccHasSaneOverflow(conf): - conf.symbols.defineSymbol("nimEmulateOverflowChecks") + conf.defineSymbol("nimEmulateOverflowChecks") compileProject(graph) if graph.config.errorCounter > 0: @@ -169,7 +169,7 @@ proc commandCompileToJS(graph: ModuleGraph) = else: conf.exc = excCpp setTarget(conf.target, osJS, cpuJS) - defineSymbol(conf.symbols, "ecmascript") # For backward compatibility + defineSymbol(conf, "ecmascript") # For backward compatibility semanticPasses(graph) registerPass(graph, JSgenPass) compileProject(graph) @@ -178,9 +178,9 @@ proc commandCompileToJS(graph: ModuleGraph) = proc interactivePasses(graph: ModuleGraph) = initDefines(graph.config.symbols) - defineSymbol(graph.config.symbols, "nimscript") + defineSymbol(graph.config, "nimscript") # note: seems redundant with -d:nimHasLibFFI - when hasFFI: defineSymbol(graph.config.symbols, "nimffi") + when hasFFI: defineSymbol(graph.config, "nimffi") registerPass(graph, verbosePass) registerPass(graph, semPass) registerPass(graph, evalPass) @@ -259,7 +259,7 @@ proc mainCommand*(graph: ModuleGraph) = # In "nim serve" scenario, each command must reset the registered passes clearPasses(graph) conf.lastCmdTime = epochTime() - conf.searchPaths.add(conf.libpath) + conf.searchPathsAdd(conf.libpath) proc customizeForBackend(backend: TBackend) = ## Sets backend specific options but don't compile to backend yet in @@ -268,7 +268,7 @@ proc mainCommand*(graph: ModuleGraph) = # only set if wasn't already set, to allow override via `nim c -b:cpp` conf.backend = backend - defineSymbol(graph.config.symbols, $conf.backend) + defineSymbol(graph.config, $conf.backend) case conf.backend of backendC: if conf.exc == excNone: conf.exc = excSetjmp @@ -281,7 +281,7 @@ proc mainCommand*(graph: ModuleGraph) = # with "-d:useNimRtl". The HCR option has been processed earlier # and it has added this define implictly, so we must undo that here. # A better solution might be to fix system.nim - undefSymbol(conf.symbols, "useNimRtl") + undefSymbol(conf, "useNimRtl") of backendInvalid: doAssert false proc compileToBackend() = @@ -301,11 +301,11 @@ proc mainCommand*(graph: ModuleGraph) = wantMainModule(conf) let docConf = if conf.cmd == cmdDoc2tex: DocTexConfig else: DocConfig loadConfigs(docConf, cache, conf, graph.idgen) - defineSymbol(conf.symbols, "nimdoc") + defineSymbol(conf, "nimdoc") body ## command prepass - if conf.cmd == cmdCrun: conf.globalOptions.incl {optRun, optUseNimcache} + if conf.cmd == cmdCrun: conf.incl {optRun, optUseNimcache} if conf.cmd notin cmdBackends + {cmdTcc}: customizeForBackend(backendC) if conf.outDir.isEmpty: # doc like commands can generate a lot of files (especially with --project) @@ -372,7 +372,7 @@ proc mainCommand*(graph: ModuleGraph) = of cmdDump: wantMainModule(conf) var state = InternalStateDump() - for s in definedSymbolNames(conf.symbols): + for s in definedSymbolNames(conf): state.definedSymbols.add $s for dir in conf.searchPaths: diff --git a/compiler/front/options.nim b/compiler/front/options.nim index 6d7b293fd36..632cb9737cf 100644 --- a/compiler/front/options.nim +++ b/compiler/front/options.nim @@ -13,8 +13,8 @@ import ast/[reports, lineinfos], modules/nimpaths -from ast/ast_types import TOption, TOptions -export TOption, TOptions +import ./in_options +export in_options from terminal import isatty from times import utc, fromUnix, local, getTime, format, DateTime @@ -28,65 +28,6 @@ const nimEnableCovariance* = defined(nimEnableCovariance) -type - TGlobalOption* = enum - gloptNone, optForceFullMake, - optWasNimscript, ## redundant with `cmdNimscript`, could be removed - optListCmd, optCompileOnly, optNoLinking, - optCDebug, ## turn on debugging information - optGenDynLib, ## generate a dynamic library - optGenStaticLib, ## generate a static library - optGenGuiApp, ## generate a GUI application - optGenScript, ## generate a script file to compile the *.c files - optGenMapping, ## generate a mapping file - optRun, ## run the compiled project - optUseNimcache, ## save artifacts (including binary) in $nimcache - optStyleHint, ## check that the names adhere to NEP-1 - optStyleError, ## enforce that the names adhere to NEP-1 - optStyleUsages, ## only enforce consistent **usages** of the symbol - optSkipSystemConfigFile, ## skip the system's cfg/nims config file - optSkipProjConfigFile, ## skip the project's cfg/nims config file - optSkipUserConfigFile, ## skip the users's cfg/nims config file - optSkipParentConfigFiles, ## skip parent dir's cfg/nims config files - optNoMain, ## do not generate a "main" proc - optUseColors, ## use colors for hints, warnings, and errors - optThreads, ## support for multi-threading - optStdout, ## output to stdout - optThreadAnalysis, ## thread analysis pass - optTlsEmulation, ## thread var emulation turned on - optGenIndex ## generate index file for documentation; - optEmbedOrigSrc ## embed the original source in the generated code - ## also: generate header file - optIdeDebug ## idetools: debug mode - optIdeTerse ## idetools: use terse descriptions - optExcessiveStackTrace ## fully qualified module filenames - optShowAllMismatches ## show all overloading resolution candidates - optWholeProject ## for 'doc': output any dependency - optDocInternal ## generate documentation for non-exported symbols - optMixedMode ## true if some module triggered C++ codegen - optDeclaredLocs ## show declaration locations in messages - optNoNimblePath - optHotCodeReloading - optDynlibOverrideAll - optSeqDestructors ## active if the implementation uses the new - ## string/seq implementation based on destructors - optTinyRtti ## active if we use the new "tiny RTTI" - ## implementation - optOwnedRefs ## active if the Nim compiler knows about 'owned'. - optMultiMethods - optBenchmarkVM ## Enables cpuTime() in the VM - optProduceAsm ## produce assembler code - optPanics ## turn panics (sysFatal) into a process termination - optNimV1Emulation ## emulate Nim v1.0 - optNimV12Emulation ## emulate Nim v1.2 - optSourcemap - optProfileVM ## enable VM profiler - optEnableDeepCopy ## ORC specific: enable 'deepcopy' for all types. - - TGlobalOptions* = set[TGlobalOption] - - - const harmlessOptions* = {optForceFullMake, optNoLinking, optRun, optUseColors, optStdout} genSubDir* = RelativeDir"nimcache" @@ -106,44 +47,6 @@ const oKeepVariableNames* = true spellSuggestSecretSauce* = -1 -type - TBackend* = enum - backendInvalid = "" # for parseEnum - backendC = "c" - backendCpp = "cpp" - backendJs = "js" - backendObjc = "objc" - # backendNimscript = "nimscript" # this could actually work - # backendLlvm = "llvm" # probably not well supported; was cmdCompileToLLVM - - Command* = enum ## Nim's commands - cmdNone ## not yet processed command - cmdUnknown ## command unmapped - cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToJS - cmdCrun ## compile and run in nimache - cmdTcc ## run the project via TCC backend - cmdCheck ## semantic checking for whole project - cmdParse ## parse a single file (for debugging) - cmdRod ## .rod to some text representation (for debugging) - cmdIdeTools ## ide tools (e.g. nimsuggest) - cmdNimscript ## evaluate nimscript - cmdDoc0 - cmdDoc ## convert .nim doc comments to HTML - cmdDoc2tex ## convert .nim doc comments to LaTeX - cmdRst2html ## convert a reStructuredText file to HTML - cmdRst2tex ## convert a reStructuredText file to TeX - cmdJsondoc0 - cmdJsondoc - cmdCtags - cmdBuildindex - cmdGendepend - cmdDump - cmdInteractive ## start interactive session - cmdNop - cmdJsonscript ## compile a .json build file - cmdNimfix - # old unused: cmdInterpret, cmdDef: def feature (find definition for IDEs) - const cmdBackends* = {cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToJS, cmdCrun} cmdDocLike* = {cmdDoc0, cmdDoc, cmdDoc2tex, cmdJsondoc0, cmdJsondoc, @@ -152,76 +55,11 @@ const type NimVer* = tuple[major: int, minor: int, patch: int] TStringSeq* = seq[string] - TGCMode* = enum # the selected GC - gcUnselected = "unselected" - gcNone = "none" - gcBoehm = "boehm" - gcRegions = "regions" - gcArc = "arc" - gcOrc = "orc" - gcMarkAndSweep = "markAndSweep" - gcHooks = "hooks" - gcRefc = "refc" - gcV2 = "v2" - gcGo = "go" - # gcRefc and the GCs that follow it use a write barrier, - # as far as usesWriteBarrier() is concerned IdeCmd* = enum ideNone, ideSug, ideCon, ideDef, ideUse, ideDus, ideChk, ideMod, ideHighlight, ideOutline, ideKnown, ideMsg, ideProject - Feature* = enum ## experimental features; DO NOT RENAME THESE! - implicitDeref, - dotOperators, - callOperator, - parallel, - destructor, - notnil, - dynamicBindSym, - forLoopMacros, # not experimental anymore; remains here for backwards compatibility - caseStmtMacros, - codeReordering, - compiletimeFFI, - ## This requires building nim with `-d:nimHasLibFFI` - ## which itself requires `nimble install libffi`, see #10150 - ## Note: this feature can't be localized with {.push.} - vmopsDanger, - strictFuncs, - views, - strictNotNil, - overloadableEnums, - strictEffects, - unicodeOperators - - LegacyFeature* = enum - allowSemcheckedAstModification, - ## Allows to modify a NimNode where the type has already been - ## flagged with nfSem. If you actually do this, it will cause - ## bugs. - checkUnsignedConversions - ## Historically and especially in version 1.0.0 of the language - ## conversions to unsigned numbers were checked. In 1.0.4 they - ## are not anymore. - - SymbolFilesOption* = enum - disabledSf, ## disables Rod files and maybe packed AST features - writeOnlySf, ## not really sure, beyond not reading rod files - readOnlySf, ## we only read from rod files - v2Sf, ## who knows, probably a bad idea - stressTest ## likely more bad ideas - - TSystemCC* = enum - ccNone, ccGcc, ccNintendoSwitch, ccLLVM_Gcc, ccCLang, ccBcc, ccVcc, - ccTcc, ccEnv, ccIcl, ccIcc, ccClangCl - - ExceptionSystem* = enum - excNone, ## no exception system selected yet - excSetjmp, ## setjmp based exception handling - excCpp, ## use C++'s native exception handling - excGoto, ## exception handling based on goto (should become the new default for C) - excQuirky ## quirky exception handling - CfileFlag* {.pure.} = enum Cached, ## no need to recompile this time External ## file was introduced via .compile pragma @@ -264,14 +102,6 @@ type stdOrrStdout stdOrrStderr - FilenameOption* = enum - foAbs ## absolute path, e.g.: /pathto/bar/foo.nim - foRelProject ## relative to project path, e.g.: ../foo.nim - foCanonical ## canonical module name - foLegacyRelProj ## legacy, shortest of (foAbs, foRelProject) - foName ## lastPathPart, e.g.: foo.nim - foStacktrace ## if optExcessiveStackTrace: foAbs else: foName - MsgFlag* = enum ## flags altering msgWriteln behavior msgStdout, ## force writing to stdout, even stderr is default msgNoUnitSep ## the message is a complete "paragraph". @@ -286,16 +116,6 @@ type doRaise ## Raise recoverable error ReportHook* = proc(conf: ConfigRef, report: Report): TErrorHandling {.closure.} - ConfNoteSet* = enum - cnCurrent ## notes after resolving all logic(defaults, - ## verbosity)/cmdline/configs - cnMainPackage - cnForeign - cnWarnAsError - cnHintAsError - cnCmdline ## notes that have been set/unset from cmdline - cnModifiedy ## notes that have been set/unset from either - ## cmdline/configs HackController* = object ## additional configuration switches to control the behavior of the @@ -315,71 +135,78 @@ type ## fields marked with '*' are subject to ## the incremental compilation mechanisms ## (+) means "part of the dependency" - backend*: TBackend ## set via `nim x` or `nim --backend:x` - target*: Target # (+) + + # active configuration handling + active*: ActiveConf + + spellSuggestMax*: int ## max number of spelling suggestions for typos + + # 'active' configuration end + + # Set and only read for `testCompileOptionArg`, so not sure if this is + # 'active' configuration + verbosity*: int ## how verbose the compiler is + + # Additional 'configuration variables', apparenly it was too hard to + # actually enumerate all the things that compiler uses, so there are + # random `dump.format` strings in the compiler, and of course they are + # not documented anywhere really. Processing is just done with 'if has + # dot then it is a config variable' + # + # `if strutils.find(switch, '.') >= 0: options.setConfigVar(conf, switch, arg)` + configVars*: StringTableRef + + + # 'arguments' aka a single string aka 'joining strings for external + # program is bad' + arguments*: string ## the arguments to be passed to the program that + ## should be run + + linesCompiled*: int # all lines that have been compiled - localOptions*: TOptions # (+) - globalOptions*: TGlobalOptions # (+) - macrosToExpand*: StringTableRef - arcToExpand*: StringTableRef m*: MsgConfig - filenameOption*: FilenameOption # how to render paths in compiler messages - unitSep*: string - evalTemplateCounter*: int - evalMacroCounter*: int + unitSep*: string ## Unit separator between compiler messages + evalTemplateCounter*: int ## Template instantiation depth used to guard + ## against infinite expansion recursion + evalMacroCounter*: int ## Macro instantiation depth, used to guard + ## against infinite macro expansion recursion exitcode*: int8 - cmd*: Command ## raw command parsed as enum - cmdInput*: string ## input command - projectIsCmd*: bool ## whether we're compiling from a command input - implicitCmd*: bool ## whether some flag triggered an implicit `command` - selectedGC*: TGCMode ## the selected GC (+) - exc*: ExceptionSystem + + + # `--eval` flag handling + cmdInput*: string ## Code to evaluate from `--eval` switch + projectIsCmd*: bool ## whether we're compiling from a command input (`--eval` switch) + implicitCmd*: bool ## whether some flag triggered an implicit `command` (`--eval`) + + hintProcessingDots*: bool ## true for dots, false for filenames - verbosity*: int ## how verbose the compiler is - numberOfProcessors*: int ## number of processors - lastCmdTime*: float ## when caas is enabled, we measure each command + + + lastCmdTime*: float ## Start of the last compiler commmand - set + ## in the `main.mainCommand` and then read to generate 'successX' + ## message symbolFiles*: SymbolFilesOption - spellSuggestMax*: int ## max number of spelling suggestions for typos - cppDefines*: HashSet[string] # (*) headerFile*: string - features*: set[Feature] - legacyFeatures*: set[LegacyFeature] - arguments*: string ## the arguments to be passed to the program that - ## should be run ideCmd*: IdeCmd oldNewlines*: bool - cCompiler*: TSystemCC ## the used compiler - noteSets*: array[ConfNoteSet, ReportKinds] ## All note sets used for - ## compilation. Active note set (`ConfNoteSet.cnCurrent`) can be - ## swapped (depending on the context - push/pop, target package) or - ## modified (via user configuration, command-line flags) mainPackageId*: int errorCounter*: int hintCounter*: int warnCounter*: int - errorMax*: int + errorMax*: int ## Maximum number of errors before compilation will be terminated maxLoopIterationsVM*: int ## VM: max iterations of all loops - isVmTrace*: bool - configVars*: StringTableRef - symbols*: StringTableRef ## We need to use a StringTableRef here as - ## defined symbols are always guaranteed to be style insensitive. - ## Otherwise hell would break lose. + packageCache*: StringTableRef - nimblePaths*: seq[AbsoluteDir] - searchPaths*: seq[AbsoluteDir] - lazyPaths*: seq[AbsoluteDir] - outFile*: RelativeFile - outDir*: AbsoluteDir + jsonBuildFile*: AbsoluteFile prefixDir*, libpath*, nimcacheDir*: AbsoluteDir nimStdlibVersion*: NimVer - dllOverrides, moduleOverrides*, cfileSpecificOptions*: StringTableRef - projectName*: string ## holds a name like 'nim' - projectPath*: AbsoluteDir ## holds a path like /home/alice/projects/nim/compiler/ - projectFull*: AbsoluteFile ## projectPath/projectName + moduleOverrides*: StringTableRef + cfileSpecificOptions*: StringTableRef ## File specific compilation options for C backend. + ## Modified by `{.localPassc.}` projectIsStdin*: bool ## whether we're compiling from stdin lastMsgWasDot*: set[StdOrrKind] ## the last compiler message was a single '.' projectMainIdx*: FileIndex ## the canonical path id of the main module @@ -389,25 +216,21 @@ type commandLine*: string extraCmds*: seq[string] ## for writeJsonBuildInstructions keepComments*: bool ## whether the parser needs to keep comments - implicitImports*: seq[string] ## modules that are to be implicitly imported - implicitIncludes*: seq[string] ## modules that are to be implicitly included docSeeSrcUrl*: string ## if empty, no seeSrc will be ## generated. The string uses the formatting variables `path` and ## `line`. docRoot*: string ## see nim --fullhelp for --docRoot docCmd*: string ## see nim --fullhelp for --docCmd - configFiles*: seq[AbsoluteFile] ## config files (cfg,nims) - cIncludes*: seq[AbsoluteDir] ## directories to search for included files - cLibs*: seq[AbsoluteDir] ## directories to search for lib files - cLinkedLibs*: seq[string] ## libraries to link + configFiles*: seq[AbsoluteFile] ## List of config files that have been + ## processed during compilation. externalToLink*: seq[string] ## files to link in addition to the file - ## we compiled (*) - linkOptionsCmd*: string - compileOptionsCmd*: seq[string] - linkOptions*: string # (*) - compileOptions*: string # (*) + ## we compiled. Modified by the `{.link.}` pragma + linkOptions*: string ## Additional linking options, modified by the + ## `{.passl.}` pragma + compileOptions*: string ## Additional compilation optinos, modified by + ## the `{.passc.}` pragma cCompilerPath*: string toCompile*: CfileList # (*) suggestionResultHook*: proc (result: Suggest) {.closure.} @@ -423,7 +246,6 @@ type writeHook*: proc(conf: ConfigRef, output: string, flags: MsgFlags) {.closure.} structuredReportHook*: ReportHook - cppCustomNamespace*: string vmProfileData*: ProfileData hack*: HackController ## Configuration values for debug printing @@ -432,13 +254,103 @@ type debugUtilsStack*: seq[string] ## which proc name to stop trace output ## len is also used for output indent level +template passField(fieldname, fieldtype: untyped): untyped = + proc `fieldname`*(conf: ConfigRef): fieldtype = + conf.active.fieldname + + proc `fieldname=`*(conf: ConfigRef, val: fieldtype) = + conf.active.fieldname = val + +passField(backend, TBackend) +passField(target, Target) + +template passSetField(fieldname, fieldtype, itemtype: untyped): untyped = + passField(fieldname, fieldtype) + + proc incl*(conf: ConfigRef, item: itemtype | fieldtype) = + conf.active.fieldname.incl item + + proc excl*(conf: ConfigRef, item: itemtype | fieldtype) = + conf.active.fieldname.excl item + +template passStrTableField(fieldname: untyped): untyped = + passField(fieldname, StringTableRef) + + proc `fieldname Set`*(conf: ConfigRef, key: string, value: string) = + conf.active.fieldname[key] = value + + proc `fieldname Get`*(conf: ConfigRef, key: string): string = + conf.active.fieldname[key] + + proc `fieldname Del`*(conf: ConfigRef, key: string) = + conf.active.fieldname.del key + +template passSeqField(fieldname, itemtype: untyped): untyped = + passField(fieldname, seq[itemtype]) + proc `fieldname Add`*(conf: ConfigRef, item: itemtype | seq[itemtype]) = + conf.active.fieldname.add item + + +passSetField(localOptions, TOptions, TOption) +passSetField(globalOptions, TGlobalOptions, TGlobalOption) +passField(cppDefines, HashSet[string]) +passSetField(features, set[Feature], Feature) +passSetField(legacyFeatures, set[LegacyFeature], LegacyFeature) + +passStrTableField(symbols) + +proc defineSymbol*(conf: ConfigRef, symbol: string, value: string = "true") = + conf.symbolsSet(symbol, value) + +proc undefSymbol*(conf: ConfigRef; symbol: string) = + conf.symbolsDel(symbol) + +iterator definedSymbolNames*(conf: ConfigRef): string = + for key, val in pairs(conf.symbols): + yield key + +proc countDefinedSymbols*(conf: ConfigRef): int = + conf.symbols.len + +passSeqField(nimblePaths, AbsoluteDir) +passSeqField(searchPaths, AbsoluteDir) +passSeqField(lazyPaths, AbsoluteDir) + +passStrTableField(macrosToExpand) +passStrTableField(arcToExpand) +passField(cmd, Command) +passField(selectedGC, TGCMode) +passField(exc, ExceptionSystem) +passField(cCompiler, TSystemCC) +passField(filenameOption, FilenameOption) + +passField(numberOfProcessors, int) +passField(outFile, RelativeFile) +passField(outDir, AbsoluteDir) + +passSeqField(implicitImports, string) +passSeqField(implicitIncludes, string) +passSeqField(cIncludes, AbsoluteDir) +passSeqField(cLibs, AbsoluteDir) +passSeqField(cLinkedLibs, string) + +passStrTableField(dllOverrides) + +passField(projectPath, AbsoluteDir) +passField(projectName, string) +passField(projectFull, AbsoluteFile) + +passSeqField(linkOptionsCmd, string) +passSeqField(compileOptionsCmd, string) +passField(cppCustomNamespace, string) + template changed(conf: ConfigRef, s: ConfNoteSet, body: untyped) = # Template for debugging purposes - single place to track all changes in # the enabled note sets. when defined(debug): - let before = conf.noteSets[s] + let before = conf.active.noteSets[s] body - let after = conf.noteSets[s] + let after = conf.active.noteSets[s] # let n = rintMsgOrigin # if (n in before) != (n in after): @@ -452,21 +364,21 @@ template changed(conf: ConfigRef, s: ConfNoteSet, body: untyped) = proc incl*(conf: ConfigRef, nset: ConfNoteSet, note: ReportKind) = ## Include report kind in specified note set changed(conf, nset): - conf.noteSets[nset].incl note + conf.active.noteSets[nset].incl note proc excl*(conf: ConfigRef, nset: ConfNoteSet, note: ReportKind) = ## Exclude report kind from the specified note set changed(conf, nset): - conf.noteSets[nset].excl note + conf.active.noteSets[nset].excl note proc asgn*(conf: ConfigRef, nset: ConfNoteSet, notes: ReportKinds) = ## Assign to specified note set changed(conf, nset): - conf.noteSets[nset] = notes + conf.active.noteSets[nset] = notes proc asgn*(conf: ConfigRef, sto, sfrom: ConfNoteSet) = ## Assign between two specified note sets - conf.noteSets[sto] = conf.noteSets[sfrom] + conf.active.noteSets[sto] = conf.active.noteSets[sfrom] proc flip*( conf: ConfigRef, nset: ConfNoteSet, note: ReportKind, state: bool) = @@ -498,44 +410,33 @@ proc `options=`*(conf: ConfigRef, opts: TOptions) = changedOpts(conf): conf.localOptions = opts -proc excl*(conf: ConfigRef, opt: TOption | TOptions) = - ## Exclude from list of active local options - changedOpts(conf): - conf.localOptions.excl opt - -proc incl*(conf: ConfigRef, opt: TOption | TOptions) = - ## Include to list of active local options - changedOpts(conf): - conf.localOptions.incl opt - - proc modifiedyNotes*(conf: ConfigRef): ReportKinds = ## Get list of reports modified from the command line or config - conf.noteSets[cnModifiedy] + conf.active.noteSets[cnModifiedy] proc cmdlineNotes*(conf: ConfigRef): ReportKinds = ## Get list of report filters modified from the command line - conf.noteSets[cnCmdline] + conf.active.noteSets[cnCmdline] proc foreignPackageNotes*(conf: ConfigRef): ReportKinds = ## Get list of reports for foreign packages - conf.noteSets[cnForeign] + conf.active.noteSets[cnForeign] proc notes*(conf: ConfigRef): ReportKinds = ## Get list of active notes - conf.noteSets[cnCurrent] + conf.active.noteSets[cnCurrent] proc warningAsErrors*(conf: ConfigRef): ReportKinds = ## Get list of warning notes that are treated like errors - conf.noteSets[cnWarnAsError] + conf.active.noteSets[cnWarnAsError] proc hintsAsErrors*(conf: ConfigRef): ReportKinds = ## Get list of hint notes that are treated like errors - conf.noteSets[cnHintAsError] + conf.active.noteSets[cnHintAsError] proc mainPackageNotes*(conf: ConfigRef): ReportKinds = ## Get list of notes for main package - conf.noteSets[cnMainPackage] + conf.active.noteSets[cnMainPackage] proc `modifiedyNotes=`*(conf: ConfigRef, nset: ReportKinds) = ## Set list of notes modified from the cli/config @@ -758,7 +659,7 @@ func isEnabled*(conf: ConfigRef, report: ReportKind): bool = result = strictNotNil in conf.features of rdbgVmExecTraceMinimal: - result = conf.isVmTrace + result = conf.active.isVmTrace of rlexLinterReport, rsemLinterReport, : # Regular linter report is enabled if style check is either hint or @@ -944,58 +845,46 @@ proc initConfigRefCommon(conf: ConfigRef) = proc newConfigRef*(hook: ReportHook): ConfigRef = result = ConfigRef( - cCompiler: ccGcc, structuredReportHook: hook, - macrosToExpand: newStringTable(modeStyleInsensitive), - arcToExpand: newStringTable(modeStyleInsensitive), m: initMsgConfig(), - cppDefines: initHashSet[string](), - headerFile: "", features: {}, legacyFeatures: {}, + headerFile: "", configVars: newStringTable(modeStyleInsensitive), packageCache: newPackageCache(), - searchPaths: @[], - lazyPaths: @[], - outFile: RelativeFile"", - outDir: AbsoluteDir"", prefixDir: AbsoluteDir"", libpath: AbsoluteDir"", nimcacheDir: AbsoluteDir"", - dllOverrides: newStringTable(modeCaseInsensitive), moduleOverrides: newStringTable(modeStyleInsensitive), cfileSpecificOptions: newStringTable(modeCaseSensitive), - projectName: "", # holds a name like 'nim' - projectPath: AbsoluteDir"", # holds a path like /home/alice/projects/nim/compiler/ - projectFull: AbsoluteFile"", # projectPath/projectName projectIsStdin: false, # whether we're compiling from stdin projectMainIdx: FileIndex(0'i32), # the canonical path id of the main module command: "", # the main command (e.g. cc, check, scan, etc) commandArgs: @[], # any arguments after the main command commandLine: "", keepComments: true, # whether the parser needs to keep comments - implicitImports: @[], # modules that are to be implicitly imported - implicitIncludes: @[], # modules that are to be implicitly included docSeeSrcUrl: "", - cIncludes: @[], # directories to search for included files - cLibs: @[], # directories to search for lib files - cLinkedLibs: @[], # libraries to link - backend: backendInvalid, - externalToLink: @[], - linkOptionsCmd: "", - compileOptionsCmd: @[], - linkOptions: "", - compileOptions: "", - ccompilerpath: "", - toCompile: @[], - arguments: "", + active: ActiveConf( + backend: backendInvalid, + cppDefines: initHashSet[string](), + features: {}, + legacyFeatures: {}, + cCompiler: ccGcc, + macrosToExpand: newStringTable(modeStyleInsensitive), + arcToExpand: newStringTable(modeStyleInsensitive), + outFile: RelativeFile"", + outDir: AbsoluteDir"", + dllOverrides: newStringTable(modeCaseInsensitive), + ), suggestMaxResults: 10_000, maxLoopIterationsVM: 10_000_000, vmProfileData: newProfileData(), spellSuggestMax: spellSuggestSecretSauce, ) initConfigRefCommon(result) - setTargetFromSystem(result.target) + result.target = result.target.withIt do: + setTargetFromSystem(it) + # enable colors by default on terminals if terminal.isatty(stderr): - incl(result.globalOptions, optUseColors) + incl(result, optUseColors) proc newPartialConfigRef*(): ConfigRef = ## create a new ConfigRef that is only good enough for error reporting. @@ -1003,7 +892,7 @@ proc newPartialConfigRef*(): ConfigRef = initConfigRefCommon(result) proc cppDefine*(c: ConfigRef; define: string) = - c.cppDefines.incl define + c.active.cppDefines.incl define proc getStdlibVersion*(conf: ConfigRef): NimVer = if conf.nimStdlibVersion == (0,0,0): @@ -1171,13 +1060,13 @@ proc removeTrailingDirSep*(path: string): string = result = path proc disableNimblePath*(conf: ConfigRef) = - incl conf.globalOptions, optNoNimblePath - conf.lazyPaths.setLen(0) - conf.nimblePaths.setLen(0) + conf.incl optNoNimblePath + conf.lazyPaths = @[] + conf.nimblePaths = @[] proc clearNimblePath*(conf: ConfigRef) = - conf.lazyPaths.setLen(0) - conf.nimblePaths.setLen(0) + conf.lazyPaths = @[] + conf.nimblePaths = @[] include modules/packagehandling @@ -1261,7 +1150,7 @@ proc rawFindFile2(conf: ConfigRef; f: RelativeFile): AbsoluteFile = if fileExists(result): # bring to front for j in countdown(i, 1): - swap(conf.lazyPaths[j], conf.lazyPaths[j-1]) + swap(conf.active.lazyPaths[j], conf.active.lazyPaths[j-1]) return canonicalizePath(conf, result) result = AbsoluteFile"" diff --git a/compiler/front/scriptconfig.nim b/compiler/front/scriptconfig.nim index a3acbf6e991..ba48b163966 100644 --- a/compiler/front/scriptconfig.nim +++ b/compiler/front/scriptconfig.nim @@ -182,7 +182,7 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string; cbconf setCommand: conf.setCommandEarly(a.getString 0) let arg = a.getString 1 - incl(conf.globalOptions, optWasNimscript) + incl(conf, optWasNimscript) if arg.len > 0: setFromProjectName(conf, arg) cbconf getCommand: setResult(a, conf.command) @@ -233,19 +233,20 @@ proc runNimScript*(cache: IdentCache; scriptName: AbsoluteFile; let graph = newModuleGraph(cache, conf) connectCallbacks(graph) - if freshDefines: initDefines(conf.symbols) + if freshDefines: + initDefines(conf.symbols) - defineSymbol(conf.symbols, "nimscript") - defineSymbol(conf.symbols, "nimconfig") + defineSymbol(conf, "nimscript") + defineSymbol(conf, "nimconfig") registerPass(graph, semPass) registerPass(graph, evalPass) - conf.searchPaths.add(conf.libpath) + conf.searchPathsAdd(conf.libpath) let oldGlobalOptions = conf.globalOptions let oldSelectedGC = conf.selectedGC - undefSymbol(conf.symbols, "nimv2") - conf.globalOptions.excl {optTinyRtti, optOwnedRefs, optSeqDestructors} + undefSymbol(conf, "nimv2") + conf.excl {optTinyRtti, optOwnedRefs, optSeqDestructors} conf.selectedGC = gcUnselected var m = graph.makeModule(scriptName) @@ -261,18 +262,18 @@ proc runNimScript*(cache: IdentCache; scriptName: AbsoluteFile; if conf.selectedGC == gcUnselected: conf.selectedGC = oldSelectedGC if optOwnedRefs in oldGlobalOptions: - conf.globalOptions.incl {optTinyRtti, optOwnedRefs, optSeqDestructors} - defineSymbol(conf.symbols, "nimv2") + conf.incl {optTinyRtti, optOwnedRefs, optSeqDestructors} + defineSymbol(conf, "nimv2") if conf.selectedGC in {gcArc, gcOrc}: - conf.globalOptions.incl {optTinyRtti, optSeqDestructors} - defineSymbol(conf.symbols, "nimv2") + conf.incl {optTinyRtti, optSeqDestructors} + defineSymbol(conf, "nimv2") # ensure we load 'system.nim' again for the real non-config stuff! resetSystemArtifacts(graph) # do not remove the defined symbols #initDefines() - undefSymbol(conf.symbols, "nimscript") - undefSymbol(conf.symbols, "nimconfig") + undefSymbol(conf, "nimscript") + undefSymbol(conf, "nimconfig") conf.symbolFiles = oldSymbolFiles conf.localReport DebugReport( diff --git a/compiler/ic/ic.nim b/compiler/ic/ic.nim index 712069390a6..c0cfab1ee93 100644 --- a/compiler/ic/ic.nim +++ b/compiler/ic/ic.nim @@ -23,8 +23,7 @@ import ], front/[ msgs, - options, - condsyms + options ], utils/[ ropes, @@ -147,7 +146,7 @@ template primConfigFields(fn: untyped) {.dirty.} = proc definedSymbolsAsString(config: ConfigRef): string = result = newStringOfCap(200) result.add "config" - for d in definedSymbolNames(config.symbols): + for d in definedSymbolNames(config): result.add ' ' result.add d diff --git a/compiler/modules/nimblecmd.nim b/compiler/modules/nimblecmd.nim index 51c5c36ccbd..fa24114e66a 100644 --- a/compiler/modules/nimblecmd.nim +++ b/compiler/modules/nimblecmd.nim @@ -33,7 +33,7 @@ import proc addPath*(conf: ConfigRef; path: AbsoluteDir, info: TLineInfo) = if not conf.searchPaths.contains(path): - conf.searchPaths.insert(path, 0) + conf.active.searchPaths.insert(path, 0) type Version* = distinct string @@ -157,7 +157,7 @@ proc addNimblePath(conf: ConfigRef; p: string, info: TLineInfo) = if not contains(conf.searchPaths, AbsoluteDir path): conf.localReport ExternalReport(kind: rextPath, packagePath: path) - conf.lazyPaths.insert(AbsoluteDir path, 0) + conf.active.lazyPaths.insert(AbsoluteDir path, 0) proc addPathRec(conf: ConfigRef; dir: string, info: TLineInfo) = var packages: PackageInfo @@ -174,5 +174,5 @@ proc nimblePath*(conf: ConfigRef; path: AbsoluteDir, info: TLineInfo) = addNimblePath(conf, path.string, info) let i = conf.nimblePaths.find(path) if i != -1: - conf.nimblePaths.delete(i) - conf.nimblePaths.insert(path, 0) + conf.active.nimblePaths.delete(i) + conf.active.nimblePaths.insert(path, 0) diff --git a/compiler/sem/passes.nim b/compiler/sem/passes.nim index 91e63bc26b0..7d516516bce 100644 --- a/compiler/sem/passes.nim +++ b/compiler/sem/passes.nim @@ -179,9 +179,9 @@ proc processModule*(graph: ModuleGraph; module: PSym; idgen: IdGenerator; # for the interactive mode. if module.name.s != "nimscriptapi": processImplicits( - graph, graph.config.implicitImports, nkImportStmt, a, module) + graph, graph.config.active.implicitImports, nkImportStmt, a, module) processImplicits( - graph, graph.config.implicitIncludes, nkIncludeStmt, a, module) + graph, graph.config.active.implicitIncludes, nkIncludeStmt, a, module) while true: if graph.stopCompile(): break diff --git a/compiler/sem/pragmas.nim b/compiler/sem/pragmas.nim index 291c8d85e11..7359e90768e 100644 --- a/compiler/sem/pragmas.nim +++ b/compiler/sem/pragmas.nim @@ -33,7 +33,6 @@ import ], front/[ msgs, - condsyms, options ], utils/[ @@ -285,7 +284,7 @@ proc processImportCpp(c: PContext; s: PSym, ext: string): SetExternNameStatus = if c.config.backend == backendC: let m = s.getModule() incl(m.flags, sfCompileToCpp) - incl c.config.globalOptions, optMixedMode + incl c.config, optMixedMode proc processImportObjC(c: PContext; s: PSym, ext: string): SetExternNameStatus = ## produces (mutates) `s`'s `loc`ation setting the imported objc proc @@ -716,7 +715,7 @@ proc processDefine(c: PContext, n: PNode): PNode = c.config.localReport( n.info, DebugReport(kind: rdbgTraceDefined)) - defineSymbol(c.config.symbols, str) + defineSymbol(c.config, str) n else: newInvalidPragmaNode(c, n) @@ -731,7 +730,7 @@ proc processUndef(c: PContext, n: PNode): PNode = c.config.localReport( n.info, DebugReport(kind: rdbgTraceUndefined)) - undefSymbol(c.config.symbols, str) + undefSymbol(c.config, str) n else: newInvalidPragmaNode(c, n) diff --git a/compiler/vm/vm.nim b/compiler/vm/vm.nim index 62adc9e8ddf..3844164c9ed 100644 --- a/compiler/vm/vm.nim +++ b/compiler/vm/vm.nim @@ -613,7 +613,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = rc: regDescr(instr.regC) ))) - if c.config.isVmTrace: + if c.config.active.isVmTrace: # unlike nimVMDebug, this doesn't require re-compiling nim and is # controlled by user code c.config.localReport(DebugReport( diff --git a/compiler/vm/vmops.nim b/compiler/vm/vmops.nim index 58778e0160b..5bbc855b339 100644 --- a/compiler/vm/vmops.nim +++ b/compiler/vm/vmops.nim @@ -124,20 +124,20 @@ when defined(nimHasInvariant): proc querySettingImpl(conf: ConfigRef, switch: BiggestInt): string = case SingleValueSetting(switch) - of arguments: result = conf.arguments - of outFile: result = conf.outFile.string - of outDir: result = conf.outDir.string - of nimcacheDir: result = conf.getNimcacheDir().string - of projectName: result = conf.projectName - of projectPath: result = conf.projectPath.string - of projectFull: result = conf.projectFull.string - of command: result = conf.command - of commandLine: result = conf.commandLine - of linkOptions: result = conf.linkOptions - of compileOptions: result = conf.compileOptions - of ccompilerPath: result = conf.cCompilerPath - of backend: result = $conf.backend - of libPath: result = conf.libpath.string + of SingleValueSetting.arguments: result = conf.arguments + of SingleValueSetting.outFile: result = conf.outFile.string + of SingleValueSetting.outDir: result = conf.outDir.string + of SingleValueSetting.nimcacheDir: result = conf.getNimcacheDir().string + of SingleValueSetting.projectName: result = conf.projectName + of SingleValueSetting.projectPath: result = conf.projectPath.string + of SingleValueSetting.projectFull: result = conf.projectFull.string + of SingleValueSetting.command: result = conf.command + of SingleValueSetting.commandLine: result = conf.commandLine + of SingleValueSetting.linkOptions: result = conf.linkOptions + of SingleValueSetting.compileOptions: result = conf.compileOptions + of SingleValueSetting.ccompilerPath: result = conf.cCompilerPath + of SingleValueSetting.backend: result = $conf.backend + of SingleValueSetting.libPath: result = conf.libpath.string of gc: result = $conf.selectedGC proc querySettingSeqImpl(conf: ConfigRef, switch: BiggestInt): seq[string] = @@ -145,12 +145,12 @@ when defined(nimHasInvariant): for i in field: result.add i.string case MultipleValueSetting(switch) - of nimblePaths: copySeq(conf.nimblePaths) - of searchPaths: copySeq(conf.searchPaths) - of lazyPaths: copySeq(conf.lazyPaths) - of commandArgs: result = conf.commandArgs - of cincludes: copySeq(conf.cIncludes) - of clibs: copySeq(conf.cLibs) + of MultipleValueSetting.nimblePaths: copySeq(conf.nimblePaths) + of MultipleValueSetting.searchPaths: copySeq(conf.searchPaths) + of MultipleValueSetting.lazyPaths: copySeq(conf.lazyPaths) + of MultipleValueSetting.commandArgs: result = conf.commandArgs + of MultipleValueSetting.cincludes: copySeq(conf.cIncludes) + of MultipleValueSetting.clibs: copySeq(conf.cLibs) proc stackTrace2(c: PCtx, report: SemReport, n: PNode) = stackTrace( @@ -267,7 +267,7 @@ proc registerAdditionalOps*(c: PCtx) = setResult(a, sfExported in n.sym.flags) registerCallback c, "stdlib.vmutils.vmTrace", proc (a: VmArgs) = - c.config.isVmTrace = getBool(a, 0) + c.config.active.isVmTrace = getBool(a, 0) proc hashVmImpl(a: VmArgs) = var res = hashes.hash(a.getString(0), a.getInt(1).int, a.getInt(2).int)