internal DeclarationAnalysisData GetOrComputeDeclarationAnalysisData(
                SyntaxReference declaration,
                Func<Func<DeclarationAnalysisData>, DeclarationAnalysisData> computeDeclarationAnalysisData,
                bool cacheAnalysisData)
            {
                if (!cacheAnalysisData)
                {
                    return computeDeclarationAnalysisData(_declarationAnalysisDataPool.Allocate);
                }

                DeclarationAnalysisData data;
                lock (_declarationAnalysisDataMap)
                {
                    if (_declarationAnalysisDataMap.TryGetValue(declaration, out data))
                    {
                        return data;
                    }
                }

                data = computeDeclarationAnalysisData(_declarationAnalysisDataPool.Allocate);

                lock (_declarationAnalysisDataMap)
                {
                    _declarationAnalysisDataMap[declaration] = data;
                }

                return data;
            }
 internal SourceStrictComplexParameterSymbol(
     DiagnosticBag diagnostics,
     Binder binder,
     Symbol owner,
     int ordinal,
     TypeSymbol parameterType,
     RefKind refKind,
     string name,
     ImmutableArray<Location> locations,
     SyntaxReference syntaxRef,
     ConstantValue defaultSyntaxValue,
     bool isParams,
     bool isExtensionMethodThis)
 : base(
     owner: owner,
     ordinal: ordinal,
     parameterType: parameterType,
     refKind: refKind,
     name: name,
     locations: locations,
     syntaxRef: syntaxRef,
     defaultSyntaxValue: defaultSyntaxValue,
     isParams: isParams,
     isExtensionMethodThis: isExtensionMethodThis)
 {
     _tempBinder = binder;
     var unused = GetAttributesBag(diagnostics);
     _lazyDefaultSyntaxValue = MakeDefaultExpression(diagnostics, binder);
     _tempBinder = null; // no need to keep it around anymore, just uses up a lot of memory
 }
 internal TypeParameterBuilder(SyntaxReference syntaxRef, SourceNamedTypeSymbol owner, Location location)
 {
     this.syntaxRef = syntaxRef;
     Debug.Assert(syntaxRef.GetSyntax().IsKind(SyntaxKind.TypeParameter));
     this.owner = owner;
     this.location = location;
 }
        internal SourceAttributeData(
            SyntaxReference applicationNode,
            NamedTypeSymbol attributeClass,
            MethodSymbol attributeConstructor,
            ImmutableArray<TypedConstant> constructorArguments,
            ImmutableArray<int> constructorArgumentsSourceIndices,
            ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments,
            bool hasErrors,
            bool isConditionallyOmitted)
        {
            Debug.Assert(!isConditionallyOmitted || (object)attributeClass != null && attributeClass.IsConditional);
            Debug.Assert(!constructorArguments.IsDefault);
            Debug.Assert(!namedArguments.IsDefault);
            Debug.Assert(constructorArgumentsSourceIndices.IsDefault ||
                constructorArgumentsSourceIndices.Any() && constructorArgumentsSourceIndices.Length == constructorArguments.Length);

            this.attributeClass = attributeClass;
            this.attributeConstructor = attributeConstructor;
            this.constructorArguments = constructorArguments;
            this.constructorArgumentsSourceIndices = constructorArgumentsSourceIndices;
            this.namedArguments = namedArguments;
            this.isConditionallyOmitted = isConditionallyOmitted;
            this.hasErrors = hasErrors;
            this.applicationNode = applicationNode;
        }
        public FieldOrPropertyInitializer(FieldSymbol fieldOpt, SyntaxNode syntax, int precedingInitializersLength)
        {
            Debug.Assert(syntax.IsKind(SyntaxKind.EqualsValueClause) && fieldOpt != null || syntax is StatementSyntax);

            FieldOpt = fieldOpt;
            Syntax = syntax.GetReference();
            PrecedingInitializersLength = precedingInitializersLength;
        }
 protected SingleNamespaceOrTypeDeclaration(
     string name,
     SyntaxReference syntaxReference,
     SourceLocation nameLocation)
     : base(name)
 {
     this.syntaxReference = syntaxReference;
     this.nameLocation = nameLocation;
 }
Exemplo n.º 7
0
 protected SingleNamespaceDeclaration(
     string name,
     SyntaxReference syntaxReference,
     SourceLocation nameLocation,
     ImmutableArray<SingleNamespaceOrTypeDeclaration> children)
     : base(name, syntaxReference, nameLocation)
 {
     this.children = children;
 }
Exemplo n.º 8
0
 public SourceEventAccessorSymbol(
     SourceEventSymbol @event,
     SyntaxReference syntaxReference,
     SyntaxReference blockSyntaxReference,
     ImmutableArray<Location> locations)
     : base(@event.containingType, syntaxReference, blockSyntaxReference, locations)
 {
     this.@event = @event;
 }
Exemplo n.º 9
0
 internal SourceMemberFieldSymbol(
     SourceMemberContainerTypeSymbol containingType,
     DeclarationModifiers modifiers,
     string name,
     SyntaxReference syntax, 
     Location location)
     : base(containingType, name, syntax, location)
 {
     _modifiers = modifiers;
 }
 internal SourceAttributeData(SyntaxReference applicationNode, NamedTypeSymbol attributeClass, MethodSymbol attributeConstructor, bool hasErrors)
     : this(
     applicationNode,
     attributeClass,
     attributeConstructor,
     constructorArguments: ImmutableArray<TypedConstant>.Empty,
     constructorArgumentsSourceIndices: default(ImmutableArray<int>),
     namedArguments: ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty,
     hasErrors: hasErrors,
     isConditionallyOmitted: false)
 {
 }
Exemplo n.º 11
0
 /// <summary>
 /// Script class declaration constructor.
 /// </summary>
 internal ImplicitTypeDeclaration(SyntaxReference memberContainer, ReadOnlyArray<SingleTypeDeclaration> children, ISet<string> memberNames, string name) :
     base(
     kind: DeclarationKind.Class,
     name: name,
     arity: 0,
     modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed,
     syntaxReference: memberContainer,
     nameLocation: new SourceLocation(memberContainer),
     memberNames: memberNames,
     children: children)
 {
 }
Exemplo n.º 12
0
 internal RetargetingAttributeData(
     SyntaxReference applicationNode,
     NamedTypeSymbol attributeClass,
     MethodSymbol attributeConstructor,
     ImmutableArray<TypedConstant> constructorArguments,
     ImmutableArray<int> constructorArgumentsSourceIndices,
     ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments,
     bool hasErrors,
     bool isConditionallyOmitted)
     : base(applicationNode, attributeClass, attributeConstructor, constructorArguments, constructorArgumentsSourceIndices, namedArguments, hasErrors, isConditionallyOmitted)
 {
 }
Exemplo n.º 13
0
        protected SourceFieldSymbol(SourceMemberContainerTypeSymbol containingType, string name, SyntaxReference syntax, Location location)
        {
            Debug.Assert((object)containingType != null);
            Debug.Assert(name != null);
            Debug.Assert(syntax != null);
            Debug.Assert(location != null);

            this.containingType = containingType;
            this.name = name;
            this.syntaxReference = syntax;
            this.location = location;
        }
Exemplo n.º 14
0
 internal GlobalExpressionVariable(
     SourceMemberContainerTypeSymbol containingType,
     DeclarationModifiers modifiers,
     TypeSyntax typeSyntax,
     string name,
     SyntaxReference syntax,
     Location location)
     : base(containingType, modifiers, name, syntax, location)
 {
     Debug.Assert(DeclaredAccessibility == Accessibility.Private);
     _typeSyntax = typeSyntax.GetReference();
 }
        protected override SyntaxNode Translate(SyntaxReference reference, CancellationToken cancellationToken)
        {
            var node = (CSharpSyntaxNode)reference.GetSyntax(cancellationToken);

            // If the node is a name syntax, it's something like "X" or "X.Y" in :
            //    namespace X.Y.Z
            // We want to return the full NamespaceDeclarationSyntax.
            while (node is NameSyntax)
            {
                node = node.Parent;
            }

            Debug.Assert(node is CompilationUnitSyntax || node is NamespaceDeclarationSyntax);

            return node;
        }
        public RootSingleNamespaceDeclaration(
            bool hasUsings,
            bool hasExternAliases,
            SyntaxReference treeNode,
            ImmutableArray<SingleNamespaceOrTypeDeclaration> children,
            ImmutableArray<ReferenceDirective> referenceDirectives,
            bool hasAssemblyAttributes)
            : base(string.Empty,
                   treeNode,
                   nameLocation: new SourceLocation(treeNode),
                   children: children)
        {
            Debug.Assert(!referenceDirectives.IsDefault);

            _referenceDirectives = referenceDirectives;
            _hasAssemblyAttributes = hasAssemblyAttributes;
            _hasUsings = hasUsings;
            _hasExternAliases = hasExternAliases;
        }
Exemplo n.º 17
0
        public static EvaluatedConstant EvaluateFieldConstant(this FieldSymbol symbol, SyntaxReference equalsValueNodeRef, ConstantFieldsInProgress inProgress)
        {
            Debug.Assert(inProgress != null);
            var diagnostics = DiagnosticBag.GetInstance();
            try
            {
                ConstantValue value;
                if (inProgress.Contains(symbol))
                {
                    var errorField = inProgress.ErrorField;
                    diagnostics.Add(ErrorCode.ERR_CircConstValue, errorField.Locations[0], errorField);
                    value = Roslyn.Compilers.ConstantValue.Bad;
                }
                else
                {
                    var compilation = ((SourceAssemblySymbol)symbol.ContainingAssembly).Compilation;
                    var binderFactory = compilation.GetBinderFactory(equalsValueNodeRef.SyntaxTree);

                    var newInProgress = inProgress.Add(symbol);

                    var equalsValueNode = (EqualsValueClauseSyntax)equalsValueNodeRef.GetSyntax();

                    var binder = binderFactory.GetBinder(equalsValueNode);
                    var inProgressBinder = new ConstantFieldsInProgressBinder(newInProgress, binder);

                    // CONSIDER: Compiler.BindFieldInitializer will make this same call on this same syntax node
                    // to determine the bound value for itself.  We expect this binding to be fairly cheap 
                    // (since constants tend to be simple) and it should only happen twice (regardless of the
                    // number of references to this constant).  If this becomes a performance bottleneck,
                    // the re-binding can be eliminated by caching the BoundNode on this SourceFieldSymbol and
                    // checking for a cached value before binding (here and in Compiler.BindFieldInitializer).
                    var boundValue = inProgressBinder.BindVariableInitializer(equalsValueNode, symbol.Type, diagnostics);
                    var initValueNodeLocation = inProgressBinder.Location(equalsValueNode.Value);

                    value = ConstantValueUtils.GetAndValidateConstantValue(boundValue, symbol, symbol.Type, initValueNodeLocation, diagnostics);
                }
                return new EvaluatedConstant(value, diagnostics.Seal());
            }
            finally
            {
                diagnostics.Free();
            }
        }
Exemplo n.º 18
0
        // TODO: CLSCompliantAttribute

        internal SourceEventSymbol(
            SourceMemberContainerTypeSymbol containingType,
            CSharpSyntaxNode syntax,
            SyntaxTokenList modifiers,
            ExplicitInterfaceSpecifierSyntax interfaceSpecifierSyntaxOpt,
            SyntaxToken nameTokenSyntax,
            DiagnosticBag diagnostics)
        {
            _location = nameTokenSyntax.GetLocation();

            this.containingType = containingType;

            _syntaxRef = syntax.GetReference();

            var isExplicitInterfaceImplementation = interfaceSpecifierSyntaxOpt != null;
            bool modifierErrors;
            _modifiers = MakeModifiers(modifiers, isExplicitInterfaceImplementation, _location, diagnostics, out modifierErrors);
            this.CheckAccessibility(_location, diagnostics);
        }
Exemplo n.º 19
0
 public static SingleNamespaceDeclaration Create(
     string name,
     bool hasUsings,
     bool hasExternAliases,
     SyntaxReference syntaxReference,
     SourceLocation nameLocation,
     ImmutableArray<SingleNamespaceOrTypeDeclaration> children)
 {
     // By far the most common case is "no usings and no extern aliases", so optimize for
     // that to minimize space. The other cases are not frequent enough to warrant their own
     // custom types.
     if (!hasUsings && !hasExternAliases)
     {
         return new SingleNamespaceDeclaration(name, syntaxReference, nameLocation, children);
     }
     else
     {
         return new SingleNamespaceDeclarationEx(name, hasUsings, hasExternAliases, syntaxReference, nameLocation, children);
     }
 }
        internal SourceComplexParameterSymbol(
            Symbol owner,
            int ordinal,
            TypeSymbol parameterType,
            RefKind refKind,
            ImmutableArray<CustomModifier> customModifiers,
            bool hasByRefBeforeCustomModifiers,
            string name,
            ImmutableArray<Location> locations,
            SyntaxReference syntaxRef,
            ConstantValue defaultSyntaxValue,
            bool isParams,
            bool isExtensionMethodThis)
            : base(owner, parameterType, ordinal, refKind, name, locations)
        {
            Debug.Assert((syntaxRef == null) || (syntaxRef.GetSyntax().IsKind(SyntaxKind.Parameter)));
            Debug.Assert(!customModifiers.IsDefault);

            _lazyHasOptionalAttribute = ThreeState.Unknown;
            _syntaxRef = syntaxRef;

            if (isParams)
            {
                _parameterSyntaxKind |= ParameterSyntaxKind.ParamsParameter;
            }

            if (isExtensionMethodThis)
            {
                _parameterSyntaxKind |= ParameterSyntaxKind.ExtensionThisParameter;
            }

            var parameterSyntax = this.CSharpSyntaxNode;
            if (parameterSyntax != null && parameterSyntax.Default != null)
            {
                _parameterSyntaxKind |= ParameterSyntaxKind.DefaultParameter;
            }

            _lazyDefaultSyntaxValue = defaultSyntaxValue;
            _customModifiers = customModifiers;
            _hasByRefBeforeCustomModifiers = hasByRefBeforeCustomModifiers;
        }
Exemplo n.º 21
0
        protected SynthesizedMethodBaseSymbol(NamedTypeSymbol containingType,
                                              MethodSymbol baseMethod,
                                              SyntaxReference syntaxReference,
                                              SyntaxReference blockSyntaxReference,
                                              Location location,
                                              string name,
                                              DeclarationModifiers declarationModifiers)
            : base(containingType, syntaxReference, blockSyntaxReference, location)
        {
            Debug.Assert((object)containingType != null);
            Debug.Assert((object)baseMethod != null);

            this.BaseMethod = baseMethod;
            _name = name;

            this.MakeFlags(
                methodKind: MethodKind.Ordinary,
                declarationModifiers: declarationModifiers,
                returnsVoid: baseMethod.ReturnsVoid,
                isExtensionMethod: false,
                isMetadataVirtualIgnoringModifiers: false);
        }
        public SemanticModel SemanticModel(SyntaxReference reference)
        {
            lock (this)
            {
                var semanticModel = _semanticModel;
                if (semanticModel == null && _lazySemanticModel != null)
                {
                    _semanticModel = semanticModel = _lazySemanticModel.Value;
                    _lazySemanticModel = null;
                }
                if (semanticModel == null && _weakModel != null)
                {
                    _weakModel.TryGetTarget(out semanticModel);
                }
                if (semanticModel == null || semanticModel.SyntaxTree != reference.SyntaxTree)
                {
                    semanticModel = Compilation.GetSemanticModel(reference.SyntaxTree);
                    _weakModel = new WeakReference<SemanticModel>(semanticModel);
                }

                return semanticModel;
            }
        }
Exemplo n.º 23
0
        internal SynthesizedClosureMethod(
            NamedTypeSymbol containingType,
            ImmutableArray <SynthesizedClosureEnvironment> structEnvironments,
            ClosureKind closureKind,
            MethodSymbol topLevelMethod,
            DebugId topLevelMethodId,
            MethodSymbol originalMethod,
            SyntaxReference blockSyntax,
            DebugId lambdaId,
            DiagnosticBag diagnostics)
            : base(containingType,
                   originalMethod,
                   blockSyntax,
                   originalMethod.DeclaringSyntaxReferences[0].GetLocation(),
                   originalMethod is LocalFunctionSymbol
                    ? MakeName(topLevelMethod.Name, originalMethod.Name, topLevelMethodId, closureKind, lambdaId)
                    : MakeName(topLevelMethod.Name, topLevelMethodId, closureKind, lambdaId),
                   MakeDeclarationModifiers(closureKind, originalMethod))
        {
            _topLevelMethod = topLevelMethod;
            ClosureKind     = closureKind;
            LambdaId        = lambdaId;

            TypeMap typeMap;
            ImmutableArray <TypeParameterSymbol> typeParameters;
            ImmutableArray <TypeParameterSymbol> constructedFromTypeParameters;

            var lambdaFrame = ContainingType as SynthesizedClosureEnvironment;

            switch (closureKind)
            {
            case ClosureKind.Singleton:   // all type parameters on method (except the top level method's)
            case ClosureKind.General:     // only lambda's type parameters on method (rest on class)
                Debug.Assert((object)lambdaFrame != null);
                typeMap = lambdaFrame.TypeMap.WithConcatAlphaRename(
                    originalMethod,
                    this,
                    out typeParameters,
                    out constructedFromTypeParameters,
                    lambdaFrame.OriginalContainingMethodOpt);
                break;

            case ClosureKind.ThisOnly:     // all type parameters on method
            case ClosureKind.Static:
                Debug.Assert((object)lambdaFrame == null);
                typeMap = TypeMap.Empty.WithConcatAlphaRename(
                    originalMethod,
                    this,
                    out typeParameters,
                    out constructedFromTypeParameters,
                    stopAt: null);
                break;

            default:
                throw ExceptionUtilities.UnexpectedValue(closureKind);
            }

            if (!structEnvironments.IsDefaultOrEmpty && typeParameters.Length != 0)
            {
                var constructedStructClosures = ArrayBuilder <NamedTypeSymbol> .GetInstance();

                foreach (var env in structEnvironments)
                {
                    NamedTypeSymbol constructed;
                    if (env.Arity == 0)
                    {
                        constructed = env;
                    }
                    else
                    {
                        var originals = env.ConstructedFromTypeParameters;
                        var newArgs   = typeMap.SubstituteTypeParameters(originals);
                        constructed = env.Construct(newArgs);
                    }
                    constructedStructClosures.Add(constructed);
                }
                _structEnvironments = constructedStructClosures.ToImmutableAndFree();
            }
            else
            {
                _structEnvironments = ImmutableArray <NamedTypeSymbol> .CastUp(structEnvironments);
            }

            AssignTypeMapAndTypeParameters(typeMap, typeParameters);
        }
Exemplo n.º 24
0
 public AnalyserItem(string message, SyntaxReference nodeReference)
 {
     this.Message       = message;
     this.NodeReference = nodeReference;
 }
Exemplo n.º 25
0
 public SingleNamespaceDeclarationEx(string name, bool hasUsings, bool hasExternAliases, SyntaxReference syntaxReference, SourceLocation nameLocation, ImmutableArray <SingleNamespaceOrTypeDeclaration> children) : base(name, syntaxReference, nameLocation, children)
 {
     this.hasUsings        = hasUsings;
     this.hasExternAliases = hasExternAliases;
 }
Exemplo n.º 26
0
        protected SourceFieldSymbolWithSyntaxReference(SourceMemberContainerTypeSymbol containingType, string name, SyntaxReference syntax, Location location)
            : base(containingType)
        {
            Debug.Assert(name != null);
            Debug.Assert(syntax != null);
            Debug.Assert(location != null);

            _name = name;
            _syntaxReference = syntax;
            _location = location;
        }
 protected TranslationSyntaxReference(SyntaxReference reference)
 {
     _reference = reference;
 }
Exemplo n.º 28
0
        private JToken GetJsonOutput(IEnumerable <MethodWrapper> invocations, Stack <MethodWrapper> invocationStack = null)
        {
            var rootInvocations = new JArray();

            if (invocationStack == null)
            {
                invocationStack = new Stack <MethodWrapper>();
            }

            foreach (var invocation in invocations)
            {
                var jInvocation = new JObject();

                var method = invocation.Method;
                if (method.IsGenericMethod)
                {
                    method = method.ConstructedFrom;
                }

                var kind = invocation.RegularExpressions.Length > 0 ?
                           "When" :
                           method.DeclaredAccessibility.ToString();

                jInvocation.Add("Kind", kind);
                jInvocation.Add("Signature", $"{method.ToDisplayString()}, {method.ContainingAssembly.Name}");

                if (invocation.RegularExpressions.Length > 0)
                {
                    jInvocation.Add("RegularExpressions", new JArray(invocation.RegularExpressions));
                }

                var interfaceDefinitions = method.ContainingType
                                           .AllInterfaces
                                           .SelectMany(@interface => @interface.GetMembers().OfType <IMethodSymbol>())
                                           .Where(m => method.Equals(method.ContainingType.FindImplementationForInterfaceMember(m)))
                                           .Select(m => $"{m.ToDisplayString()}, {m.ContainingAssembly.Name}")
                                           .ToList();
                if (interfaceDefinitions.Any())
                {
                    jInvocation.Add("InterfaceDefinitions", new JArray(interfaceDefinitions));
                }

                if (invocation.AutomationDeclaringType != null && !string.IsNullOrWhiteSpace(invocation.AutomationTargetMethodName))
                {
                    var childInvocations = invocation.Invocations.Flatten(i => i.Invocations);

                    List <MethodWrapper> automationTargets = new List <MethodWrapper>();
                    if (invocation.AutomationTargetOverloadHandling == OverloadHandling.First)
                    {
                        automationTargets.Add(childInvocations.FirstOrDefault(i => invocation.AutomationDeclaringType.GetComparableSyntax().Equals(i.Method.ContainingType.GetComparableSyntax()) &&
                                                                              i.Method.Name.Equals(invocation.AutomationTargetMethodName, StringComparison.InvariantCulture)));
                    }
                    else if (invocation.AutomationTargetOverloadHandling == OverloadHandling.Last)
                    {
                        automationTargets.Add(childInvocations.LastOrDefault(i => invocation.AutomationDeclaringType.GetComparableSyntax().Equals(i.Method.ContainingType.GetComparableSyntax()) &&
                                                                             i.Method.Name.Equals(invocation.AutomationTargetMethodName, StringComparison.InvariantCulture)));
                    }
                    else
                    {
                        automationTargets.AddRange(childInvocations.Where(i => invocation.AutomationDeclaringType.GetComparableSyntax().Equals(i.Method.ContainingType.GetComparableSyntax()) &&
                                                                          i.Method.Name.Equals(invocation.AutomationTargetMethodName, StringComparison.InvariantCulture)));
                    }

                    if (automationTargets.All(target => target != null))
                    {
                        JArray jAutomationTargets = new JArray();
                        automationTargets.Select(target => (JToken)$"{target.Method.ToDisplayString()}, {target.Method.ContainingAssembly.Name}").ToList().ForEach(jAutomationTargets.Add);
                        jInvocation.Add("AutomationTargets", jAutomationTargets);
                    }
                    else
                    {
                        jInvocation.Add("ErrorCode", "UnresolvedAutomationTarget");
                        jInvocation.Add("ErrorArguments", new JArray(invocation.AutomationDeclaringType.ToString(), invocation.AutomationTargetMethodName));
                    }
                }

                SyntaxReference methodDeclaration = method.GetComparableSyntax();
                if (methodDeclaration != null && _context.SpecifcationsProject.GetDocument(methodDeclaration.SyntaxTree) == null)
                {
                    jInvocation.Add("Local", true);
                }

                if (!invocationStack.Contains(invocation))
                {
                    invocationStack.Push(invocation);
                    jInvocation.Add("Invocations", GetJsonOutput(invocation.Invocations, invocationStack));
                    invocationStack.Pop();
                }
                else
                {
                    jInvocation.Add("Note", "Recursive");
                }

                rootInvocations.Add(jInvocation);
            }

            return(rootInvocations);
        }
Exemplo n.º 29
0
 /// <summary>
 /// Marks the given symbol declaration as fully analyzed for the given analyzer.
 /// </summary>
 public void MarkDeclarationComplete(SyntaxReference decl, DiagnosticAnalyzer analyzer)
 {
     GetAnalyzerState(analyzer).MarkDeclarationComplete(decl);
 }
Exemplo n.º 30
0
 public Reference(CountedSyntaxTree countedSyntaxTree, SyntaxReference syntaxReference)
 {
     this.countedSyntaxTree = countedSyntaxTree;
     this.underlyingSyntaxReference = syntaxReference;
 }
Exemplo n.º 31
0
        protected SourceUserDefinedOperatorSymbolBase(
            MethodKind methodKind,
            string name,
            SourceMemberContainerTypeSymbol containingType,
            Location location,
            SyntaxReference syntaxReference,
            SyntaxReference bodySyntaxReference,
            SyntaxTokenList modifiersSyntax,
            DiagnosticBag diagnostics,
            bool isExpressionBodied) :
            base(containingType, syntaxReference, bodySyntaxReference, location)
        {
            _name = name;
            _isExpressionBodied = isExpressionBodied;

            var defaultAccess    = DeclarationModifiers.Private;
            var allowedModifiers =
                DeclarationModifiers.AccessibilityMask |
                DeclarationModifiers.Static |
                DeclarationModifiers.Extern |
                DeclarationModifiers.Unsafe;

            bool modifierErrors;
            var  declarationModifiers = ModifierUtils.MakeAndCheckNontypeMemberModifiers(
                modifiersSyntax, defaultAccess, allowedModifiers, location, diagnostics, out modifierErrors);

            this.CheckUnsafeModifier(declarationModifiers, diagnostics);

            // We will bind the formal parameters and the return type lazily. For now,
            // assume that the return type is non-void; when we do the lazy initialization
            // of the parameters and return type we will update the flag if necessary.

            this.MakeFlags(methodKind, declarationModifiers, returnsVoid: false, isExtensionMethod: false);

            if (this.ContainingType.IsInterface)
            {
                // If we have an operator in an interface, we already have reported that fact as
                // an error. No need to cascade the error further.
                return;
            }

            if (this.ContainingType.IsStatic)
            {
                // Similarly if we're in a static class, though we have not reported it yet.

                // CS0715: '{0}': static classes cannot contain user-defined operators
                diagnostics.Add(ErrorCode.ERR_OperatorInStaticClass, location, this);
                return;
            }

            // SPEC: An operator declaration must include both a public and a
            // SPEC: static modifier
            if (this.DeclaredAccessibility != Accessibility.Public || !this.IsStatic)
            {
                // CS0558: User-defined operator '...' must be declared static and public
                diagnostics.Add(ErrorCode.ERR_OperatorsMustBeStatic, this.Locations[0], this);
            }

            // SPEC: Because an external operator provides no actual implementation,
            // SPEC: its operator body consists of a semicolon. For expression-bodied
            // SPEC: operators, the body is an expression. For all other operators,
            // SPEC: the operator body consists of a block...
            if (bodySyntaxReference != null && IsExtern)
            {
                diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this);
            }
            else if (bodySyntaxReference == null && !IsExtern && !IsAbstract && !IsPartial)
            {
                // Do not report that the body is missing if the operator is marked as
                // partial or abstract; we will already have given an error for that so
                // there's no need to "cascade" the error.
                diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this);
            }

            // SPEC: It is an error for the same modifier to appear multiple times in an
            // SPEC: operator declaration.
            var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers);

            if (info != null)
            {
                diagnostics.Add(info, location);
            }
        }
 public FieldInitializers(SyntaxReference typeDeclarationSyntax, ImmutableArray<FieldInitializer> initializers)
 {
     Debug.Assert(!initializers.IsDefaultOrEmpty);
     TypeDeclarationSyntax = typeDeclarationSyntax;
     Initializers = initializers;
 }
Exemplo n.º 33
0
        // CONSIDER: if the parameters were computed lazily, ParameterCount could be overridden to fall back on the syntax (as in SourceMemberMethodSymbol).

        private SourcePropertySymbol(
            SourceMemberContainerTypeSymbol containingType,
            Binder bodyBinder,
            BasePropertyDeclarationSyntax syntax,
            string name,
            Location location,
            DiagnosticBag diagnostics)
        {
            // This has the value that IsIndexer will ultimately have, once we've populated the fields of this object.
            bool isIndexer = syntax.Kind() == SyntaxKind.IndexerDeclaration;
            var interfaceSpecifier = GetExplicitInterfaceSpecifier(syntax);
            bool isExplicitInterfaceImplementation = (interfaceSpecifier != null);

            _location = location;
            _containingType = containingType;
            _syntaxRef = syntax.GetReference();

            SyntaxTokenList modifiers = syntax.Modifiers;
            bodyBinder = bodyBinder.WithUnsafeRegionIfNecessary(modifiers);
            bodyBinder = bodyBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);

            bool modifierErrors;
            _modifiers = MakeModifiers(modifiers, isExplicitInterfaceImplementation, isIndexer, location, diagnostics, out modifierErrors);
            this.CheckAccessibility(location, diagnostics);

            this.CheckModifiers(location, isIndexer, diagnostics);

            if (isIndexer && !isExplicitInterfaceImplementation)
            {
                // Evaluate the attributes immediately in case the IndexerNameAttribute has been applied.
                // NOTE: we want IsExplicitInterfaceImplementation, IsOverride, Locations, and the syntax reference
                // to be initialized before we pass this symbol to LoadCustomAttributes.

                // CONSIDER: none of the information from this early binding pass is cached.  Everything will
                // be re-bound when someone calls GetAttributes.  If this gets to be a problem, we could
                // always use the real attribute bag of this symbol and modify LoadAndValidateAttributes to
                // handle partially filled bags.
                CustomAttributesBag<CSharpAttributeData> temp = null;
                LoadAndValidateAttributes(OneOrMany.Create(this.CSharpSyntaxNode.AttributeLists), ref temp, earlyDecodingOnly: true);
                if (temp != null)
                {
                    Debug.Assert(temp.IsEarlyDecodedWellKnownAttributeDataComputed);
                    var propertyData = (PropertyEarlyWellKnownAttributeData)temp.EarlyDecodedWellKnownAttributeData;
                    if (propertyData != null)
                    {
                        _sourceName = propertyData.IndexerName;
                    }
                }
            }

            string aliasQualifierOpt;
            string memberName = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, interfaceSpecifier, name, diagnostics, out _explicitInterfaceType, out aliasQualifierOpt);
            _sourceName = _sourceName ?? memberName; //sourceName may have been set while loading attributes
            _name = isIndexer ? ExplicitInterfaceHelpers.GetMemberName(WellKnownMemberNames.Indexer, _explicitInterfaceType, aliasQualifierOpt) : _sourceName;
            _isExpressionBodied = false;

            bool hasAccessorList = syntax.AccessorList != null;
            var propertySyntax = syntax as PropertyDeclarationSyntax;
            var arrowExpression = propertySyntax != null
                ? propertySyntax.ExpressionBody
                : ((IndexerDeclarationSyntax)syntax).ExpressionBody;
            bool hasExpressionBody = arrowExpression != null;
            bool hasInitializer = !isIndexer && propertySyntax.Initializer != null;

            bool notRegularProperty = (!IsAbstract && !IsExtern && !isIndexer && hasAccessorList);
            AccessorDeclarationSyntax getSyntax = null;
            AccessorDeclarationSyntax setSyntax = null;
            if (hasAccessorList)
            {
                foreach (var accessor in syntax.AccessorList.Accessors)
                {
                    if (accessor.Kind() == SyntaxKind.GetAccessorDeclaration &&
                        (getSyntax == null || getSyntax.Keyword.Span.IsEmpty))
                    {
                        getSyntax = accessor;
                    }
                    else if (accessor.Kind() == SyntaxKind.SetAccessorDeclaration &&
                        (setSyntax == null || setSyntax.Keyword.Span.IsEmpty))
                    {
                        setSyntax = accessor;
                    }
                    else
                    {
                        continue;
                    }

                    if (accessor.Body != null)
                    {
                        notRegularProperty = false;
                    }
                }
            }
            else
            {
                notRegularProperty = false;
            }

            if (hasInitializer)
            {
                CheckInitializer(hasExpressionBody, notRegularProperty, location, diagnostics);
            }

            if (notRegularProperty || hasInitializer)
            {
                var hasGetSyntax = getSyntax != null;
                _isAutoProperty = notRegularProperty && hasGetSyntax;
                bool isReadOnly = hasGetSyntax && setSyntax == null;

                if (_isAutoProperty || hasInitializer)
                {
                    if (_isAutoProperty)
                    {
                        //issue a diagnostic if the compiler generated attribute ctor is not found.
                        Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(bodyBinder.Compilation,
                        WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, diagnostics, syntax: syntax);
                    }

                    string fieldName = GeneratedNames.MakeBackingFieldName(_sourceName);
                    _backingField = new SynthesizedBackingFieldSymbol(this,
                                                                          fieldName,
                                                                          isReadOnly,
                                                                          this.IsStatic,
                                                                          hasInitializer);
                }

                if (notRegularProperty)
                {
                    Binder.CheckFeatureAvailability(location, 
                                                    isReadOnly ? MessageID.IDS_FeatureReadonlyAutoImplementedProperties : 
                                                                 MessageID.IDS_FeatureAutoImplementedProperties, 
                                                    diagnostics);
                }
            }

            PropertySymbol explicitlyImplementedProperty = null;
            _typeCustomModifiers = ImmutableArray<CustomModifier>.Empty;

            // The runtime will not treat the accessors of this property as overrides or implementations
            // of those of another property unless both the signatures and the custom modifiers match.
            // Hence, in the case of overrides and *explicit* implementations, we need to copy the custom
            // modifiers that are in the signatures of the overridden/implemented property accessors.
            // (From source, we know that there can only be one overridden/implemented property, so there
            // are no conflicts.)  This is unnecessary for implicit implementations because, if the custom
            // modifiers don't match, we'll insert bridge methods for the accessors (explicit implementations 
            // that delegate to the implicit implementations) with the correct custom modifiers
            // (see SourceNamedTypeSymbol.ImplementInterfaceMember).

            // Note: we're checking if the syntax indicates explicit implementation rather,
            // than if explicitInterfaceType is null because we don't want to look for an
            // overridden property if this is supposed to be an explicit implementation.
            if (isExplicitInterfaceImplementation || this.IsOverride)
            {
                // Type and parameters for overrides and explicit implementations cannot be bound
                // lazily since the property name depends on the metadata name of the base property,
                // and the property name is required to add the property to the containing type, and
                // the type and parameters are required to determine the override or implementation.
                _lazyType = this.ComputeType(bodyBinder, syntax, diagnostics);
                _lazyParameters = this.ComputeParameters(bodyBinder, syntax, diagnostics);

                bool isOverride = false;
                PropertySymbol overriddenOrImplementedProperty = null;

                if (!isExplicitInterfaceImplementation)
                {
                    // If this property is an override, we may need to copy custom modifiers from
                    // the overridden property (so that the runtime will recognize it as an override).
                    // We check for this case here, while we can still modify the parameters and
                    // return type without losing the appearance of immutability.
                    isOverride = true;
                    overriddenOrImplementedProperty = this.OverriddenProperty;
                }
                else
                {
                    string interfacePropertyName = isIndexer ? WellKnownMemberNames.Indexer : name;
                    explicitlyImplementedProperty = this.FindExplicitlyImplementedProperty(_explicitInterfaceType, interfacePropertyName, interfaceSpecifier, diagnostics);
                    overriddenOrImplementedProperty = explicitlyImplementedProperty;
                }

                if ((object)overriddenOrImplementedProperty != null)
                {
                    _typeCustomModifiers = overriddenOrImplementedProperty.TypeCustomModifiers;

                    TypeSymbol overriddenPropertyType = overriddenOrImplementedProperty.Type;

                    // We do an extra check before copying the type to handle the case where the overriding
                    // property (incorrectly) has a different type than the overridden property.  In such cases,
                    // we want to retain the original (incorrect) type to avoid hiding the type given in source.
                    if (_lazyType.Equals(overriddenPropertyType, ignoreCustomModifiersAndArraySizesAndLowerBounds: true, ignoreDynamic: false))
                    {
                        _lazyType = overriddenPropertyType;
                    }

                    _lazyParameters = CustomModifierUtils.CopyParameterCustomModifiers(overriddenOrImplementedProperty.Parameters, _lazyParameters, alsoCopyParamsModifier: isOverride);
                }
            }

            if (!hasAccessorList)
            {
                if (hasExpressionBody)
                {
                    _isExpressionBodied = true;
                    _getMethod = SourcePropertyAccessorSymbol.CreateAccessorSymbol(
                        containingType,
                        this,
                        _modifiers,
                        _sourceName,
                        arrowExpression,
                        explicitlyImplementedProperty,
                        aliasQualifierOpt,
                        diagnostics);
                }
                else
                {
                    _getMethod = null;
                }
                _setMethod = null;
            }
            else
            {
                _getMethod = CreateAccessorSymbol(getSyntax, explicitlyImplementedProperty, aliasQualifierOpt, notRegularProperty, diagnostics);
                _setMethod = CreateAccessorSymbol(setSyntax, explicitlyImplementedProperty, aliasQualifierOpt, notRegularProperty, diagnostics);

                if ((getSyntax == null) || (setSyntax == null))
                {
                    if ((getSyntax == null) && (setSyntax == null))
                    {
                        diagnostics.Add(ErrorCode.ERR_PropertyWithNoAccessors, location, this);
                    }
                    else if (notRegularProperty)
                    {
                        var accessor = _getMethod ?? _setMethod;
                        if (getSyntax == null)
                        {
                            diagnostics.Add(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, accessor.Locations[0], accessor);
                        }
                    }
                }

                // Check accessor accessibility is more restrictive than property accessibility.
                CheckAccessibilityMoreRestrictive(_getMethod, diagnostics);
                CheckAccessibilityMoreRestrictive(_setMethod, diagnostics);

                if (((object)_getMethod != null) && ((object)_setMethod != null))
                {
                    // Check accessibility is set on at most one accessor.
                    if ((_getMethod.LocalAccessibility != Accessibility.NotApplicable) &&
                        (_setMethod.LocalAccessibility != Accessibility.NotApplicable))
                    {
                        diagnostics.Add(ErrorCode.ERR_DuplicatePropertyAccessMods, location, this);
                    }
                    else if (this.IsAbstract)
                    {
                        // Check abstract property accessors are not private.
                        CheckAbstractPropertyAccessorNotPrivate(_getMethod, diagnostics);
                        CheckAbstractPropertyAccessorNotPrivate(_setMethod, diagnostics);
                    }
                }
                else
                {
                    if (!this.IsOverride)
                    {
                        var accessor = _getMethod ?? _setMethod;
                        if ((object)accessor != null)
                        {
                            // Check accessibility is not set on the one accessor.
                            if (accessor.LocalAccessibility != Accessibility.NotApplicable)
                            {
                                diagnostics.Add(ErrorCode.ERR_AccessModMissingAccessor, location, this);
                            }
                        }
                    }
                }
            }

            if ((object)explicitlyImplementedProperty != null)
            {
                CheckExplicitImplementationAccessor(this.GetMethod, explicitlyImplementedProperty.GetMethod, explicitlyImplementedProperty, diagnostics);
                CheckExplicitImplementationAccessor(this.SetMethod, explicitlyImplementedProperty.SetMethod, explicitlyImplementedProperty, diagnostics);
            }

            _explicitInterfaceImplementations =
                (object)explicitlyImplementedProperty == null ?
                    ImmutableArray<PropertySymbol>.Empty :
                    ImmutableArray.Create(explicitlyImplementedProperty);

            // get-only auto property should not override settable properties
            if (_isAutoProperty && (object)_setMethod == null && !this.IsReadOnly)
            {
                diagnostics.Add(ErrorCode.ERR_AutoPropertyMustOverrideSet, location, this);
            }
        }
Exemplo n.º 34
0
        internal static async Task <SyntaxNode> GetTopmostSyntaxNodeForDeclarationAsync(SyntaxReference declaration, ISymbol declaredSymbol, SemanticModelProvider semanticModelProvider, CancellationToken cancellationToken)
        {
            var declSyntax = await declaration.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);

            if (declSyntax.Language == LanguageNames.VisualBasic)
            {
                SemanticModel model = semanticModelProvider.GetSemanticModel(declSyntax);
                while (declSyntax.Parent != null && Equals(model.GetDeclaredSymbol(declSyntax.Parent, cancellationToken), declaredSymbol))
                {
                    declSyntax = declSyntax.Parent;
                }
            }

            return(declSyntax);
        }
Exemplo n.º 35
0
        /// <summary>
        /// In regular C#, all field initializers are assignments to fields and the assigned expressions
        /// may not reference instance members.
        /// </summary>
        private static void BindRegularCSharpFieldInitializers(
            CSharpCompilation compilation,
            ImmutableArray <FieldInitializers> initializers,
            ArrayBuilder <BoundInitializer> boundInitializers,
            DiagnosticBag diagnostics,
            bool generateDebugInfo,
            out ConsList <Imports> firstDebugImports)
        {
            firstDebugImports = null;

            foreach (FieldInitializers siblingInitializers in initializers)
            {
                // All sibling initializers share the same parent node and tree so we can reuse the binder
                // factory across siblings.  Unfortunately, we cannot reuse the binder itself, because
                // individual fields might have their own binders (e.g. because of being declared unsafe).
                BinderFactory binderFactory = null;

                var infos = ArrayBuilder <FieldInitializerInfo> .GetInstance(); // Exact size is not known up front.

                foreach (FieldInitializer initializer in siblingInitializers.Initializers)
                {
                    FieldSymbol fieldSymbol = initializer.Field;
                    Debug.Assert((object)fieldSymbol != null);

                    // A constant field of type decimal needs a field initializer, so
                    // check if it is a metadata constant, not just a constant to exclude
                    // decimals. Other constants do not need field initializers.
                    if (!fieldSymbol.IsMetadataConstant)
                    {
                        //Can't assert that this is a regular C# compilation, because we could be in a nested type of a script class.
                        SyntaxReference syntaxRef       = initializer.Syntax;
                        var             initializerNode = (EqualsValueClauseSyntax)syntaxRef.GetSyntax();

                        if (binderFactory == null)
                        {
                            binderFactory = compilation.GetBinderFactory(syntaxRef.SyntaxTree);
                        }

                        Binder parentBinder = binderFactory.GetBinder(initializerNode);
                        Debug.Assert(parentBinder.ContainingMemberOrLambda == fieldSymbol.ContainingType || //should be the binder for the type
                                     fieldSymbol.ContainingType.IsImplicitClass);                           //however, we also allow fields in namespaces to help support script scenarios

                        if (generateDebugInfo && firstDebugImports == null)
                        {
                            firstDebugImports = parentBinder.ImportsList;
                        }

                        parentBinder = new LocalScopeBinder(parentBinder).WithAdditionalFlagsAndContainingMemberOrLambda(parentBinder.Flags | BinderFlags.FieldInitializer, fieldSymbol);

                        if (!fieldSymbol.IsConst && !fieldSymbol.IsStatic)
                        {
                            parentBinder = parentBinder.WithPrimaryConstructorParametersIfNecessary(fieldSymbol.ContainingType);
                        }

                        infos.Add(new FieldInitializerInfo(initializer, parentBinder, initializerNode));
                    }
                }

                // See if there are locals that we need to bring into the scope.
                var locals = default(ImmutableArray <LocalSymbol>);
                if (siblingInitializers.TypeDeclarationSyntax != null)
                {
                    locals = GetInitializationScopeLocals(infos);
                }

                ArrayBuilder <BoundInitializer> initializersBuilder = locals.IsDefaultOrEmpty ? boundInitializers : ArrayBuilder <BoundInitializer> .GetInstance(infos.Count);

                foreach (var info in infos)
                {
                    Binder binder = info.Binder;
                    ScopedExpressionBinder scopedExpressionBinder = null;

                    // Constant initializers is not part of the initialization scope.
                    if (info.Initializer.Field.IsConst || locals.IsDefault)
                    {
                        binder = scopedExpressionBinder = new ScopedExpressionBinder(binder, info.EqualsValue.Value);
                    }
                    else if (!locals.IsEmpty)
                    {
                        binder = new SimpleLocalScopeBinder(locals, binder);
                    }

                    BoundFieldInitializer boundInitializer = BindFieldInitializer(binder, info.Initializer.Field, info.EqualsValue, diagnostics);

                    if (scopedExpressionBinder != null && !scopedExpressionBinder.Locals.IsDefaultOrEmpty)
                    {
                        boundInitializer = boundInitializer.Update(boundInitializer.Field, scopedExpressionBinder.AddLocalScopeToExpression(boundInitializer.InitialValue));
                    }

                    initializersBuilder.Add(boundInitializer);
                }

                Debug.Assert(locals.IsDefaultOrEmpty == (initializersBuilder == boundInitializers));
                if (!locals.IsDefaultOrEmpty)
                {
                    boundInitializers.Add(new BoundInitializationScope((CSharpSyntaxNode)siblingInitializers.TypeDeclarationSyntax.GetSyntax(),
                                                                       locals, initializersBuilder.ToImmutableAndFree()));
                }
            }
        }
Exemplo n.º 36
0
 private static SingleNamespaceOrTypeDeclaration CreateImplicitClass(ICollection <string> memberNames, SyntaxReference container, SingleTypeDeclaration.TypeDeclarationFlags declFlags)
 {
     return(new SingleTypeDeclaration(
                kind: DeclarationKind.ImplicitClass,
                name: TypeSymbol.ImplicitTypeName,
                arity: 0,
                modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed,
                declFlags: declFlags,
                syntaxReference: container,
                nameLocation: new SourceLocation(container),
                memberNames: memberNames,
                children: ImmutableArray <SingleTypeDeclaration> .Empty));
 }
Exemplo n.º 37
0
 public NamespaceDeclarationSyntaxReference(SyntaxReference reference)
     : base(reference)
 {
 }
Exemplo n.º 38
0
        internal static void BindRegularCSharpFieldInitializers(
            CSharpCompilation compilation,
            ImmutableArray <ImmutableArray <FieldOrPropertyInitializer> > initializers,
            ArrayBuilder <BoundInitializer> boundInitializers,
            DiagnosticBag diagnostics,
            out ImportChain?firstDebugImports)
        {
            firstDebugImports = null;

            foreach (ImmutableArray <FieldOrPropertyInitializer> siblingInitializers in initializers)
            {
                // All sibling initializers share the same parent node and tree so we can reuse the binder
                // factory across siblings.  Unfortunately, we cannot reuse the binder itself, because
                // individual fields might have their own binders (e.g. because of being declared unsafe).
                BinderFactory?binderFactory = null;

                foreach (FieldOrPropertyInitializer initializer in siblingInitializers)
                {
                    FieldSymbol fieldSymbol = initializer.FieldOpt;
                    Debug.Assert((object)fieldSymbol != null);

                    // A constant field of type decimal needs a field initializer, so
                    // check if it is a metadata constant, not just a constant to exclude
                    // decimals. Other constants do not need field initializers.
                    if (!fieldSymbol.IsMetadataConstant)
                    {
                        //Can't assert that this is a regular C# compilation, because we could be in a nested type of a script class.
                        SyntaxReference syntaxRef = initializer.Syntax;

                        switch (syntaxRef.GetSyntax())
                        {
                        case EqualsValueClauseSyntax initializerNode:
                            if (binderFactory == null)
                            {
                                binderFactory = compilation.GetBinderFactory(syntaxRef.SyntaxTree);
                            }

                            Binder parentBinder = binderFactory.GetBinder(initializerNode);

                            if (firstDebugImports == null)
                            {
                                firstDebugImports = parentBinder.ImportChain;
                            }

                            parentBinder = parentBinder.GetFieldInitializerBinder(fieldSymbol);

                            BoundFieldEqualsValue boundInitializer = BindFieldInitializer(parentBinder, fieldSymbol, initializerNode, diagnostics);
                            boundInitializers.Add(boundInitializer);
                            break;

                        case ParameterSyntax parameterSyntax:     // Initializer for a generated property based on record parameters

                            if (firstDebugImports == null)
                            {
                                if (binderFactory == null)
                                {
                                    binderFactory = compilation.GetBinderFactory(syntaxRef.SyntaxTree);
                                }

                                firstDebugImports = binderFactory.GetBinder(parameterSyntax).ImportChain;
                            }

                            boundInitializers.Add(new BoundFieldEqualsValue(parameterSyntax, fieldSymbol, ImmutableArray <LocalSymbol> .Empty,
                                                                            new BoundParameter(parameterSyntax,
                                                                                               ((SynthesizedRecordPropertySymbol)fieldSymbol.AssociatedSymbol).BackingParameter).MakeCompilerGenerated()));
                            break;

                        default:
                            throw ExceptionUtilities.Unreachable;
                        }
                    }
                }
            }
        }
Exemplo n.º 39
0
 internal static MemberDeclarationSyntax GetDeclarationSyntax(this SyntaxReference @this)
 {
     return(@this.GetSyntax().AncestorsAndSelf().OfType <MemberDeclarationSyntax>().First());
 }
Exemplo n.º 40
0
        private void BindPCallAndDelegate(InvocationExpressionSyntax node, ArrayBuilder <BoundExpression> args,
                                          DiagnosticBag diagnostics, TypeSyntax type)
        {
            var    XNode  = node.XNode as XP.MethodCallContext;
            string method = XNode?.Expr.GetText();

            if (string.IsNullOrEmpty(method))
            {
                method = "PCALL";
            }
            if (!ValidatePCallArguments(node, args, diagnostics, method))
            {
                return;
            }
            var kind = args[0].Kind;

            if (kind != BoundKind.Local && kind != BoundKind.FieldAccess)
            {
                Error(diagnostics, ErrorCode.ERR_PCallFirstArgument, node, method, "typed function pointer");
                return;
            }
            string methodName = null;
            // Note that this does not get the syntax of the argument itself
            // but the syntax of the place where the symbol (Global, Field or Local) that the argument points to was defined
            SyntaxReference syntaxref = null;

            if (kind == BoundKind.FieldAccess)
            {
                var bfa = args[0] as BoundFieldAccess;  // Global or Field
                if (bfa != null && bfa.ExpressionSymbol.DeclaringSyntaxReferences.Length > 0)
                {
                    syntaxref = bfa.ExpressionSymbol.DeclaringSyntaxReferences[0] as SyntaxReference;
                }
            }
            else if (kind == BoundKind.Local)
            {
                var bl = args[0] as BoundLocal;         // Local
                if (bl != null && bl.LocalSymbol?.DeclaringSyntaxReferences.Length > 0)
                {
                    syntaxref = bl.LocalSymbol.DeclaringSyntaxReferences[0] as SyntaxReference;
                }
            }
            if (syntaxref != null)
            {
                CSharpSyntaxNode syntaxnode = syntaxref.GetSyntax() as CSharpSyntaxNode;
                var xNode = syntaxnode?.XNode;
                methodName = GetTypedPtrName(xNode);
            }

            if (methodName == null)
            {
                // first argument for pcall must be typed ptr
                Error(diagnostics, ErrorCode.ERR_PCallFirstArgument, node, method, "typed function pointer");
                return;
            }
            var lookupResult = LookupResult.GetInstance();
            HashSet <DiagnosticInfo> useSiteDiagnostics = null;
            LookupOptions            options            = LookupOptions.AllMethodsOnArityZero;

            options |= LookupOptions.MustNotBeInstance;
            this.LookupSymbolsWithFallback(lookupResult, methodName, arity: 0, useSiteDiagnostics: ref useSiteDiagnostics, options: options);
            SourceMethodSymbol methodSym = null;

            if (lookupResult.IsClear)
            {
                // Cannot locate types pointer for pcall
                Error(diagnostics, ErrorCode.ERR_PCallTypedPointerName, node, method, methodName);
                methodSym = null;
            }
            else if (lookupResult.IsMultiViable)
            {
                foreach (var symbol in lookupResult.Symbols)
                {
                    if (symbol.DeclaringCompilation == this.Compilation && symbol is SourceMethodSymbol)
                    {
                        methodSym = (SourceMethodSymbol)symbol;
                        break;
                    }
                }
            }
            else
            {
                methodSym = (SourceMethodSymbol)lookupResult.Symbols[0];
            }
            if (methodSym != null)
            {
                lookupResult.Clear();
                var ts = FindPCallDelegateType(type as IdentifierNameSyntax);
                if (ts != null && ts.IsDelegateType())
                {
                    SourceDelegateMethodSymbol delmeth = ts.DelegateInvokeMethod() as SourceDelegateMethodSymbol;
                    // clone the parameters from the methodSym
                    var builder = ArrayBuilder <ParameterSymbol> .GetInstance();

                    foreach (var par in methodSym.Parameters)
                    {
                        var parameter = new SourceSimpleParameterSymbol(
                            delmeth,
                            par.Type,
                            par.Ordinal,
                            par.RefKind,
                            par.Name,
                            par.Locations);
                        builder.Add(parameter);
                    }
                    delmeth.InitializeParameters(builder.ToImmutableAndFree());
                    delmeth.SetReturnType(methodSym.ReturnType);
                }
                else
                {
                    Error(diagnostics, ErrorCode.ERR_PCallResolveGeneratedDelegate, node, method, type.ToString());
                }
            }
            return;
        }
 protected SourceOrdinaryMethodOrUserDefinedOperatorSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator)
     : base(containingType, syntaxReferenceOpt, location, isIterator)
 {
 }
Exemplo n.º 42
0
 public bool TryStartAnalyzingDeclaration(SyntaxReference decl, out DeclarationAnalyzerStateData state)
 {
     return(TryStartProcessingEntity(decl.GetSyntax(), _pendingDeclarations, _declarationAnalyzerStateDataPool, out state));
 }
 protected abstract SyntaxNode Translate(SyntaxReference reference, CancellationToken cancellationToken);
Exemplo n.º 44
0
 public LexicalSortKey(SyntaxReference syntaxRef, CSharpCompilation compilation)
     : this(syntaxRef.SyntaxTree, syntaxRef.Span.Start, compilation)
 {
 }
Exemplo n.º 45
0
 /// <summary>
 /// Attempts to start processing a symbol declaration for the given analyzer's syntax node and code block actions.
 /// </summary>
 /// <returns>
 /// Returns false if the declaration has already been processed for the analyzer OR is currently being processed by another task.
 /// If true, then it returns a non-null <paramref name="state"/> representing partial analysis state for the given declaration for the given analyzer.
 /// </returns>
 public bool TryStartAnalyzingDeclaration(SyntaxReference decl, DiagnosticAnalyzer analyzer, out DeclarationAnalyzerStateData state)
 {
     return(GetAnalyzerState(analyzer).TryStartAnalyzingDeclaration(decl, out state));
 }
Exemplo n.º 46
0
 protected SourceMethodSymbolWithAttributes(SyntaxReference syntaxReferenceOpt)
 {
     this.syntaxReferenceOpt = syntaxReferenceOpt;
 }
 public CrefTypeParameterSymbol(string name, int ordinal, IdentifierNameSyntax declaringSyntax)
 {
     this.name = name;
     this.ordinal = ordinal;
     this.declaringSyntax = declaringSyntax.GetReference();
 }
Exemplo n.º 48
0
 public FieldOrPropertyInitializer(FieldSymbol field, SyntaxReference syntax)
 {
     Debug.Assert(((object)field != null) || (syntax != null));
     Field  = field;
     Syntax = syntax;
 }
Exemplo n.º 49
0
 public Reference(CountedSyntaxTree countedSyntaxTree, SyntaxReference syntaxReference)
 {
     this.countedSyntaxTree         = countedSyntaxTree;
     this.underlyingSyntaxReference = syntaxReference;
 }
Exemplo n.º 50
0
        protected SourceFieldSymbolWithSyntaxReference(SourceMemberContainerTypeSymbol containingType, string name, SyntaxReference syntax, Location location)
            : base(containingType)
        {
            Debug.Assert(name != null);
            Debug.Assert(syntax != null);
            Debug.Assert(location != null);

            _name            = name;
            _syntaxReference = syntax;
            _location        = location;
        }
Exemplo n.º 51
0
 public FieldInitializer(FieldSymbol field, SyntaxReference syntax)
 {
     Debug.Assert(((object)field != null) || (syntax != null));
     Field = field;
     Syntax = syntax;
 }
Exemplo n.º 52
0
 public void MarkDeclarationComplete(SyntaxReference decl)
 {
     MarkEntityProcessed(decl.GetSyntax(), _pendingDeclarations, _declarationAnalyzerStateDataPool);
 }
Exemplo n.º 53
0
 public Reference(CountedSyntaxTree countedSyntaxTree, SyntaxReference syntaxReference)
 {
     _countedSyntaxTree         = countedSyntaxTree;
     _underlyingSyntaxReference = syntaxReference;
 }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            Document          doc = context.Document;
            CancellationToken cancellationToken = context.CancellationToken;
            SyntaxNode        root = await doc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            if (root.FindNode(context.Span) is SyntaxNode expression)
            {
                SemanticModel semanticModel = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                var operation = semanticModel.GetOperation(expression, cancellationToken);
                if (operation is IArgumentOperation argumentOperation)
                {
                    var localReferenceOperation = argumentOperation.Value as ILocalReferenceOperation;
                    var literalOperation        = argumentOperation.Value as ILiteralOperation;
                    if (localReferenceOperation == null && literalOperation == null)
                    {
                        return;
                    }

                    IVariableDeclaratorOperation?variableDeclaratorOperation = default;
                    if (localReferenceOperation != null)
                    {
                        ILocalSymbol    localArgumentDeclaration = localReferenceOperation.Local;
                        SyntaxReference declaringSyntaxReference = localArgumentDeclaration.DeclaringSyntaxReferences.FirstOrDefault();
                        if (declaringSyntaxReference is null)
                        {
                            return;
                        }

                        variableDeclaratorOperation = semanticModel.GetOperationWalkingUpParentChain(declaringSyntaxReference.GetSyntax(cancellationToken), cancellationToken) as IVariableDeclaratorOperation;

                        if (variableDeclaratorOperation == null)
                        {
                            return;
                        }

                        var variableInitializerOperation = variableDeclaratorOperation.GetVariableInitializer();
                        if (variableInitializerOperation == null)
                        {
                            return;
                        }

                        IVariableDeclarationOperation variableDeclarationOperation = (IVariableDeclarationOperation)variableDeclaratorOperation.Parent;
                        if (variableDeclarationOperation == null)
                        {
                            return;
                        }

                        IVariableDeclarationGroupOperation variableGroupDeclarationOperation = (IVariableDeclarationGroupOperation)variableDeclarationOperation.Parent;
                        if (variableGroupDeclarationOperation.Declarations.Length != 1)
                        {
                            return;
                        }

                        if (variableDeclarationOperation.Declarators.Length != 1)
                        {
                            return;
                        }
                    }

                    context.RegisterCodeFix(
                        CodeAction.Create(
                            title: MicrosoftNetCoreAnalyzersResources.PreferConstCharOverConstUnitStringInStringBuilderTitle,
                            createChangedDocument: async c =>
                    {
                        if (literalOperation != null)
                        {
                            return(await HandleStringLiteral(literalOperation, doc, root, cancellationToken).ConfigureAwait(false));
                        }
                        else
                        {
                            RoslynDebug.Assert(variableDeclaratorOperation != null);
                            return(await HandleVariableDeclarator(variableDeclaratorOperation !, doc, root, cancellationToken).ConfigureAwait(false));
                        }
                    },
                            equivalenceKey: MicrosoftNetCoreAnalyzersResources.PreferConstCharOverConstUnitStringInStringBuilderMessage),
                        context.Diagnostics);
Exemplo n.º 55
0
 private static SyntaxNode GetTopmostNodeForAnalysis(ISymbol symbol, SyntaxReference syntaxReference, Compilation compilation)
 {
     var model = compilation.GetSemanticModel(syntaxReference.SyntaxTree);
     return model.GetTopmostNodeForDiagnosticAnalysis(symbol, syntaxReference.GetSyntax());
 }
Exemplo n.º 56
0
 protected SourceMemberMethodSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator)
     : this(containingType, syntaxReferenceOpt, ImmutableArray.Create(location), isIterator)
 {
 }
Exemplo n.º 57
0
 public CrefTypeParameterSymbol(string name, int ordinal, IdentifierNameSyntax declaringSyntax)
 {
     _name            = name;
     _ordinal         = ordinal;
     _declaringSyntax = declaringSyntax.GetReference();
 }
Exemplo n.º 58
0
 protected abstract SyntaxNode SyntaxFromReference(SyntaxReference reference);
 internal Binder GetBinder(SyntaxReference reference)
 {
     return GetBinderFactory(reference.SyntaxTree).GetBinder((CSharpSyntaxNode)reference.GetSyntax());
 }
Exemplo n.º 60
0
        private async Task AnalyzeDeclaringReference(CompilationEvent.SymbolDeclared symbolEvent, SyntaxReference decl, Action <Diagnostic> addDiagnostic, CancellationToken cancellationToken)
        {
            var symbol = symbolEvent.Symbol;
            var syntax = await decl.GetSyntaxAsync();

            var endedAnalyzers = ArrayBuilder <ICodeBlockEndedAnalyzer> .GetInstance();

            endedAnalyzers.AddRange(CodeBlockEndedAnalyzers);
            var nodeAnalyzers = ArrayBuilder <ISyntaxNodeAnalyzer <TSyntaxKind> > .GetInstance();

            nodeAnalyzers.AddRange(Analyzers.OfType <ISyntaxNodeAnalyzer <TSyntaxKind> >());
            foreach (var da in CodeBlockStartedAnalyzers)
            {
                // Catch Exception from da.OnCodeBlockStarted
                ExecuteAndCatchIfThrows(da, addDiagnostic, continueOnError, cancellationToken, () =>
                {
                    var blockStatefulAnalyzer = da.OnCodeBlockStarted(syntax, symbol, symbolEvent.SemanticModel(decl), addDiagnostic, cancellationToken);
                    var endedAnalyzer         = blockStatefulAnalyzer as ICodeBlockEndedAnalyzer;
                    if (endedAnalyzer != null)
                    {
                        endedAnalyzers.Add(endedAnalyzer);
                    }
                    var nodeAnalyzer = blockStatefulAnalyzer as ISyntaxNodeAnalyzer <TSyntaxKind>;
                    if (nodeAnalyzer != null)
                    {
                        nodeAnalyzers.Add(nodeAnalyzer);
                    }
                });
            }

            PooledDictionary <TSyntaxKind, ArrayBuilder <ISyntaxNodeAnalyzer <TSyntaxKind> > > nodeAnalyzersByKind = null;

            foreach (var nodeAnalyzer in nodeAnalyzers)
            {
                // Catch Exception from  nodeAnalyzer.SyntaxKindsOfInterest
                try
                {
                    foreach (var kind in nodeAnalyzer.SyntaxKindsOfInterest)
                    {
                        if (nodeAnalyzersByKind == null)
                        {
                            nodeAnalyzersByKind = PooledDictionary <TSyntaxKind, ArrayBuilder <ISyntaxNodeAnalyzer <TSyntaxKind> > > .GetInstance();
                        }
                        ArrayBuilder <ISyntaxNodeAnalyzer <TSyntaxKind> > analyzersForKind;
                        if (!nodeAnalyzersByKind.TryGetValue(kind, out analyzersForKind))
                        {
                            nodeAnalyzersByKind.Add(kind, analyzersForKind = ArrayBuilder <ISyntaxNodeAnalyzer <TSyntaxKind> > .GetInstance());
                        }
                        analyzersForKind.Add(nodeAnalyzer);
                    }
                }
                catch (Exception e)
                {
                    // Create a info diagnostic saying that the analyzer failed
                    addDiagnostic(GetAnalyzerDiagnostic(nodeAnalyzer, e));
                }
            }
            nodeAnalyzers.Free();

            SemanticModel semanticModel = (nodeAnalyzersByKind != null || endedAnalyzers.Any()) ? symbolEvent.SemanticModel(decl) : null;

            if (nodeAnalyzersByKind != null)
            {
                semanticModel = symbolEvent.SemanticModel(decl);
                foreach (var child in syntax.DescendantNodesAndSelf())
                {
                    ArrayBuilder <ISyntaxNodeAnalyzer <TSyntaxKind> > analyzersForKind;
                    if (nodeAnalyzersByKind.TryGetValue(GetKind(child), out analyzersForKind))
                    {
                        foreach (var analyzer in analyzersForKind)
                        {
                            // Catch Exception from analyzer.AnalyzeNode
                            ExecuteAndCatchIfThrows(analyzer, addDiagnostic, continueOnError, cancellationToken, () => { analyzer.AnalyzeNode(child, semanticModel, addDiagnostic, cancellationToken); });
                        }
                    }
                }

                foreach (var b in nodeAnalyzersByKind.Values)
                {
                    b.Free();
                }
                nodeAnalyzersByKind.Free();
            }

            foreach (var a in endedAnalyzers)
            {
                // Catch Exception from a.OnCodeBlockEnded
                ExecuteAndCatchIfThrows(a, addDiagnostic, continueOnError, cancellationToken, () => { a.OnCodeBlockEnded(syntax, symbol, semanticModel, addDiagnostic, cancellationToken); });
            }
            endedAnalyzers.Free();
        }