当前位置: 首页>>代码示例>>C#>>正文


C# DiagnosticBag类代码示例

本文整理汇总了C#中DiagnosticBag的典型用法代码示例。如果您正苦于以下问题:C# DiagnosticBag类的具体用法?C# DiagnosticBag怎么用?C# DiagnosticBag使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


DiagnosticBag类属于命名空间,在下文中一共展示了DiagnosticBag类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ParseAssignment

        internal static ExpressionSyntax ParseAssignment(
            this string target,
            string expr,
            DiagnosticBag diagnostics)
        {
            var text = SourceText.From(expr);
            var expression = SyntaxHelpers.ParseDebuggerExpressionInternal(text, consumeFullText: true);
            // We're creating a SyntaxTree for just the RHS so that the Diagnostic spans for parse errors
            // will be correct (with respect to the original input text).  If we ever expose a SemanticModel
            // for debugger expressions, we should use this SyntaxTree.
            var syntaxTree = expression.CreateSyntaxTree(text);
            diagnostics.AddRange(syntaxTree.GetDiagnostics());
            if (diagnostics.HasAnyErrors())
            {
                return null;
            }

            // Any Diagnostic spans produced in binding will be offset by the length of the "target" expression text.
            // If we want to support live squiggles in debugger windows, SemanticModel, etc, we'll want to address this.
            var targetSyntax = SyntaxHelpers.ParseDebuggerExpressionInternal(SourceText.From(target), consumeFullText: true);
            Debug.Assert(!targetSyntax.GetDiagnostics().Any(), "The target of an assignment should never contain Diagnostics if we're being allowed to assign to it in the debugger.");

            var assignment = InternalSyntax.SyntaxFactory.AssignmentExpression(
                SyntaxKind.SimpleAssignmentExpression,
                targetSyntax,
                InternalSyntax.SyntaxFactory.Token(SyntaxKind.EqualsToken),
                expression);
            return assignment.MakeDebuggerExpression(SourceText.From(assignment.ToString()));
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:29,代码来源:SyntaxHelpers.cs

示例2: EnsureSwitchGoverningExpressionAndDiagnosticsBound

 private void EnsureSwitchGoverningExpressionAndDiagnosticsBound()
 {
     var switchGoverningDiagnostics = new DiagnosticBag();
     var boundSwitchExpression = BindSwitchExpression(SwitchSyntax.Expression, switchGoverningDiagnostics);
     _switchGoverningDiagnostics = switchGoverningDiagnostics;
     Interlocked.CompareExchange(ref _switchGoverningExpression, boundSwitchExpression, null);
 }
开发者ID:vslsnap,项目名称:roslyn,代码行数:7,代码来源:SwitchBinder.cs

示例3: GetValue

 internal override BoundExpression GetValue(BoundPseudoVariable variable, DiagnosticBag diagnostics)
 {
     var method = GetIntrinsicMethod(_compilation, ExpressionCompilerConstants.GetVariableValueMethodName);
     var local = variable.LocalSymbol;
     var expr = InvokeGetMethod(method, variable.Syntax, local.Name);
     return ConvertToLocalType(_compilation, expr, local.Type, diagnostics);
 }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:7,代码来源:ObjectIdLocalSymbol.cs

示例4: ImplicitlyTypedArrayLocal

        public void ImplicitlyTypedArrayLocal()
        {
            var compilation = CreateCompilationWithMscorlib(@"
class M {}

class C 
{ 
     public void F()
     {
        var a = new[] { new M() };
     }
}
");

            compilation.VerifyDiagnostics();

            var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("F").Single();    
            var diagnostics = new DiagnosticBag();
            var block = Compiler.BindMethodBody(method, diagnostics);

            var locDecl =(BoundLocalDeclaration)block.Statements.Single();
            var localA = (ArrayTypeSymbol)locDecl.DeclaredType.Display;
    
            var typeM = compilation.GlobalNamespace.GetMember<TypeSymbol>("M");

            Assert.Equal(typeM, localA.ElementType);
        }
开发者ID:riversky,项目名称:roslyn,代码行数:27,代码来源:ImplicitlyTypeArraysTests.cs

示例5: ResolveBounds

        /// <summary>
        /// Determine the effective base type, effective interface set, and set of type
        /// parameters (excluding cycles) from the type parameter constraints. Conflicts
        /// within the constraints and constraint types are returned as diagnostics.
        /// 'inherited' should be true if the type parameters are from an overridden
        /// generic method. In those cases, additional constraint checks are applied.
        /// </summary>
        public static TypeParameterBounds ResolveBounds(
            this TypeParameterSymbol typeParameter,
            AssemblySymbol corLibrary,
            ConsList<TypeParameterSymbol> inProgress,
            ImmutableArray<TypeSymbol> constraintTypes,
            bool inherited,
            CSharpCompilation currentCompilation,
            DiagnosticBag diagnostics)
        {
            var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance();
            ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null;
            var bounds = typeParameter.ResolveBounds(corLibrary, inProgress, constraintTypes, inherited, currentCompilation, diagnosticsBuilder, ref useSiteDiagnosticsBuilder);

            if (useSiteDiagnosticsBuilder != null)
            {
                diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder);
            }

            foreach (var pair in diagnosticsBuilder)
            {
                diagnostics.Add(new CSDiagnostic(pair.DiagnosticInfo, pair.TypeParameter.Locations[0]));
            }

            diagnosticsBuilder.Free();
            return bounds;
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:33,代码来源:ConstraintsHelper.cs

示例6: MakeParameters

            protected override ReadOnlyArray<ParameterSymbol> MakeParameters(
                Binder binder,
                DelegateDeclarationSyntax syntax,
                out bool isExtensionMethod,
                out bool isVararg,
                DiagnosticBag diagnostics,
                CancellationToken cancellationToken)
            {
                isExtensionMethod = false;
                isVararg = false;
                var delegateBinder = binder as DelegateBinder;
                var parameters = ArrayBuilder<ParameterSymbol>.GetInstance();
                int ordinal = 0;
                foreach (var p in delegateBinder.invoke.Parameters)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (p.RefKind != RefKind.None)
                    {
                        parameters.Add(new SynthesizedParameterSymbol(this, p.Type, ordinal++, p.RefKind, p.Name));
                    }
                }

                parameters.Add(new SynthesizedParameterSymbol(this, binder.GetSpecialType(SpecialType.System_IAsyncResult, diagnostics, syntax), ordinal++, RefKind.None, "result"));
                return parameters.ToReadOnlyAndFree();
            }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:25,代码来源:SourceNamedTypeSymbol.DelegateEndInvokeMethod.cs

示例7: BindCref

 internal ImmutableArray<Symbol> BindCref(CrefSyntax syntax, out Symbol ambiguityWinner, DiagnosticBag diagnostics)
 {
     ImmutableArray<Symbol> symbols = BindCrefInternal(syntax, out ambiguityWinner, diagnostics);
     Debug.Assert(!symbols.IsDefault, "Prefer empty to null.");
     Debug.Assert((symbols.Length > 1) == ((object)ambiguityWinner != null), "ambiguityWinner should be set iff more than one symbol is returned.");
     return symbols;
 }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:7,代码来源:Binder_Crefs.cs

示例8: BindRangeVariable

            protected override BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, DiagnosticBag diagnostics)
            {
                Debug.Assert(!qv.IsTransparent);

                BoundExpression translation;
                ImmutableArray<string> path;
                if (_rangeVariableMap.TryGetValue(qv, out path))
                {
                    if (path.IsEmpty)
                    {
                        // the range variable maps directly to a use of the parameter of that name
                        var value = base.parameterMap[qv.Name];
                        Debug.Assert(value.Count == 1);
                        translation = new BoundParameter(node, value.Single()) { WasCompilerGenerated = true };
                    }
                    else
                    {
                        // if the query variable map for this variable is non empty, we always start with the current
                        // lambda's first parameter, which is a transparent identifier.
                        Debug.Assert(base.lambdaSymbol.Parameters[0].Name.StartsWith(transparentIdentifierPrefix));
                        translation = new BoundParameter(node, base.lambdaSymbol.Parameters[0]) { WasCompilerGenerated = true };
                        for (int i = path.Length - 1; i >= 0; i--)
                        {
                            var nextField = path[i];
                            translation = SelectField(node, translation, nextField, diagnostics);
                            translation.WasCompilerGenerated = true;
                        }
                    }

                    return new BoundRangeVariable(node, qv, translation, translation.Type);
                }

                return base.BindRangeVariable(node, qv, diagnostics);
            }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:34,代码来源:Binder.WithQueryLambdaParametersBinder.cs

示例9: SelectField

            private BoundExpression SelectField(SimpleNameSyntax node, BoundExpression receiver, string name, DiagnosticBag diagnostics)
            {
                var receiverType = receiver.Type as NamedTypeSymbol;
                if ((object)receiverType == null || !receiverType.IsAnonymousType)
                {
                    // We only construct transparent query variables using anonymous types, so if we're trying to navigate through
                    // some other type, we must have some hinky query API where the types don't match up as expected.
                    // We should report this as an error of some sort.
                    // TODO: DevDiv #737822 - reword error message and add test.
                    var info = new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, name, receiver.ExpressionSymbol ?? receiverType);
                    Error(diagnostics, info, node);
                    return new BoundBadExpression(
                        node,
                        LookupResultKind.Empty,
                        ImmutableArray.Create<Symbol>(receiver.ExpressionSymbol),
                        ImmutableArray.Create<BoundNode>(receiver),
                        new ExtendedErrorTypeSymbol(this.Compilation, "", 0, info));
                }

                LookupResult lookupResult = LookupResult.GetInstance();
                LookupOptions options = LookupOptions.MustBeInstance;
                HashSet<DiagnosticInfo> useSiteDiagnostics = null;
                LookupMembersWithFallback(lookupResult, receiver.Type, name, 0, ref useSiteDiagnostics, basesBeingResolved: null, options: options);
                diagnostics.Add(node, useSiteDiagnostics);

                var result = BindMemberOfType(node, node, name, 0, receiver, default(SeparatedSyntaxList<TypeSyntax>), default(ImmutableArray<TypeSymbol>), lookupResult, BoundMethodGroupFlags.None, diagnostics);
                result.WasCompilerGenerated = true;
                lookupResult.Free();
                return result;
            }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:30,代码来源:Binder.WithQueryLambdaParametersBinder.cs

示例10: TestOverloadResolutionWithDiff

        internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null)
        {
            // The mechanism of this test is: we build the bound tree for the code passed in and then extract
            // from it the nodes that describe the method symbols. We then compare the description of
            // the symbols given to the comment that follows the call.

            var mscorlibRef = new MetadataImageReference(ProprietaryTestResources.NetFX.v4_0_30316_17626.mscorlib.AsImmutableOrNull(), display: "mscorlib");
            var references = new[] { mscorlibRef }.Concat(additionalRefs ?? SpecializedCollections.EmptyArray<MetadataReference>());

            var compilation = CreateCompilation(source, references, TestOptions.ReleaseDll);

            var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
            var diagnostics = new DiagnosticBag();
            var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), diagnostics);
            var tree = BoundTreeDumperNodeProducer.MakeTree(block);
            var results = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value)
                .Where(x => x.Text == "method" && x.Value != null)
                .Select(x => x.Value)
                .ToArray());

            // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray();

            var expected = string.Join("\n", source
                .Split(new[] { "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries)
                .Where(x => x.Contains("//-"))
                .Select(x => x.Substring(x.IndexOf("//-") + 3))
                .ToArray());

            AssertEx.Equal(expected, results);
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:30,代码来源:OverloadResolutionTestBase.cs

示例11: ReportInferenceFailure

 private void ReportInferenceFailure(DiagnosticBag diagnostics)
 {
     var designation = (SingleVariableDesignationSyntax)this.Syntax;
     Binder.Error(
         diagnostics, ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, designation.Identifier,
         designation.Identifier.ValueText);
 }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:7,代码来源:DeconstructionVariablePendingInference.cs

示例12: SynthesizedInteractiveInitializerMethod

        internal SynthesizedInteractiveInitializerMethod(SourceMemberContainerTypeSymbol containingType, DiagnosticBag diagnostics)
        {
            Debug.Assert(containingType.IsScriptClass);

            _containingType = containingType;
            CalculateReturnType(containingType.DeclaringCompilation, diagnostics, out _resultType, out _returnType);
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:7,代码来源:SynthesizedInteractiveInitializerMethod.cs

示例13: AsyncMethodToClassRewriter

            internal AsyncMethodToClassRewriter(
                MethodSymbol method,
                AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection,
                SyntheticBoundNodeFactory F,
                FieldSymbol state,
                FieldSymbol builder,
                HashSet<Symbol> variablesCaptured,
                Dictionary<Symbol, CapturedSymbolReplacement> initialProxies,
                DiagnosticBag diagnostics,
                bool generateDebugInfo)
                : base(F, method, state, variablesCaptured, initialProxies, diagnostics,
                      useFinalizerBookkeeping: false,
                      generateDebugInfo: generateDebugInfo)
            {
                this.method = method;
                this.asyncMethodBuilderMemberCollection = asyncMethodBuilderMemberCollection;
                this.asyncMethodBuilderField = builder;
                this.exprReturnLabel = F.GenerateLabel("exprReturn");
                this.exitLabel = F.GenerateLabel("exitLabel");

                this.exprRetValue = method.IsGenericTaskReturningAsync(F.Compilation)
                    ? F.SynthesizedLocal(asyncMethodBuilderMemberCollection.ResultType, GeneratedNames.AsyncExprRetValueFieldName())
                    : null;

                this.dynamicFactory = new LoweredDynamicOperationFactory(F);
            }
开发者ID:riversky,项目名称:roslyn,代码行数:26,代码来源:AsyncMethodToClassRewriter.cs

示例14: CheckModifiers

        internal static DeclarationModifiers CheckModifiers(
            DeclarationModifiers modifiers,
            DeclarationModifiers allowedModifiers,
            Location errorLocation,
            DiagnosticBag diagnostics,
            out bool modifierErrors)
        {
            modifierErrors = false;
            DeclarationModifiers errorModifiers = modifiers & ~allowedModifiers;
            DeclarationModifiers result = modifiers & allowedModifiers;
            while (errorModifiers != DeclarationModifiers.None)
            {
                DeclarationModifiers oneError = errorModifiers & ~(errorModifiers - 1);
                Debug.Assert(oneError != DeclarationModifiers.None);
                errorModifiers = errorModifiers & ~oneError;
                switch (oneError)
                {
                    case DeclarationModifiers.Partial:
                        diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyMethods, errorLocation);
                        break;

                    default:
                        diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, ConvertSingleModifierToSyntaxText(oneError));
                        break;
                }
                modifierErrors = true;
            }

            bool isMethod = (allowedModifiers & (DeclarationModifiers.Partial | DeclarationModifiers.Virtual)) == (DeclarationModifiers.Partial | DeclarationModifiers.Virtual);
            if (isMethod && ((result & (DeclarationModifiers.Partial | DeclarationModifiers.Private)) == (DeclarationModifiers.Partial | DeclarationModifiers.Private)))
            {
                diagnostics.Add(ErrorCode.ERR_PartialMethodInvalidModifier, errorLocation);
            }
            return result;
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:35,代码来源:ModifierUtils.cs

示例15: AsyncMethodToStateMachineRewriter

        internal AsyncMethodToStateMachineRewriter(
            MethodSymbol method,
            int methodOrdinal,
            AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection,
            SyntheticBoundNodeFactory F,
            FieldSymbol state,
            FieldSymbol builder,
            IReadOnlySet<Symbol> hoistedVariables,
            IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
            SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
            VariableSlotAllocator slotAllocatorOpt,
            int nextFreeHoistedLocalSlot,
            DiagnosticBag diagnostics)
            : base(F, method, state, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics, useFinalizerBookkeeping: false)
        {
            _method = method;
            _asyncMethodBuilderMemberCollection = asyncMethodBuilderMemberCollection;
            _asyncMethodBuilderField = builder;
            _exprReturnLabel = F.GenerateLabel("exprReturn");
            _exitLabel = F.GenerateLabel("exitLabel");

            _exprRetValue = method.IsGenericTaskReturningAsync(F.Compilation)
                ? F.SynthesizedLocal(asyncMethodBuilderMemberCollection.ResultType, syntax: F.Syntax, kind: SynthesizedLocalKind.AsyncMethodReturnValue)
                : null;

            _dynamicFactory = new LoweredDynamicOperationFactory(F, methodOrdinal);
            _awaiterFields = new Dictionary<TypeSymbol, FieldSymbol>(TypeSymbol.EqualsIgnoringDynamicComparer);
            _nextAwaiterId = slotAllocatorOpt?.PreviousAwaiterSlotCount ?? 0;
        }
开发者ID:rafaellincoln,项目名称:roslyn,代码行数:29,代码来源:AsyncMethodToStateMachineRewriter.cs


注:本文中的DiagnosticBag类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。