private LookupResult(ObjectPool<LookupResult> pool)
 {
     this.pool = pool;
     this.kind = LookupResultKind.Empty;
     this.symbolList = new ArrayBuilder<Symbol>();
     this.error = null;
 }
Пример #2
0
 private void PopulateHelper(BoundExpression receiverOpt, LookupResultKind resultKind, DiagnosticInfo error)
 {
     VerifyClear();
     this.Receiver = receiverOpt;
     this.Error = error;
     this.ResultKind = resultKind;
 }
Пример #3
0
        public void TestDiagnostic()
        {
            MockMessageProvider provider = new MockMessageProvider();
            SyntaxTree syntaxTree = new MockSyntaxTree();
            CultureInfo englishCulture = CultureHelpers.EnglishCulture;

            DiagnosticInfo di1 = new DiagnosticInfo(provider, 1);
            Assert.Equal(1, di1.Code);
            Assert.Equal(DiagnosticSeverity.Error, di1.Severity);
            Assert.Equal("MOCK0001", di1.MessageIdentifier);
            Assert.Equal("The first error", di1.GetMessage(englishCulture));

            DiagnosticInfo di2 = new DiagnosticInfo(provider, 1002, "Elvis", "Mort");
            Assert.Equal(1002, di2.Code);
            Assert.Equal(DiagnosticSeverity.Warning, di2.Severity);
            Assert.Equal("MOCK1002", di2.MessageIdentifier);
            Assert.Equal("The second warning about Elvis and Mort", di2.GetMessage(englishCulture));

            Location l1 = new SourceLocation(syntaxTree, new TextSpan(5, 8));
            var d1 = new CSDiagnostic(di2, l1);
            Assert.Equal(l1, d1.Location);
            Assert.Same(syntaxTree, d1.Location.SourceTree);
            Assert.Equal(new TextSpan(5, 8), d1.Location.SourceSpan);
            Assert.Equal(0, d1.AdditionalLocations.Count());
            Assert.Same(di2, d1.Info);
        }
Пример #4
0
 internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol containingSymbol, ImmutableArray<Symbol> candidateSymbols, LookupResultKind resultKind, DiagnosticInfo errorInfo, int arity, bool unreported = false)
     : this(containingSymbol, candidateSymbols[0].Name, arity, errorInfo, unreported)
 {
     _candidateSymbols = UnwrapErrorCandidates(candidateSymbols);
     _resultKind = resultKind;
     Debug.Assert(candidateSymbols.IsEmpty || resultKind != LookupResultKind.Viable, "Shouldn't use LookupResultKind.Viable with candidate symbols");
 }
Пример #5
0
 private LookupResult(ObjectPool<LookupResult> pool)
 {
     _pool = pool;
     _kind = LookupResultKind.Empty;
     _symbolList = new ArrayBuilder<Symbol>();
     _error = null;
 }
Пример #6
0
        internal PEFieldSymbol(
            PEModuleSymbol moduleSymbol,
            PENamedTypeSymbol containingType,
            FieldDefinitionHandle fieldDef)
        {
            Debug.Assert((object)moduleSymbol != null);
            Debug.Assert((object)containingType != null);
            Debug.Assert(!fieldDef.IsNil);

            _handle = fieldDef;
            _containingType = containingType;

            try
            {
                moduleSymbol.Module.GetFieldDefPropsOrThrow(fieldDef, out _name, out _flags);
            }
            catch (BadImageFormatException)
            {
                if ((object)_name == null)
                {
                    _name = String.Empty;
                }

                _lazyUseSiteDiagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this);
            }
        }
 /// <summary>
 /// Applies the diagnostic mask if the object was initialize with a ServiceResult.
 /// </summary>
 public void ApplyDiagnosticMasks(DiagnosticsMasks diagnosticMasks, StringTable stringTable)
 {
     if (m_result != null)
     {
         m_statusCode     = m_result.StatusCode;
         m_diagnosticInfo = new DiagnosticInfo(m_result, diagnosticMasks, false, stringTable);
     }
 }
Пример #8
0
 internal LazyObsoleteDiagnosticInfo(Symbol symbol, Symbol containingSymbol, BinderFlags binderFlags)
     : base(CSharp.MessageProvider.Instance, (int)ErrorCode.Unknown)
 {
     this.symbol = symbol;
     this.containingSymbol = containingSymbol;
     this.binderFlags = binderFlags;
     this.lazyActualObsoleteDiagnostic = null;
 }
 internal SyntaxIdentifierWithTrailingTrivia(string text, GreenNode trailing, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations)
     : base(text, diagnostics, annotations)
 {
     if (trailing != null)
     {
         this.AdjustFlagsAndWidth(trailing);
         _trailing = trailing;
     }
 }
Пример #10
0
 internal void PopulateWithSingleMethod(
     BoundExpression receiverOpt,
     MethodSymbol method,
     LookupResultKind resultKind = LookupResultKind.Viable,
     DiagnosticInfo error = null)
 {
     this.PopulateHelper(receiverOpt, resultKind, error);
     this.Methods.Add(method);
 }
 internal WithTwoChildren(DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations, GreenNode child0, GreenNode child1)
     : base(diagnostics, annotations)
 {
     this.SlotCount = 2;
     this.AdjustFlagsAndWidth(child0);
     _child0 = child0;
     this.AdjustFlagsAndWidth(child1);
     _child1 = child1;
 }
Пример #12
0
 public TupleErrorFieldSymbol(NamedTypeSymbol container, string name, int tupleFieldId, Location location, TypeSymbol type, DiagnosticInfo useSiteDiagnosticInfo)
     : base(container, name, isPublic:true, isReadOnly:false, isStatic:false)
 {
     Debug.Assert(name != null);
     _type = type;
     _locations = location == null ? ImmutableArray<Location>.Empty : ImmutableArray.Create(location);
     _useSiteDiagnosticInfo = useSiteDiagnosticInfo;
     _tupleFieldId = tupleFieldId;
 }
 public DiagnosticInfo(int namespaceUri = -1, int symbolicId = -1, int locale = -1, int localizedText = -1, string additionalInfo = null, StatusCode innerStatusCode = default(StatusCode), DiagnosticInfo innerDiagnosticInfo = null)
 {
     this.NamespaceUri = namespaceUri;
     this.SymbolicId = symbolicId;
     this.Locale = locale;
     this.LocalizedText = localizedText;
     this.AdditionalInfo = additionalInfo;
     this.InnerStatusCode = innerStatusCode;
     this.InnerDiagnosticInfo = innerDiagnosticInfo;
 }
Пример #14
0
 public static ImmutableArray<TypeWithModifiers> CreateTypeArguments(ImmutableArray<TypeParameterSymbol> typeParameters, int n, DiagnosticInfo errorInfo)
 {
     var result = ArrayBuilder<TypeWithModifiers>.GetInstance();
     for (int i = 0; i < n; i++)
     {
         string name = (i < typeParameters.Length) ? typeParameters[i].Name : string.Empty;
         result.Add(new TypeWithModifiers(new UnboundArgumentErrorTypeSymbol(name, errorInfo)));
     }
     return result.ToImmutableAndFree();
 }
Пример #15
0
 public TupleErrorFieldSymbol(NamedTypeSymbol container, string name, int tupleElementIndex, Location location, TypeSymbol type, DiagnosticInfo useSiteDiagnosticInfo, bool isImplicitlyDeclared)
     : base(container, name, isPublic:true, isReadOnly:false, isStatic:false)
 {
     Debug.Assert(name != null);
     _type = type;
     _locations = location == null ? ImmutableArray<Location>.Empty : ImmutableArray.Create(location);
     _useSiteDiagnosticInfo = useSiteDiagnosticInfo;
     _tupleElementIndex = tupleElementIndex;
     _isImplicitlyDeclared = isImplicitlyDeclared;
 }
Пример #16
0
 internal Enumerator(GreenNode node)
 {
     _current = null;
     _stack = null;
     _count = 0;
     if (node != null && node.ContainsDiagnostics)
     {
         _stack = new NodeIteration[8];
         this.PushNodeOrToken(node);
     }
 }
Пример #17
0
 private ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol containingSymbol, string name, int arity, DiagnosticInfo errorInfo, bool unreported, bool variableUsedBeforeDeclaration, ImmutableArray<Symbol> candidateSymbols, LookupResultKind resultKind)
 {
     _name = name;
     _errorInfo = errorInfo;
     _containingSymbol = containingSymbol;
     _arity = arity;
     _unreported = unreported;
     this.VariableUsedBeforeDeclaration = variableUsedBeforeDeclaration;
     _candidateSymbols = candidateSymbols;
     _resultKind = resultKind;
 }
Пример #18
0
 public override int Run(TextWriter consoleOutput, CancellationToken cancellationToken = default(CancellationToken))
 {
     try
     {
         return base.Run(consoleOutput, cancellationToken);
     }
     catch (OperationCanceledException)
     {
         DiagnosticInfo diag = new DiagnosticInfo(MessageProvider, (int)ErrorCode.ERR_CompileCancelled);
         PrintErrors(new[] { diag }, consoleOutput);
         return 1;
     }
 }
 internal SyntaxTokenWithTrivia(SyntaxKind kind, CSharpSyntaxNode leading, CSharpSyntaxNode trailing, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations)
     : base(kind, diagnostics, annotations)
 {
     if (leading != null)
     {
         this.AdjustFlagsAndWidth(leading);
         this.LeadingField = leading;
     }
     if (trailing != null)
     {
         this.AdjustFlagsAndWidth(trailing);
         this.TrailingField = trailing;
     }
 }
Пример #20
0
 internal void PopulateWithNonExtensionMethods(
     BoundExpression receiverOpt,
     ImmutableArray<MethodSymbol> methods,
     ImmutableArray<TypeSymbol> typeArguments,
     LookupResultKind resultKind = LookupResultKind.Viable,
     DiagnosticInfo error = null)
 {
     this.PopulateHelper(receiverOpt, resultKind, error);
     this.Methods.AddRange(methods);
     if (!typeArguments.IsDefault)
     {
         this.TypeArguments.AddRange(typeArguments);
     }
 }
Пример #21
0
        internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol containingSymbol, string name, int arity, DiagnosticInfo errorInfo, bool unreported = false, bool variableUsedBeforeDeclaration = false)
        {
            Debug.Assert(((object)containingSymbol == null) ||
                (containingSymbol.Kind == SymbolKind.Namespace) ||
                (containingSymbol.Kind == SymbolKind.NamedType) ||
                (containingSymbol.Kind == SymbolKind.ErrorType));

            Debug.Assert(name != null);
            Debug.Assert(unreported == false || errorInfo != null);

            _name = name;
            _errorInfo = errorInfo;
            _containingSymbol = containingSymbol;
            _arity = arity;
            _unreported = unreported;
            this.VariableUsedBeforeDeclaration = variableUsedBeforeDeclaration;
            _resultKind = LookupResultKind.Empty;
        }
Пример #22
0
 internal void PopulateWithExtensionMethods(
     BoundExpression receiverOpt,
     ArrayBuilder<Symbol> members,
     ImmutableArray<TypeSymbol> typeArguments,
     LookupResultKind resultKind = LookupResultKind.Viable,
     DiagnosticInfo error = null)
 {
     this.PopulateHelper(receiverOpt, resultKind, error);
     this.IsExtensionMethodGroup = true;
     foreach (var member in members)
     {
         this.Methods.Add((MethodSymbol)member);
     }
     if (!typeArguments.IsDefault)
     {
         this.TypeArguments.AddRange(typeArguments);
     }
 }
 internal SyntaxIdentifierWithTrivia(
     SyntaxKind contextualKind,
     string text,
     string valueText,
     GreenNode leading,
     GreenNode trailing,
     DiagnosticInfo[] diagnostics,
     SyntaxAnnotation[] annotations)
     : base(contextualKind, text, valueText, diagnostics, annotations)
 {
     if (leading != null)
     {
         this.AdjustFlagsAndWidth(leading);
         _leading = leading;
     }
     if (trailing != null)
     {
         this.AdjustFlagsAndWidth(trailing);
         _trailing = trailing;
     }
 }
Пример #24
0
            public bool MoveNext()
            {
                while (_count > 0)
                {
                    var diagIndex = _stack[_count - 1].DiagnosticIndex;
                    var node = _stack[_count - 1].Node;
                    var diags = node.GetDiagnostics();
                    if (diagIndex < diags.Length - 1)
                    {
                        diagIndex++;
                        _current = diags[diagIndex];
                        _stack[_count - 1].DiagnosticIndex = diagIndex;
                        return true;
                    }

                    var slotIndex = _stack[_count - 1].SlotIndex;
                tryAgain:
                    if (slotIndex < node.SlotCount - 1)
                    {
                        slotIndex++;
                        var child = node.GetSlot(slotIndex);
                        if (child == null || !child.ContainsDiagnostics)
                        {
                            goto tryAgain;
                        }

                        _stack[_count - 1].SlotIndex = slotIndex;
                        this.PushNodeOrToken(child);
                    }
                    else
                    {
                        this.Pop();
                    }
                }

                return false;
            }
Пример #25
0
        public TupleErrorFieldSymbol(
            NamedTypeSymbol container, 
            string name, 
            int tupleElementIndex, 
            Location location, 
            TypeSymbol type, 
            DiagnosticInfo useSiteDiagnosticInfo, 
            bool isImplicitlyDeclared,
            TupleErrorFieldSymbol correspondingDefaultFieldOpt)

            : base(container, name, isPublic:true, isReadOnly:false, isStatic:false)
        {
            Debug.Assert(name != null);
            _type = type;
            _locations = location == null ? ImmutableArray<Location>.Empty : ImmutableArray.Create(location);
            _useSiteDiagnosticInfo = useSiteDiagnosticInfo;
            _tupleElementIndex = (object)correspondingDefaultFieldOpt == null ? tupleElementIndex << 1 : (tupleElementIndex << 1) + 1;
            _isImplicitlyDeclared = isImplicitlyDeclared;

            Debug.Assert((correspondingDefaultFieldOpt == null) == this.IsDefaultTupleElement);
            Debug.Assert(correspondingDefaultFieldOpt == null || correspondingDefaultFieldOpt.IsDefaultTupleElement);

            _correspondingDefaultField = correspondingDefaultFieldOpt ?? this;
        }
Пример #26
0
        private PETypeParameterSymbol(
            PEModuleSymbol moduleSymbol,
            Symbol definingSymbol,
            ushort ordinal,
            GenericParameterHandle handle)
        {
            Debug.Assert((object)moduleSymbol != null);
            Debug.Assert((object)definingSymbol != null);
            Debug.Assert(ordinal >= 0);
            Debug.Assert(!handle.IsNil);

            _containingSymbol = definingSymbol;

            GenericParameterAttributes flags = 0;

            try
            {
                moduleSymbol.Module.GetGenericParamPropsOrThrow(handle, out _name, out flags);
            }
            catch (BadImageFormatException)
            {
                if ((object)_name == null)
                {
                    _name = string.Empty;
                }

                _lazyBoundsErrorInfo = new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this);
            }

            // Clear the '.ctor' flag if both '.ctor' and 'valuetype' are
            // set since '.ctor' is redundant in that case.
            _flags = ((flags & GenericParameterAttributes.NotNullableValueTypeConstraint) == 0) ? flags : (flags & ~GenericParameterAttributes.DefaultConstructorConstraint);

            _ordinal = ordinal;
            _handle = handle;
        }
Пример #27
0
 public override Diagnostic CreateDiagnostic(DiagnosticInfo info)
 {
     throw new NotImplementedException();
 }
Пример #28
0
 internal CSDiagnostic(DiagnosticInfo info, Location location, bool isSuppressed = false)
     : base(info, location, isSuppressed)
 {
 }
Пример #29
0
 internal static void Error(DiagnosticBag diagnostics, DiagnosticInfo info, CSharpSyntaxNode syntax)
 {
     diagnostics.Add(new CSDiagnostic(info, syntax.Location));
 }
Пример #30
0
 internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet <TypeSymbol> checkedTypes)
 {
     return(this.PointedAtTypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes));
 }
Пример #31
0
        public static ImmutableArray <TypeWithAnnotations> CreateTypeArguments(ImmutableArray <TypeParameterSymbol> typeParameters, int n, DiagnosticInfo errorInfo)
        {
            var result = ArrayBuilder <TypeWithAnnotations> .GetInstance();

            for (int i = 0; i < n; i++)
            {
                string name = (i < typeParameters.Length) ? typeParameters[i].Name : string.Empty;
                result.Add(TypeWithAnnotations.Create(new UnboundArgumentErrorTypeSymbol(name, errorInfo)));
            }
            return(result.ToImmutableAndFree());
        }
Пример #32
0
 internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet <TypeSymbol> checkedTypes)
 {
     return(false);
 }
        private readonly LookupResultKind resultKind;              // why the guessSymbols were wrong.

        internal ExtendedErrorTypeSymbol(CSharpCompilation compilation, string name, int arity, DiagnosticInfo errorInfo, bool unreported = false, bool variableUsedBeforeDeclaration = false)
            : this(compilation.Assembly.GlobalNamespace, name, arity, errorInfo, unreported, variableUsedBeforeDeclaration)
        {
        }
Пример #34
0
 private static void Error(DiagnosticBag diagnostics, SyntaxNode syntaxOpt, DiagnosticInfo info)
 {
     diagnostics.Add(new CSDiagnostic(info, syntaxOpt == null ? NoLocation.Singleton : syntaxOpt.Location));
 }
Пример #35
0
 public TypeParameterDiagnosticInfo(TypeParameterSymbol typeParameter, DiagnosticInfo diagnosticInfo)
 {
     this.TypeParameter  = typeParameter;
     this.DiagnosticInfo = diagnosticInfo;
 }
Пример #36
0
 public override Diagnostic CreateDiagnostic(DiagnosticInfo info)
 => new LuaDiagnostic(info, Location.None);
Пример #37
0
        internal override DiagnosticInfo GetUseSiteDiagnostic()
        {
            if (ReferenceEquals(_lazyUseSiteDiagnostic, CSDiagnosticInfo.EmptyErrorInfo))
            {
                DiagnosticInfo result = null;
                CalculateUseSiteDiagnostic(ref result);
                _lazyUseSiteDiagnostic = result;
            }

            return _lazyUseSiteDiagnostic;
        }
 internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics)
 {
     return new SyntaxIdentifierWithTrivia(this.contextualKind, this.TextField, this.valueText, _leading, _trailing, diagnostics, this.GetAnnotations());
 }
Пример #39
0
 internal bool DeriveUseSiteDiagnosticFromParameter(ref DiagnosticInfo result, ParameterSymbol param)
 {
     return(DeriveUseSiteDiagnosticFromType(ref result, param.Type) ||
            DeriveUseSiteDiagnosticFromCustomModifiers(ref result, param.CustomModifiers));
 }
 internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol guessSymbol, LookupResultKind resultKind, DiagnosticInfo errorInfo, bool unreported = false)
     : this(guessSymbol.ContainingNamespaceOrType(), guessSymbol, resultKind, errorInfo, unreported)
 {
 }
        internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol containingSymbol, string name, int arity, DiagnosticInfo errorInfo, bool unreported = false, bool variableUsedBeforeDeclaration = false)
        {
            Debug.Assert(((object)containingSymbol == null) ||
                         (containingSymbol.Kind == SymbolKind.Namespace) ||
                         (containingSymbol.Kind == SymbolKind.NamedType) ||
                         (containingSymbol.Kind == SymbolKind.ErrorType));

            Debug.Assert(name != null);
            Debug.Assert(unreported == false || errorInfo != null);

            this.name             = name;
            this.errorInfo        = errorInfo;
            this.containingSymbol = containingSymbol;
            this.arity            = arity;
            this.unreported       = unreported;
            this.VariableUsedBeforeDeclaration = variableUsedBeforeDeclaration;
            this.resultKind = LookupResultKind.Empty;
        }
Пример #42
0
        internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics)
        {
            ImmutableArray <LocalSymbol> declaredLocalsArray;
            var body        = _generateMethodBody(this, diagnostics, out declaredLocalsArray, out _lazyResultProperties);
            var compilation = compilationState.Compilation;

            _lazyReturnType = CalculateReturnType(compilation, body);

            // Can't do this until the return type has been computed.
            TypeParameterChecker.Check(this, _allTypeParameters);

            if (diagnostics.HasAnyErrors())
            {
                return;
            }

            DiagnosticsPass.IssueDiagnostics(compilation, body, diagnostics, this);
            if (diagnostics.HasAnyErrors())
            {
                return;
            }

            // Check for use-site diagnostics (e.g. missing types in the signature).
            DiagnosticInfo useSiteDiagnosticInfo = null;

            this.CalculateUseSiteDiagnostic(ref useSiteDiagnosticInfo);
            if (useSiteDiagnosticInfo != null && useSiteDiagnosticInfo.Severity == DiagnosticSeverity.Error)
            {
                diagnostics.Add(useSiteDiagnosticInfo, this.Locations[0]);
                return;
            }

            try
            {
                var declaredLocals = PooledHashSet <LocalSymbol> .GetInstance();

                try
                {
                    // Rewrite local declaration statement.
                    body = (BoundStatement)LocalDeclarationRewriter.Rewrite(
                        compilation,
                        _container,
                        declaredLocals,
                        body,
                        declaredLocalsArray,
                        diagnostics);

                    // Verify local declaration names.
                    foreach (var local in declaredLocals)
                    {
                        Debug.Assert(local.Locations.Length > 0);
                        var name = local.Name;
                        if (name.StartsWith("$", StringComparison.Ordinal))
                        {
                            diagnostics.Add(ErrorCode.ERR_UnexpectedCharacter, local.Locations[0], name[0]);
                            return;
                        }
                    }

                    // Rewrite references to placeholder "locals".
                    body = (BoundStatement)PlaceholderLocalRewriter.Rewrite(compilation, _container, declaredLocals, body, diagnostics);

                    if (diagnostics.HasAnyErrors())
                    {
                        return;
                    }
                }
                finally
                {
                    declaredLocals.Free();
                }

                var syntax            = body.Syntax;
                var statementsBuilder = ArrayBuilder <BoundStatement> .GetInstance();

                statementsBuilder.Add(body);
                // Insert an implicit return statement if necessary.
                if (body.Kind != BoundKind.ReturnStatement)
                {
                    statementsBuilder.Add(new BoundReturnStatement(syntax, RefKind.None, expressionOpt: null));
                }

                var localsSet = PooledHashSet <LocalSymbol> .GetInstance();

                try
                {
                    var localsBuilder = ArrayBuilder <LocalSymbol> .GetInstance();

                    foreach (var local in this.LocalsForBinding)
                    {
                        Debug.Assert(!localsSet.Contains(local));
                        localsBuilder.Add(local);
                        localsSet.Add(local);
                    }
                    foreach (var local in this.Locals)
                    {
                        if (localsSet.Add(local))
                        {
                            localsBuilder.Add(local);
                        }
                    }

                    body = new BoundBlock(syntax, localsBuilder.ToImmutableAndFree(), statementsBuilder.ToImmutableAndFree())
                    {
                        WasCompilerGenerated = true
                    };

                    Debug.Assert(!diagnostics.HasAnyErrors());
                    Debug.Assert(!body.HasErrors);

                    bool sawLambdas;
                    bool sawLocalFunctions;
                    bool sawAwaitInExceptionHandler;
                    ImmutableArray <SourceSpan> dynamicAnalysisSpans = ImmutableArray <SourceSpan> .Empty;
                    body = LocalRewriter.Rewrite(
                        compilation: this.DeclaringCompilation,
                        method: this,
                        methodOrdinal: _methodOrdinal,
                        containingType: _container,
                        statement: body,
                        compilationState: compilationState,
                        previousSubmissionFields: null,
                        allowOmissionOfConditionalCalls: false,
                        instrumentForDynamicAnalysis: false,
                        debugDocumentProvider: null,
                        dynamicAnalysisSpans: ref dynamicAnalysisSpans,
                        diagnostics: diagnostics,
                        sawLambdas: out sawLambdas,
                        sawLocalFunctions: out sawLocalFunctions,
                        sawAwaitInExceptionHandler: out sawAwaitInExceptionHandler);

                    Debug.Assert(!sawAwaitInExceptionHandler);
                    Debug.Assert(dynamicAnalysisSpans.Length == 0);

                    if (body.HasErrors)
                    {
                        return;
                    }

                    // Variables may have been captured by lambdas in the original method
                    // or in the expression, and we need to preserve the existing values of
                    // those variables in the expression. This requires rewriting the variables
                    // in the expression based on the closure classes from both the original
                    // method and the expression, and generating a preamble that copies
                    // values into the expression closure classes.
                    //
                    // Consider the original method:
                    // static void M()
                    // {
                    //     int x, y, z;
                    //     ...
                    //     F(() => x + y);
                    // }
                    // and the expression in the EE: "F(() => x + z)".
                    //
                    // The expression is first rewritten using the closure class and local <1>
                    // from the original method: F(() => <1>.x + z)
                    // Then lambda rewriting introduces a new closure class that includes
                    // the locals <1> and z, and a corresponding local <2>: F(() => <2>.<1>.x + <2>.z)
                    // And a preamble is added to initialize the fields of <2>:
                    //     <2> = new <>c__DisplayClass0();
                    //     <2>.<1> = <1>;
                    //     <2>.z = z;

                    // Rewrite "this" and "base" references to parameter in this method.
                    // Rewrite variables within body to reference existing display classes.
                    body = (BoundStatement)CapturedVariableRewriter.Rewrite(
                        this.GenerateThisReference,
                        compilation.Conversions,
                        _displayClassVariables,
                        body,
                        diagnostics);

                    if (body.HasErrors)
                    {
                        Debug.Assert(false, "Please add a test case capturing whatever caused this assert.");
                        return;
                    }

                    if (diagnostics.HasAnyErrors())
                    {
                        return;
                    }

                    if (sawLambdas || sawLocalFunctions)
                    {
                        var closureDebugInfoBuilder = ArrayBuilder <ClosureDebugInfo> .GetInstance();

                        var lambdaDebugInfoBuilder = ArrayBuilder <LambdaDebugInfo> .GetInstance();

                        body = LambdaRewriter.Rewrite(
                            loweredBody: body,
                            thisType: this.SubstitutedSourceMethod.ContainingType,
                            thisParameter: _thisParameter,
                            method: this,
                            methodOrdinal: _methodOrdinal,
                            substitutedSourceMethod: this.SubstitutedSourceMethod.OriginalDefinition,
                            closureDebugInfoBuilder: closureDebugInfoBuilder,
                            lambdaDebugInfoBuilder: lambdaDebugInfoBuilder,
                            slotAllocatorOpt: null,
                            compilationState: compilationState,
                            diagnostics: diagnostics,
                            assignLocals: localsSet);

                        // we don't need this information:
                        closureDebugInfoBuilder.Free();
                        lambdaDebugInfoBuilder.Free();
                    }
                }
                finally
                {
                    localsSet.Free();
                }

                // Insert locals from the original method,
                // followed by any new locals.
                var block        = (BoundBlock)body;
                var localBuilder = ArrayBuilder <LocalSymbol> .GetInstance();

                foreach (var local in this.Locals)
                {
                    Debug.Assert(!(local is EELocalSymbol) || (((EELocalSymbol)local).Ordinal == localBuilder.Count));
                    localBuilder.Add(local);
                }
                foreach (var local in block.Locals)
                {
                    if (local is EELocalSymbol oldLocal)
                    {
                        Debug.Assert(localBuilder[oldLocal.Ordinal] == oldLocal);
                        continue;
                    }
                    localBuilder.Add(local);
                }

                body = block.Update(localBuilder.ToImmutableAndFree(), block.LocalFunctions, block.Statements);
                TypeParameterChecker.Check(body, _allTypeParameters);
                compilationState.AddSynthesizedMethod(this, body);
            }
            catch (BoundTreeVisitor.CancelledByStackGuardException ex)
            {
                ex.AddAnError(diagnostics);
            }
        }
        /// <summary>
        /// Publishes a value.
        /// </summary>
        private void Publish(
            OperationContext context,
            DataValue value,
            ServiceResult error,
            Queue <MonitoredItemNotification> notifications,
            Queue <DiagnosticInfo> diagnostics)
        {
            // set semantics changed bit.
            if (m_semanticsChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetSemanticsChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetSemanticsChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_semanticsChanged = false;
            }

            // set structure changed bit.
            if (m_structureChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetStructureChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetStructureChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_structureChanged = false;
            }

            // copy data value.
            MonitoredItemNotification item = new MonitoredItemNotification();

            item.ClientHandle = m_clientHandle;
            item.Value        = value;

            // apply timestamp filter.
            if (m_timestampsToReturn != TimestampsToReturn.Server && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.ServerTimestamp = DateTime.MinValue;
            }

            if (m_timestampsToReturn != TimestampsToReturn.Source && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.SourceTimestamp = DateTime.MinValue;
            }

            notifications.Enqueue(item);

            // update diagnostic info.
            DiagnosticInfo diagnosticInfo = null;

            if (m_lastError != null)
            {
                if ((m_diagnosticsMasks & DiagnosticsMasks.OperationAll) != 0)
                {
                    diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_source.Server, context, m_lastError);
                }
            }

            diagnostics.Enqueue(diagnosticInfo);
        }
Пример #44
0
 public override Diagnostic CreateDiagnostic(DiagnosticInfo info)
 {
     return(new CSDiagnostic(info, Location.None));
 }
Пример #45
0
 private UnboundArgumentErrorTypeSymbol(string name, DiagnosticInfo errorInfo, TupleExtraData?tupleData = null)
     : base(tupleData)
 {
     _name      = name;
     _errorInfo = errorInfo;
 }
Пример #46
0
 internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet <TypeSymbol> checkedTypes)
 {
     return(_elementTypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) ||
            ((object)_baseType != null && _baseType.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) ||
            GetUnificationUseSiteDiagnosticRecursive(ref result, this.InterfacesNoUseSiteDiagnostics(), owner, ref checkedTypes));
 }
Пример #47
0
 /// <summary>
 /// Returns a unification use-site error (if any) for a symbol contained in this module
 /// that is referring to a specified <paramref name="dependentType"/>.
 /// </summary>
 /// <remarks>
 /// If an assembly referenced by this module isn't exactly matching any reference given to compilation
 /// the Assembly Manager might decide to use another reference if it matches except for version
 /// (it unifies the version with the existing reference).
 /// </remarks>
 internal abstract bool GetUnificationUseSiteDiagnostic(ref DiagnosticInfo result, TypeSymbol dependentType);
 internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet <TypeSymbol> checkedTypes)
 => OriginalDefinition.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes);
Пример #49
0
 internal static void Error(DiagnosticBag diagnostics, DiagnosticInfo info, Location location)
 {
     diagnostics.Add(new CSDiagnostic(info, location));
 }
 internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol containingSymbol, ImmutableArray <Symbol> candidateSymbols, LookupResultKind resultKind, DiagnosticInfo errorInfo, int arity, bool unreported = false)
     : this(containingSymbol, candidateSymbols[0].Name, arity, errorInfo, unreported)
 {
     this.candidateSymbols = UnwrapErrorCandidates(candidateSymbols);
     this.resultKind       = resultKind;
     Debug.Assert(candidateSymbols.IsEmpty || resultKind != LookupResultKind.Viable, "Shouldn't use LookupResultKind.Viable with candidate symbols");
 }
 internal SingleLookupResult(LookupResultKind kind, Symbol symbol, DiagnosticInfo error)
 {
     this.Kind   = kind;
     this.Symbol = symbol;
     this.Error  = error;
 }
 internal ExtendedErrorTypeSymbol(NamespaceOrTypeSymbol containingSymbol, Symbol guessSymbol, LookupResultKind resultKind, DiagnosticInfo errorInfo, bool unreported = false)
     : this(containingSymbol, ImmutableArray.Create <Symbol>(guessSymbol), resultKind, errorInfo, GetArity(guessSymbol), unreported)
 {
 }
Пример #53
0
 public override ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options)
 {
     throw new NotImplementedException();
 }
Пример #54
0
 private void PopulateHelper(BoundExpression receiverOpt, LookupResultKind resultKind, DiagnosticInfo error)
 {
     VerifyClear();
     this.Receiver   = receiverOpt;
     this.Error      = error;
     this.ResultKind = resultKind;
 }
		/// <summary>
		/// Initializes the object with a status code and a diagnostic info structure.
		/// </summary>
		public ServiceResult(StatusCode code, DiagnosticInfo diagnosticInfo, IList<string> stringTable)
		{
			m_code = (uint)code;

            if (diagnosticInfo != null)
            {
				m_namespaceUri = LookupString(stringTable, diagnosticInfo.NamespaceUri);
				m_symbolicId = LookupString(stringTable, diagnosticInfo.SymbolicId);

                string locale = LookupString(stringTable, diagnosticInfo.Locale);
                string localizedText = LookupString(stringTable, diagnosticInfo.LocalizedText);
				m_localizedText  = new LocalizedText(locale, localizedText);

                m_additionalInfo = diagnosticInfo.AdditionalInfo;

                if (!StatusCode.IsGood(diagnosticInfo.InnerStatusCode))
                {
                    m_innerResult = new ServiceResult(diagnosticInfo.InnerStatusCode, diagnosticInfo.InnerDiagnosticInfo, stringTable);
                }
            }
		}
Пример #56
0
        private PEPropertySymbol(
            PEModuleSymbol moduleSymbol,
            PENamedTypeSymbol containingType,
            PropertyDefinitionHandle handle,
            PEMethodSymbol getMethod,
            PEMethodSymbol setMethod,
            int countOfCustomModifiers,
            ParamInfo <TypeSymbol>[] propertyParams,
            MetadataDecoder metadataDecoder)
        {
            _containingType = containingType;
            var module = moduleSymbol.Module;
            PropertyAttributes      mdFlags = 0;
            BadImageFormatException mrEx    = null;

            try
            {
                module.GetPropertyDefPropsOrThrow(handle, out _name, out mdFlags);
            }
            catch (BadImageFormatException e)
            {
                mrEx = e;

                if ((object)_name == null)
                {
                    _name = string.Empty;
                }
            }

            _getMethod = getMethod;
            _setMethod = setMethod;
            _handle    = handle;

            SignatureHeader         unusedCallingConvention;
            BadImageFormatException getEx = null;
            var getMethodParams           = (object)getMethod == null ? null : metadataDecoder.GetSignatureForMethod(getMethod.Handle, out unusedCallingConvention, out getEx);
            BadImageFormatException setEx = null;
            var setMethodParams           = (object)setMethod == null ? null : metadataDecoder.GetSignatureForMethod(setMethod.Handle, out unusedCallingConvention, out setEx);

            // NOTE: property parameter names are not recorded in metadata, so we have to
            // use the parameter names from one of the indexers
            // NB: prefer setter names to getter names if both are present.
            bool isBad;

            _parameters = setMethodParams is null
                ? GetParameters(moduleSymbol, this, propertyParams, getMethodParams, getMethod.IsMetadataVirtual(), out isBad)
                : GetParameters(moduleSymbol, this, propertyParams, setMethodParams, setMethod.IsMetadataVirtual(), out isBad);

            if (getEx != null || setEx != null || mrEx != null || isBad)
            {
                _lazyUseSiteDiagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this);
            }

            var returnInfo          = propertyParams[0];
            var typeCustomModifiers = CSharpCustomModifier.Convert(returnInfo.CustomModifiers);

            if (returnInfo.IsByRef)
            {
                if (moduleSymbol.Module.HasIsReadOnlyAttribute(handle))
                {
                    _refKind = RefKind.RefReadOnly;
                }
                else
                {
                    _refKind = RefKind.Ref;
                }
            }
            else
            {
                _refKind = RefKind.None;
            }

            // CONSIDER: Can we make parameter type computation lazy?
            TypeSymbol originalPropertyType = returnInfo.Type;

            originalPropertyType = DynamicTypeDecoder.TransformType(originalPropertyType, typeCustomModifiers.Length, handle, moduleSymbol, _refKind);

            // Dynamify object type if necessary
            originalPropertyType = originalPropertyType.AsDynamicIfNoPia(_containingType);

            // We start without annotation (they will be decoded below)
            var propertyType = TypeSymbolWithAnnotations.Create(nonNullTypesContext: this, originalPropertyType, isAnnotated: false, typeCustomModifiers);

            // Decode nullable before tuple types to avoid converting between
            // NamedTypeSymbol and TupleTypeSymbol unnecessarily.
            propertyType = NullableTypeDecoder.TransformType(propertyType, handle, moduleSymbol);
            propertyType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(propertyType, handle, moduleSymbol);

            _propertyType = propertyType;

            // A property is bogus and must be accessed by calling its accessors directly if the
            // accessor signatures do not agree, both with each other and with the property,
            // or if it has parameters and is not an indexer or indexed property.
            bool callMethodsDirectly = !DoSignaturesMatch(module, metadataDecoder, propertyParams, _getMethod, getMethodParams, _setMethod, setMethodParams) ||
                                       MustCallMethodsDirectlyCore();

            if (!callMethodsDirectly)
            {
                if ((object)_getMethod != null)
                {
                    _getMethod.SetAssociatedProperty(this, MethodKind.PropertyGet);
                }

                if ((object)_setMethod != null)
                {
                    _setMethod.SetAssociatedProperty(this, MethodKind.PropertySet);
                }
            }

            if (callMethodsDirectly)
            {
                _flags |= Flags.CallMethodsDirectly;
            }

            if ((mdFlags & PropertyAttributes.SpecialName) != 0)
            {
                _flags |= Flags.IsSpecialName;
            }

            if ((mdFlags & PropertyAttributes.RTSpecialName) != 0)
            {
                _flags |= Flags.IsRuntimeSpecialName;
            }
        }
Пример #57
0
 internal override bool GetUnificationUseSiteDiagnostic(ref DiagnosticInfo result, TypeSymbol dependentType)
 {
     throw ExceptionUtilities.Unreachable;
 }
Пример #58
0
 public Diagnostic Create(DiagnosticDescriptor descriptor, DiagnosticInfo info)
 {
     return(Diagnostic.Create(descriptor, info.Location, info.Args));
 }
Пример #59
0
        internal PEEventSymbol(
            PEModuleSymbol moduleSymbol,
            PENamedTypeSymbol containingType,
            EventDefinitionHandle handle,
            PEMethodSymbol addMethod,
            PEMethodSymbol removeMethod,
            MultiDictionary<string, PEFieldSymbol> privateFieldNameToSymbols)
        {
            Debug.Assert((object)moduleSymbol != null);
            Debug.Assert((object)containingType != null);
            Debug.Assert(!handle.IsNil);
            Debug.Assert((object)addMethod != null);
            Debug.Assert((object)removeMethod != null);

            _addMethod = addMethod;
            _removeMethod = removeMethod;
            _handle = handle;
            _containingType = containingType;

            EventAttributes mdFlags = 0;
            EntityHandle eventType = default(EntityHandle);

            try
            {
                var module = moduleSymbol.Module;
                module.GetEventDefPropsOrThrow(handle, out _name, out mdFlags, out eventType);
            }
            catch (BadImageFormatException mrEx)
            {
                if ((object)_name == null)
                {
                    _name = string.Empty;
                }

                _lazyUseSiteDiagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this);

                if (eventType.IsNil)
                {
                    _eventType = new UnsupportedMetadataTypeSymbol(mrEx);
                }
            }

            TypeSymbol originalEventType = _eventType;
            if ((object)_eventType == null)
            {
                var metadataDecoder = new MetadataDecoder(moduleSymbol, containingType);
                originalEventType = metadataDecoder.GetTypeOfToken(eventType);

                const int targetSymbolCustomModifierCount = 0;
                _eventType = DynamicTypeDecoder.TransformType(originalEventType, targetSymbolCustomModifierCount, handle, moduleSymbol);
                _eventType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(_eventType, handle, moduleSymbol);
            }

            // IsWindowsRuntimeEvent checks the signatures, so we just have to check the accessors.
            bool isWindowsRuntimeEvent = IsWindowsRuntimeEvent;
            bool callMethodsDirectly = isWindowsRuntimeEvent
                ? !DoModifiersMatch(_addMethod, _removeMethod)
                : !DoSignaturesMatch(moduleSymbol, originalEventType, _addMethod, _removeMethod);

            if (callMethodsDirectly)
            {
                _flags |= Flags.CallMethodsDirectly;
            }
            else
            {
                _addMethod.SetAssociatedEvent(this, MethodKind.EventAdd);
                _removeMethod.SetAssociatedEvent(this, MethodKind.EventRemove);

                PEFieldSymbol associatedField = GetAssociatedField(privateFieldNameToSymbols, isWindowsRuntimeEvent);
                if ((object)associatedField != null)
                {
                    _associatedFieldOpt = associatedField;
                    associatedField.SetAssociatedEvent(this);
                }
            }

            if ((mdFlags & EventAttributes.SpecialName) != 0)
            {
                _flags |= Flags.IsSpecialName;
            }

            if ((mdFlags & EventAttributes.RTSpecialName) != 0)
            {
                _flags |= Flags.IsRuntimeSpecialName;
            }
        }
Пример #60
0
        /// <summary>
        /// Processes acknowledgements for previously published messages.
        /// </summary>
        public void Acknowledge(
            OperationContext context,
            SubscriptionAcknowledgementCollection subscriptionAcknowledgements,
            out StatusCodeCollection acknowledgeResults,
            out DiagnosticInfoCollection acknowledgeDiagnosticInfos)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (subscriptionAcknowledgements == null)
            {
                throw new ArgumentNullException("subscriptionAcknowledgements");
            }

            lock (m_lock)
            {
                bool diagnosticsExist = false;
                acknowledgeResults         = new StatusCodeCollection(subscriptionAcknowledgements.Count);
                acknowledgeDiagnosticInfos = new DiagnosticInfoCollection(subscriptionAcknowledgements.Count);

                for (int ii = 0; ii < subscriptionAcknowledgements.Count; ii++)
                {
                    SubscriptionAcknowledgement acknowledgement = subscriptionAcknowledgements[ii];

                    bool found = false;

                    for (int jj = 0; jj < m_queuedSubscriptions.Count; jj++)
                    {
                        QueuedSubscription subscription = m_queuedSubscriptions[jj];

                        if (subscription.Subscription.Id == acknowledgement.SubscriptionId)
                        {
                            ServiceResult result = subscription.Subscription.Acknowledge(context, acknowledgement.SequenceNumber);

                            if (ServiceResult.IsGood(result))
                            {
                                acknowledgeResults.Add(StatusCodes.Good);

                                if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
                                {
                                    acknowledgeDiagnosticInfos.Add(null);
                                }
                            }
                            else
                            {
                                acknowledgeResults.Add(result.Code);

                                if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
                                {
                                    DiagnosticInfo diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_server, context, result);
                                    acknowledgeDiagnosticInfos.Add(diagnosticInfo);
                                    diagnosticsExist = true;
                                }
                            }

                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        ServiceResult result = new ServiceResult(StatusCodes.BadSubscriptionIdInvalid);
                        acknowledgeResults.Add(result.Code);

                        if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
                        {
                            DiagnosticInfo diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_server, context, result);
                            acknowledgeDiagnosticInfos.Add(diagnosticInfo);
                            diagnosticsExist = true;
                        }
                    }
                }

                if (!diagnosticsExist)
                {
                    acknowledgeDiagnosticInfos.Clear();
                }
            }
        }