Esempio n. 1
0
 public static void CheckForFormat(NeosSdiMef neosSdiMef, CodingRule rule, BasePropertyDeclarationSyntax _property, string text, string textFull, int spanStart, int spanEnd)
 {
     switch (rule.RuleCase)
     {
         case CodingRuleCaseEnum.UpperCamelCase:
             string upperText = rule.RuleFirstLetter + text.UpperCamelCase();
             if (text != upperText)
             {
                 neosSdiMef.AddDecorationError(_property, textFull, "Replace " + text + " by " + upperText, () =>
                 {
                     var span = Span.FromBounds(spanStart, spanEnd);
                     neosSdiMef._textView.TextBuffer.Replace(span, upperText);
                 });
             }
             break;
         case CodingRuleCaseEnum.LowerCamelCase:
             string lowerText = rule.RuleFirstLetter + text.LowerCamelCase();
             if (text != lowerText)
             {
                 neosSdiMef.AddDecorationError(_property, textFull, "Replace " + text + " by " + lowerText, () =>
                 {
                     var span = Span.FromBounds(spanStart, spanEnd);
                     neosSdiMef._textView.TextBuffer.Replace(span, lowerText);
                 });
             }
             break;
         default:
             break;
     }
 }
        private static async Task<Document> ApplyFix(
            Document document
            , BaseTypeSyntax derivingClass
            , BasePropertyDeclarationSyntax viewModelProperty
            , CancellationToken cancellationToken)
        {
            var genericClassDeclaration = SyntaxFactory.SimpleBaseType(
                SyntaxFactory.GenericName(
                    SyntaxFactory.Identifier(
                            derivingClass.Type.ToString()
                        )
                    )
                    .WithTypeArgumentList(
                        SyntaxFactory.TypeArgumentList(
                            SyntaxFactory.SingletonSeparatedList(viewModelProperty.Type)
                        )
                    )
                ).WithAdditionalAnnotations(Formatter.Annotation);

            var editor = await DocumentEditor.CreateAsync(document, cancellationToken);
            editor.RemoveNode(viewModelProperty);
            editor.ReplaceNode(derivingClass, genericClassDeclaration);

            return editor.GetChangedDocument();
        }
Esempio n. 3
0
        public void AddDecorationError(BasePropertyDeclarationSyntax _property, string textFull, string toolTipText, FixErrorCallback errorCallback)
        {
            var lineSpan = tree.GetLineSpan(_property.Span, usePreprocessorDirectives: false);
            int lineNumber = lineSpan.StartLinePosition.Line;
            var line = _textView.TextSnapshot.GetLineFromLineNumber(lineNumber);
            var textViewLine = _textView.GetTextViewLineContainingBufferPosition(line.Start);
            int startSpace = textFull.Length - textFull.TrimStart().Length;
            int endSpace = textFull.Length - textFull.TrimEnd().Length;

            SnapshotSpan span = new SnapshotSpan(_textView.TextSnapshot, Span.FromBounds(line.Start.Position + startSpace, line.End.Position - endSpace));
            Geometry g = _textView.TextViewLines.GetMarkerGeometry(span);
            if (g != null)
            {
                rects.Add(g.Bounds);

                GeometryDrawing drawing = new GeometryDrawing(_brush, _pen, g);
                drawing.Freeze();

                DrawingImage drawingImage = new DrawingImage(drawing);
                drawingImage.Freeze();

                Image image = new Image();
                image.Source = drawingImage;
                //image.Visibility = Visibility.Hidden;

                Canvas.SetLeft(image, g.Bounds.Left);
                Canvas.SetTop(image, g.Bounds.Top);
                _layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, (t, ui) =>
                {
                    rects.Remove(g.Bounds);
                });

                DrawIcon(span, g.Bounds.Left - 30, g.Bounds.Top, toolTipText, errorCallback);
            }
        }
        private static bool HasBothAccessors(BasePropertyDeclarationSyntax property)
        {
            var accessors = property.AccessorList.Accessors;
            var getter = accessors.FirstOrDefault(ad => ad.Kind() == SyntaxKind.GetAccessorDeclaration);
            var setter = accessors.FirstOrDefault(ad => ad.Kind() == SyntaxKind.SetAccessorDeclaration);

            return getter?.Body?.Statements.Count == 1 && setter?.Body?.Statements.Count == 1;
        }
        public BasePropertyDeclarationTranslation(BasePropertyDeclarationSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
        {
            Type = syntax.Type.Get<TypeTranslation>(this);
            AccessorList = syntax.AccessorList.Get<AccessorListTranslation>(this);
            Modifiers = syntax.Modifiers.Get(this);

            AccessorList.SetModifier(Modifiers);
        }
Esempio n. 6
0
        /// <summary>
        /// Returns true if both get and set accessors exist on the given property; otherwise false.
        /// </summary>
        private static bool HasBothAccessors(BasePropertyDeclarationSyntax property)
        {
            var accessors = property.AccessorList.Accessors;
            var getter = accessors.FirstOrDefault(ad => ad.Kind() == SyntaxKind.GetAccessorDeclaration);
            var setter = accessors.FirstOrDefault(ad => ad.Kind() == SyntaxKind.SetAccessorDeclaration);

            if (getter != null && setter != null)
            {
                // The getter and setter should have a body.
                return getter.Body != null && setter.Body != null;
            }

            return false;
        }
        private static async Task<Document> ConvertToExpressionBodiedMemberAsync(Document document, BasePropertyDeclarationSyntax declaration, CancellationToken cancellationToken)
        {
            var accessors = declaration.AccessorList.Accessors;
            var body = accessors[0].Body;
            var returnStatement = body.Statements[0] as ReturnStatementSyntax;

            var arrowExpression = SyntaxFactory.ArrowExpressionClause(
                returnStatement.Expression);

            var newDeclaration = declaration;

            newDeclaration = ((dynamic)declaration)
                .WithAccessorList(null)
                .WithExpressionBody(arrowExpression)
                .WithSemicolon(SyntaxFactory.Token(SyntaxKind.SemicolonToken));

            newDeclaration = newDeclaration.WithAdditionalAnnotations(Formatter.Annotation);

            return await ReplaceNodeAsync(document, declaration, newDeclaration, cancellationToken);
        }
        private static void AnalyzeProperty(SyntaxNodeAnalysisContext context, BasePropertyDeclarationSyntax propertyDeclaration)
        {
            if (propertyDeclaration?.AccessorList == null)
            {
                return;
            }

            var accessors = propertyDeclaration.AccessorList.Accessors;
            if (propertyDeclaration.AccessorList.IsMissing ||
                accessors.Count != 2)
            {
                return;
            }

            if (accessors[0].Kind() == SyntaxKind.SetAccessorDeclaration &&
                accessors[1].Kind() == SyntaxKind.GetAccessorDeclaration)
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, accessors[0].GetLocation()));
            }
        }
        public PropertyToArrowSyntaxRefactoring(BasePropertyDeclarationSyntax property)
        {
            Requires(property != null);

            _property = property;
        }
Esempio n. 10
0
        private static DeclarationInfo GetExpressionBodyDeclarationInfo(
            BasePropertyDeclarationSyntax declarationWithExpressionBody,
            ArrowExpressionClauseSyntax expressionBody,
            SemanticModel model,
            bool getSymbol,
            CancellationToken cancellationToken)
        {
            // TODO: use 'model.GetDeclaredSymbol(expressionBody)' when compiler is fixed to return the getter symbol for it.
            var declaredAccessor = getSymbol ? (model.GetDeclaredSymbol(declarationWithExpressionBody, cancellationToken) as IPropertySymbol)?.GetMethod : null;

            return new DeclarationInfo(
                declaredNode: expressionBody,
                executableCodeBlocks: ImmutableArray.Create<SyntaxNode>(expressionBody),
                declaredSymbol: declaredAccessor);
        }
Esempio n. 11
0
 /// <summary>
 /// Given a syntax node that declares a property, indexer or an event, get the corresponding declared symbol.
 /// </summary>
 /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The symbol that was declared.</returns>
 public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (Logger.LogBlock(FunctionId.CSharp_SemanticModel_GetDeclaredSymbol, message: this.SyntaxTree.FilePath, cancellationToken: cancellationToken))
     {
         return GetDeclaredMemberSymbol(declarationSyntax);
     }
 }
#pragma warning restore RS1008 // Avoid storing per-compilation data into the fields of a diagnostic analyzer.

            public Neighbors(BasePropertyDeclarationSyntax before, BasePropertyDeclarationSyntax after)
            {
                this.Before = before;
                this.After  = after;
            }
Esempio n. 13
0
 private static bool IsNotPublicModifier(BasePropertyDeclarationSyntax property)
 {
     return  IsNotPublicModifier(property, PrivateModifier) ||
             IsNotPublicModifier(property, ProtectedModifier) ||
             IsNotPublicModifier(property, InternalModifier);
 }
Esempio n. 14
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);
            }
        }
Esempio n. 15
0
 private static bool TryGetSetter(BasePropertyDeclarationSyntax declaration, out AccessorDeclarationSyntax setter)
 {
     return(declaration.TryGetSetAccessorDeclaration(out setter));
 }
Esempio n. 16
0
        private void ProcessPropertyAccessors(BasePropertyDeclarationSyntax node, string propertyDeclaringTypeVar, string propName, string propertyType, string propDefVar, List <string> parameters)
        {
            var propInfo      = (IPropertySymbol)Context.SemanticModel.GetDeclaredSymbol(node);
            var declaringType = node.ResolveDeclaringType();

            foreach (var accessor in node.AccessorList.Accessors)
            {
                var accessorModifiers = node.Modifiers.MethodModifiersToCecil(ModifiersToCecil, "MethodAttributes.SpecialName", propInfo.GetMethod ?? propInfo.SetMethod);
                switch (accessor.Keyword.Kind())
                {
                case SyntaxKind.GetKeyword:
                    var getMethodVar = TempLocalVar(propertyDeclaringTypeVar + "_get_");
                    Context.DefinitionVariables.RegisterMethod(declaringType.Identifier.Text, $"get_{propName}", parameters?.ToArray(), getMethodVar);

                    AddCecilExpression($"var {getMethodVar} = new MethodDefinition(\"get_{propName}\", {accessorModifiers}, {propertyType});");
                    parameters.ForEach(paramVar => AddCecilExpression($"{getMethodVar}.Parameters.Add({paramVar});"));
                    AddCecilExpression($"{propertyDeclaringTypeVar}.Methods.Add({getMethodVar});");

                    AddCecilExpression($"{getMethodVar}.Body = new MethodBody({getMethodVar});");
                    AddCecilExpression($"{propDefVar}.GetMethod = {getMethodVar};");

                    if (propInfo.ContainingType.TypeKind == TypeKind.Interface)
                    {
                        break;
                    }

                    var ilVar          = TempLocalVar("ilVar_get_");
                    var ilProcessorExp = $"var {ilVar} = {getMethodVar}.Body.GetILProcessor();";

                    AddCecilExpression(ilProcessorExp);
                    if (accessor.Body == null)     //is this an auto property ?
                    {
                        AddBackingFieldIfNeeded(accessor);

                        AddCilInstruction(ilVar, OpCodes.Ldarg_0);     // TODO: This assumes instance properties...
                        AddCilInstruction(ilVar, OpCodes.Ldfld, MakeGenericTypeIfAppropriate(propInfo, backingFieldVar, propertyDeclaringTypeVar));

                        AddCilInstruction(ilVar, OpCodes.Ret);
                    }
                    else
                    {
                        StatementVisitor.Visit(Context, ilVar, accessor.Body);
                    }

                    break;

                case SyntaxKind.SetKeyword:
                    var setMethodVar = TempLocalVar(propertyDeclaringTypeVar + "_set_");
                    var localParams  = new List <string>(parameters);
                    localParams.Add(Context.GetTypeInfo(node.Type).Type.Name);     // Setters always have at least one `value` parameter.
                    Context.DefinitionVariables.RegisterMethod(declaringType.Identifier.Text, $"set_{propName}", localParams.ToArray(), setMethodVar);
                    var ilSetVar = TempLocalVar("ilVar_set_");

                    AddCecilExpression($"var {setMethodVar} = new MethodDefinition(\"set_{propName}\", {accessorModifiers}, {Context.TypeResolver.ResolvePredefinedType("Void")});");
                    parameters.ForEach(paramVar => AddCecilExpression($"{setMethodVar}.Parameters.Add({paramVar});"));
                    AddCecilExpression($"{propertyDeclaringTypeVar}.Methods.Add({setMethodVar});");

                    AddCecilExpression($"{setMethodVar}.Body = new MethodBody({setMethodVar});");
                    AddCecilExpression($"{propDefVar}.SetMethod = {setMethodVar};");

                    AddCecilExpression($"{setMethodVar}.Parameters.Add(new ParameterDefinition({propertyType}));");
                    AddCecilExpression($"var {ilSetVar} = {setMethodVar}.Body.GetILProcessor();");

                    if (propInfo.ContainingType.TypeKind == TypeKind.Interface)
                    {
                        break;
                    }

                    if (accessor.Body == null)     //is this an auto property ?
                    {
                        AddBackingFieldIfNeeded(accessor);

                        AddCilInstruction(ilSetVar, OpCodes.Ldarg_0);     // TODO: This assumes instance properties...
                        AddCilInstruction(ilSetVar, OpCodes.Ldarg_1);
                        AddCilInstruction(ilSetVar, OpCodes.Stfld, MakeGenericTypeIfAppropriate(propInfo, backingFieldVar, propertyDeclaringTypeVar));
                    }
                    else
                    {
                        StatementVisitor.Visit(Context, ilSetVar, accessor.Body);
                    }

                    AddCilInstruction(ilSetVar, OpCodes.Ret);
                    break;
                }
            }

            void AddBackingFieldIfNeeded(AccessorDeclarationSyntax accessor)
            {
                if (backingFieldVar != null)
                {
                    return;
                }

                backingFieldVar = TempLocalVar("bf");
                var backingFieldName = $"<{propName}>k__BackingField";
                var backingFieldExps = new[]
                {
                    $"var {backingFieldVar} = new FieldDefinition(\"{backingFieldName}\", {ModifiersToCecil("FieldAttributes", accessor.Modifiers, "Private")}, {propertyType});",
                    $"{propertyDeclaringTypeVar}.Fields.Add({backingFieldVar});"
                };

                AddCecilExpressions(backingFieldExps);
            }
        }
Esempio n. 17
0
        private TypeSymbol ComputeType(Binder binder, BasePropertyDeclarationSyntax syntax, DiagnosticBag diagnostics)
        {
            var type = binder.BindType(syntax.Type, diagnostics);
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;

            if (!this.IsNoMoreVisibleThan(type, ref useSiteDiagnostics))
            {
                // "Inconsistent accessibility: indexer return type '{1}' is less accessible than indexer '{0}'"
                // "Inconsistent accessibility: property type '{1}' is less accessible than property '{0}'"
                diagnostics.Add((this.IsIndexer ? ErrorCode.ERR_BadVisIndexerReturn : ErrorCode.ERR_BadVisPropertyType), _location, this, type);
            }

            diagnostics.Add(_location, useSiteDiagnostics);

            if (type.SpecialType == SpecialType.System_Void)
            {
                ErrorCode errorCode = this.IsIndexer ? ErrorCode.ERR_IndexerCantHaveVoidType : ErrorCode.ERR_PropertyCantHaveVoidType;
                diagnostics.Add(errorCode, _location, this);
            }

            return type;
        }
Esempio n. 18
0
 internal static bool IsPropertyOrIndexer(this BasePropertyDeclarationSyntax declaration)
 {
     return(declaration is PropertyDeclarationSyntax || declaration is IndexerDeclarationSyntax);
 }
Esempio n. 19
0
 internal static bool TryGetSetter(this BasePropertyDeclarationSyntax property, out AccessorDeclarationSyntax result)
 {
     return(TryGetAccessorDeclaration(property, SyntaxKind.SetAccessorDeclaration, out result));
 }
Esempio n. 20
0
 public static bool IsPublic(this BasePropertyDeclarationSyntax node)
 {
     return(node.Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword)) || node.Parent.IsKind(SyntaxKind.InterfaceDeclaration));
 }
Esempio n. 21
0
        public static Doc Print(BasePropertyDeclarationSyntax node)
        {
            EqualsValueClauseSyntax?         initializer = null;
            ExplicitInterfaceSpecifierSyntax?explicitInterfaceSpecifierSyntax = null;
            Doc identifier   = Doc.Null;
            Doc eventKeyword = Doc.Null;
            ArrowExpressionClauseSyntax?expressionBody = null;
            SyntaxToken?semicolonToken = null;

            if (node is PropertyDeclarationSyntax propertyDeclarationSyntax)
            {
                expressionBody = propertyDeclarationSyntax.ExpressionBody;
                initializer    = propertyDeclarationSyntax.Initializer;
                explicitInterfaceSpecifierSyntax = propertyDeclarationSyntax.ExplicitInterfaceSpecifier;
                identifier     = Token.Print(propertyDeclarationSyntax.Identifier);
                semicolonToken = propertyDeclarationSyntax.SemicolonToken;
            }
            else if (node is IndexerDeclarationSyntax indexerDeclarationSyntax)
            {
                expressionBody = indexerDeclarationSyntax.ExpressionBody;
                explicitInterfaceSpecifierSyntax = indexerDeclarationSyntax.ExplicitInterfaceSpecifier;
                identifier = Doc.Concat(
                    Token.Print(indexerDeclarationSyntax.ThisKeyword),
                    Node.Print(indexerDeclarationSyntax.ParameterList)
                    );
                semicolonToken = indexerDeclarationSyntax.SemicolonToken;
            }
            else if (node is EventDeclarationSyntax eventDeclarationSyntax)
            {
                eventKeyword = Token.Print(eventDeclarationSyntax.EventKeyword, " ");
                explicitInterfaceSpecifierSyntax = eventDeclarationSyntax.ExplicitInterfaceSpecifier;
                identifier     = Token.Print(eventDeclarationSyntax.Identifier);
                semicolonToken = eventDeclarationSyntax.SemicolonToken;
            }

            Doc contents = string.Empty;

            if (node.AccessorList != null)
            {
                Doc separator = " ";
                if (
                    node.AccessorList.Accessors.Any(
                        o =>
                        o.Body != null ||
                        o.ExpressionBody != null ||
                        o.Modifiers.Any() ||
                        o.AttributeLists.Any()
                        )
                    )
                {
                    separator = Doc.Line;
                }

                contents = Doc.Group(
                    Doc.Concat(
                        separator,
                        Token.Print(node.AccessorList.OpenBraceToken),
                        Doc.Indent(
                            node.AccessorList.Accessors.Select(
                                o => PrintAccessorDeclarationSyntax(o, separator)
                                )
                            .ToArray()
                            ),
                        separator,
                        Token.Print(node.AccessorList.CloseBraceToken)
                        )
                    );
            }
            else if (expressionBody != null)
            {
                contents = Doc.Concat(ArrowExpressionClause.Print(expressionBody));
            }

            var docs = new List <Doc>();

            docs.Add(ExtraNewLines.Print(node));
            docs.Add(AttributeLists.Print(node, node.AttributeLists));

            return(Doc.Group(
                       Doc.Concat(
                           Doc.Concat(docs),
                           Modifiers.Print(node.Modifiers),
                           eventKeyword,
                           Node.Print(node.Type),
                           " ",
                           explicitInterfaceSpecifierSyntax != null
                        ? Doc.Concat(
                               Node.Print(explicitInterfaceSpecifierSyntax.Name),
                               Token.Print(explicitInterfaceSpecifierSyntax.DotToken)
                               )
                        : Doc.Null,
                           identifier,
                           contents,
                           initializer != null ? EqualsValueClause.Print(initializer) : Doc.Null,
                           semicolonToken.HasValue ? Token.Print(semicolonToken.Value) : Doc.Null
                           )
                       ));
        }
 public static bool HasAnyContractAttribute(this BasePropertyDeclarationSyntax @this, SemanticModel model) =>
 @this.HasAnyPreconditionAttribute(model) ||
 @this.HasAnyPostconditionAttribute(model);
 public static IEnumerable <Contract> GetContracts(this BasePropertyDeclarationSyntax @this, SemanticModel model, IContractProvider contractProvider) =>
 @this.GetPreconditions(model, contractProvider).Concat(
     @this.GetPostconditions(model, contractProvider));
Esempio n. 24
0
 internal static ISymbol GetDeclaredSymbolSafe(this SemanticModel semanticModel, BasePropertyDeclarationSyntax node, CancellationToken cancellationToken)
 {
     return(semanticModel.SemanticModelFor(node)
            ?.GetDeclaredSymbol(node, cancellationToken));
 }
Esempio n. 25
0
		private string GetParameters(BasePropertyDeclarationSyntax syntax)
		{
			var symbol = ModelExtensions.GetSymbolInfo(_semanticModel, syntax.Type).Symbol as ITypeSymbol;
			return string.Format("({0})", symbol == null ? string.Empty : ResolveTypeName(symbol));
		}
Esempio n. 26
0
        private static SourcePropertySymbol Create(
            SourceMemberContainerTypeSymbol containingType,
            Binder binder,
            BasePropertyDeclarationSyntax syntax,
            string name,
            Location location,
            BindingDiagnosticBag diagnostics
            )
        {
            GetAccessorDeclarations(
                syntax,
                diagnostics,
                out bool isAutoProperty,
                out bool hasAccessorList,
                out bool accessorsHaveImplementation,
                out bool isInitOnly,
                out var getSyntax,
                out var setSyntax
                );

            var             explicitInterfaceSpecifier        = GetExplicitInterfaceSpecifier(syntax);
            SyntaxTokenList modifiersTokenList                = GetModifierTokensSyntax(syntax);
            bool            isExplicitInterfaceImplementation = explicitInterfaceSpecifier is object;
            var             modifiers = MakeModifiers(
                containingType,
                modifiersTokenList,
                isExplicitInterfaceImplementation,
                isIndexer: syntax.Kind() == SyntaxKind.IndexerDeclaration,
                accessorsHaveImplementation: accessorsHaveImplementation,
                location,
                diagnostics,
                out _
                );

            bool isExpressionBodied = !hasAccessorList && GetArrowExpression(syntax) != null;

            binder = binder.WithUnsafeRegionIfNecessary(modifiersTokenList);
            TypeSymbol?explicitInterfaceType;
            string?    aliasQualifierOpt;
            string     memberName = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(
                binder,
                explicitInterfaceSpecifier,
                name,
                diagnostics,
                out explicitInterfaceType,
                out aliasQualifierOpt
                );

            return(new SourcePropertySymbol(
                       containingType,
                       syntax,
                       hasGetAccessor: getSyntax != null || isExpressionBodied,
                       hasSetAccessor: setSyntax != null,
                       isExplicitInterfaceImplementation,
                       explicitInterfaceType,
                       aliasQualifierOpt,
                       modifiers,
                       isAutoProperty: isAutoProperty,
                       isExpressionBodied: isExpressionBodied,
                       isInitOnly: isInitOnly,
                       memberName,
                       location,
                       diagnostics
                       ));
        }
Esempio n. 27
0
 private static ExplicitInterfaceSpecifierSyntax GetExplicitInterfaceSpecifier(BasePropertyDeclarationSyntax syntax)
 {
     switch (syntax.Kind())
     {
         case SyntaxKind.PropertyDeclaration:
             return ((PropertyDeclarationSyntax)syntax).ExplicitInterfaceSpecifier;
         case SyntaxKind.IndexerDeclaration:
             return ((IndexerDeclarationSyntax)syntax).ExplicitInterfaceSpecifier;
         default:
             throw ExceptionUtilities.UnexpectedValue(syntax.Kind());
     }
 }
Esempio n. 28
0
        private string GetParameters(BasePropertyDeclarationSyntax syntax)
        {
            var symbol = ModelExtensions.GetSymbolInfo(_semanticModel, syntax.Type).Symbol as ITypeSymbol;

            return(string.Format("({0})", symbol == null ? string.Empty : ResolveTypeName(symbol)));
        }
 private SyntaxNode RegisterPropertyLikeDeclarationCodeFix(SyntaxNode syntaxRoot, BasePropertyDeclarationSyntax node, IndentationOptions indentationOptions)
 {
     return this.ReformatElement(syntaxRoot, node, node.AccessorList.OpenBraceToken, node.AccessorList.CloseBraceToken, indentationOptions);
 }
Esempio n. 30
0
        private string GetReturnType(BasePropertyDeclarationSyntax syntax)
        {
            var symbol = ModelExtensions.GetSymbolInfo(_semanticModel, syntax.Type).Symbol as ITypeSymbol;

            return(symbol != null?string.Format(": {0}", ResolveTypeName(symbol)) : string.Empty);
        }
Esempio n. 31
0
 // 属性定义基类
 public virtual void VisitBasePropertyDeclarationSyntax(BasePropertyDeclarationSyntax value)
 {
     DefaultVisit(value);
 }
Esempio n. 32
0
 private bool RemoveProperty(BasePropertyDeclarationSyntax property)
 {
     return(RemoveTestAttributes(property.AttributeLists));
 }
 public static bool HasGetterAndSetter(this BasePropertyDeclarationSyntax property)
 => property.AccessorList?.Accessors.Count == 2;
Esempio n. 34
0
        /// <summary>
        /// Add the field and respect StyleCop ordering.
        /// </summary>
        /// <param name="editor">The <see cref="DocumentEditor"/>.</param>
        /// <param name="containingType">The containing type.</param>
        /// <param name="property">The <see cref="BasePropertyDeclarationSyntax"/>.</param>
        /// <returns>The <paramref name="editor"/>.</returns>
        public static DocumentEditor AddProperty(this DocumentEditor editor, TypeDeclarationSyntax containingType, BasePropertyDeclarationSyntax property)
        {
            if (editor is null)
            {
                throw new System.ArgumentNullException(nameof(editor));
            }

            if (containingType is null)
            {
                throw new System.ArgumentNullException(nameof(containingType));
            }

            if (property is null)
            {
                throw new System.ArgumentNullException(nameof(property));
            }

            editor.ReplaceNode(
                containingType,
                (node, generator) => generator.AddSorted((TypeDeclarationSyntax)node, property));
            return(editor);
        }
Esempio n. 35
0
 private static bool IsNotPublicModifier(BasePropertyDeclarationSyntax property, string modifier)
 {
     return property.Modifiers.Any(x => string.Compare(x.Text, modifier, StringComparison.InvariantCultureIgnoreCase) == 0);
 }
        private string GetPropertyPrototype(BasePropertyDeclarationSyntax node, IPropertySymbol symbol, PrototypeFlags flags)
        {
            if ((flags & PrototypeFlags.Signature) != 0)
            {
                if (flags != PrototypeFlags.Signature)
                {
                    // vsCMPrototypeUniqueSignature can't be combined with anything else.
                    throw Exceptions.ThrowEInvalidArg();
                }

                // The unique signature is simply the node key.
                return GetNodeKey(node).Name;
            }

            var builder = new StringBuilder();

            AppendPropertyPrototype(builder, symbol, flags, GetName(node));

            return builder.ToString();
        }
Esempio n. 37
0
 /// <summary>
 /// Given a syntax node that declares a property, indexer or an event, get the corresponding declared symbol.
 /// </summary>
 /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The symbol that was declared.</returns>
 public abstract ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken));
            private AccessorDeclarationSyntax FindFirstAccessorNode(BasePropertyDeclarationSyntax node)
            {
                if (node.AccessorList == null)
                {
                    return null;
                }

                return node.AccessorList.Accessors.FirstOrDefault();
            }
Esempio n. 39
0
        private static async Task <Document> ConvertToExpressionBodiedMemberAsync(Document document, BasePropertyDeclarationSyntax declaration, CancellationToken cancellationToken)
        {
            var accessors       = declaration.AccessorList.Accessors;
            var body            = accessors[0].Body;
            var returnStatement = body.Statements[0] as ReturnStatementSyntax;

            var arrowExpression = SyntaxFactory.ArrowExpressionClause(
                returnStatement.Expression);

            var newDeclaration = declaration;

            newDeclaration = ((dynamic)declaration)
                             .WithAccessorList(null)
                             .WithExpressionBody(arrowExpression)
                             .WithSemicolon(SyntaxFactory.Token(SyntaxKind.SemicolonToken));

            newDeclaration = newDeclaration.WithAdditionalAnnotations(Formatter.Annotation);

            return(await ReplaceNodeAsync(document, declaration, newDeclaration, cancellationToken));
        }
            private VirtualTreePoint GetEndPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part)
            {
                int endPosition;

                switch (part)
                {
                    case EnvDTE.vsCMPart.vsCMPartName:
                    case EnvDTE.vsCMPart.vsCMPartAttributes:
                    case EnvDTE.vsCMPart.vsCMPartHeader:
                    case EnvDTE.vsCMPart.vsCMPartWhole:
                    case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
                    case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
                        throw Exceptions.ThrowENotImpl();

                    case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
                        if (node.AttributeLists.Count == 0)
                        {
                            throw Exceptions.ThrowEFail();
                        }

                        endPosition = node.AttributeLists.Last().Span.End;
                        break;

                    case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
                        endPosition = node.Span.End;
                        break;

                    case EnvDTE.vsCMPart.vsCMPartNavigate:
                        var firstAccessorNode = FindFirstAccessorNode(node);
                        if (firstAccessorNode != null)
                        {
                            if (firstAccessorNode.Body != null)
                            {
                                return GetBodyEndPoint(text, firstAccessorNode.Body.CloseBraceToken);
                            }
                            else
                            {
                                // This is total weirdness from the old C# code model with auto props.
                                // If there isn't a body, the semi-colon is used
                                return GetBodyEndPoint(text, firstAccessorNode.SemicolonToken);
                            }
                        }

                        throw Exceptions.ThrowEFail();

                    case EnvDTE.vsCMPart.vsCMPartBody:
                        if (node.AccessorList != null && !node.AccessorList.CloseBraceToken.IsMissing)
                        {
                            return GetBodyEndPoint(text, node.AccessorList.CloseBraceToken);
                        }

                        throw Exceptions.ThrowEFail();

                    default:
                        throw Exceptions.ThrowEInvalidArg();
                }

                return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
            }
Esempio n. 41
0
        private void BasePropertyDeclarationProlog(BasePropertyDeclarationSyntax node)
        {
            _writer.WriteIndent();

            WriteAttributes(
                node,
                _writer.Configuration.LineBreaksAndWrapping.Other.PlacePropertyIndexerEventAttributeOnSameLine
            );

            WriteMemberModifiers(node.Modifiers);

            node.Type.Accept(this);
            _writer.WriteSpace();

            if (node.ExplicitInterfaceSpecifier != null)
                node.ExplicitInterfaceSpecifier.Accept(this);
        }
        internal static Accessibility GetDeclaredAccessibility(this BasePropertyDeclarationSyntax syntax, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            if (syntax == null)
            {
                throw new ArgumentNullException(nameof(syntax));
            }

            if (semanticModel == null)
            {
                throw new ArgumentNullException(nameof(semanticModel));
            }

            AccessLevel accessLevel = GetAccessLevel(syntax.Modifiers);

            if (accessLevel != AccessLevel.NotSpecified)
            {
                return(accessLevel.ToAccessibility());
            }

            PropertyDeclarationSyntax propertyDeclarationSyntax = syntax as PropertyDeclarationSyntax;

            if (propertyDeclarationSyntax != null)
            {
                if (propertyDeclarationSyntax.ExplicitInterfaceSpecifier == null)
                {
                    return(Accessibility.Private);
                }
                else
                {
                    return(Accessibility.Public);
                }
            }

            IndexerDeclarationSyntax indexerDeclarationSyntax = syntax as IndexerDeclarationSyntax;

            if (indexerDeclarationSyntax != null)
            {
                if (indexerDeclarationSyntax.ExplicitInterfaceSpecifier == null)
                {
                    return(Accessibility.Private);
                }
                else
                {
                    return(Accessibility.Public);
                }
            }

            EventDeclarationSyntax eventDeclarationSyntax = syntax as EventDeclarationSyntax;

            if (eventDeclarationSyntax != null)
            {
                if (eventDeclarationSyntax.ExplicitInterfaceSpecifier == null)
                {
                    return(Accessibility.Private);
                }
                else
                {
                    return(Accessibility.Public);
                }
            }

            ISymbol declaredSymbol = semanticModel.GetDeclaredSymbol(syntax, cancellationToken);

            return(declaredSymbol?.DeclaredAccessibility ?? Accessibility.NotApplicable);
        }
        private static Document GetTransformedDocumentForBasePropertyDeclaration(Document document, Diagnostic diagnostic, SyntaxNode root, SemanticModel semanticModel, BasePropertyDeclarationSyntax basePropertyDeclaration, CancellationToken cancellationToken)
        {
            if (basePropertyDeclaration.ExplicitInterfaceSpecifier == null && !basePropertyDeclaration.Modifiers.Any(SyntaxKind.OverrideKeyword))
            {
                ISymbol declaredSymbol = semanticModel.GetDeclaredSymbol(basePropertyDeclaration, cancellationToken);
                if (declaredSymbol == null || !NamedTypeHelpers.IsImplementingAnInterfaceMember(declaredSymbol))
                {
                    return document;
                }
            }

            return InsertInheritdocComment(document, diagnostic, root, basePropertyDeclaration, cancellationToken);
        }
        private static Document GetTransformedDocumentForBasePropertyDeclaration(Document document, Diagnostic diagnostic, SyntaxNode root, SemanticModel semanticModel, BasePropertyDeclarationSyntax basePropertyDeclaration, CancellationToken cancellationToken)
        {
            if (basePropertyDeclaration.ExplicitInterfaceSpecifier == null && !basePropertyDeclaration.Modifiers.Any(SyntaxKind.OverrideKeyword))
            {
                ISymbol declaredSymbol = semanticModel.GetDeclaredSymbol(basePropertyDeclaration, cancellationToken);
                if (declaredSymbol == null || !NamedTypeHelpers.IsImplementingAnInterfaceMember(declaredSymbol))
                {
                    return(document);
                }
            }

            return(InsertInheritdocComment(document, diagnostic, root, basePropertyDeclaration, cancellationToken));
        }
Esempio n. 45
0
        void ExportProperty(BasePropertyDeclarationSyntax v)
        {
            var v_type = GetType(v.Type);

            if (v_type == null)
            {
                Console.Error.WriteLine("无法识别的类型 " + v);
                return;
            }

            string name = "";

            if (v is PropertyDeclarationSyntax)
            {
                name = ((PropertyDeclarationSyntax)v).Identifier.Text;
            }
            else if (v is EventDeclarationSyntax)
            {
                name = ((EventDeclarationSyntax)v).Identifier.Text;
            }
            else if (v is IndexerDeclarationSyntax)
            {
                name = "Index";
            }

            if (step == ECompilerStet.ScanMember)
            {
                var property = new ULMemberInfo();
                property.Name            = name;
                property.DeclareTypeName = currentType.FullName;
                property.MemberType      = ULMemberInfo.EMemberType.Property;
                property.IsStatic        = ContainModifier(v.Modifiers, "static") || ContainModifier(v.Modifiers, "const");
                property.Modifier        = GetModifier(v.Modifiers);
                property.TypeName        = v_type.FullName;
                currentType.Members.Add(property);

                foreach (var ve in v.AccessorList.Accessors)
                {
                    var dB_Member = new ULMemberInfo();
                    dB_Member.DeclareTypeName = currentType.FullName;
                    dB_Member.TypeName        = v_type.FullName;
                    dB_Member.IsStatic        = property.IsStatic;
                    dB_Member.Modifier        = property.Modifier;
                    //dB_Member.method_abstract = ContainModifier(v.Modifiers, "abstract");
                    //dB_Member.method_virtual = ContainModifier(v.Modifiers, "virtual");
                    //dB_Member.method_override = ContainModifier(v.Modifiers, "override");
                    if (ve.Keyword.Text == "get")
                    {
                        dB_Member.MemberType = ULMemberInfo.EMemberType.PropertyGet;

                        dB_Member.Name = property.Name_PropertyGet;
                        if (v is IndexerDeclarationSyntax)
                        {
                            IndexerDeclarationSyntax indexerDeclarationSyntax = v as IndexerDeclarationSyntax;
                            dB_Member.Args = new List <ULMemberInfo.MethodArg>();
                            foreach (var a in indexerDeclarationSyntax.ParameterList.Parameters)
                            {
                                dB_Member.Args.Add(GetArgument(a));
                            }
                        }
                    }
                    else if (ve.Keyword.Text == "set")
                    {
                        dB_Member.MemberType = ULMemberInfo.EMemberType.PropertySet;
                        dB_Member.Name       = property.Name_PropertySet;
                        if (v is IndexerDeclarationSyntax)
                        {
                            IndexerDeclarationSyntax indexerDeclarationSyntax = v as IndexerDeclarationSyntax;
                            dB_Member.Args = new List <ULMemberInfo.MethodArg>();
                            foreach (var a in indexerDeclarationSyntax.ParameterList.Parameters)
                            {
                                dB_Member.Args.Add(GetArgument(a));
                            }
                            var arg = new ULMemberInfo.MethodArg();
                            arg.ArgName  = "value";
                            arg.TypeName = v_type.FullName;
                            dB_Member.Args.Add(arg);
                        }
                        else
                        {
                            var arg = new ULMemberInfo.MethodArg();
                            arg.ArgName  = "value";
                            arg.TypeName = v_type.FullName;
                            dB_Member.Args.Add(arg);
                        }
                    }
                    else if (ve.Keyword.Text == "add")
                    {
                        dB_Member.MemberType = ULMemberInfo.EMemberType.PropertyAdd;
                        dB_Member.Name       = property.Name_PropertyAdd;
                        var arg = new ULMemberInfo.MethodArg();
                        arg.ArgName  = "value";
                        arg.TypeName = v_type.FullName;
                        dB_Member.Args.Add(arg);
                    }
                    else if (ve.Keyword.Text == "remove")
                    {
                        dB_Member.MemberType = ULMemberInfo.EMemberType.PropertyRemove;
                        dB_Member.Name       = property.Name_PropertyRemove;
                        var arg = new ULMemberInfo.MethodArg();
                        arg.ArgName  = "value";
                        arg.TypeName = v_type.FullName;
                        dB_Member.Args.Add(arg);
                    }
                    currentType.Members.Add(dB_Member);
                }
            }
            else if (step == ECompilerStet.Compile)
            {
                currentMember = currentType.Members.Find(m => m.Name == name);
                foreach (var ve in v.AccessorList.Accessors)
                {
                    if (ve.Keyword.Text == "get")
                    {
                        currentMember = currentType.Members.Find(m => m.Name == currentMember.Name_PropertyGet);
                        ExportBody(ve.Body);
                    }
                    else if (ve.Keyword.Text == "set")
                    {
                        currentMember = currentType.Members.Find(m => m.Name == currentMember.Name_PropertySet);
                        ExportBody(ve.Body);
                    }
                    else if (ve.Keyword.Text == "add")
                    {
                        currentMember = currentType.Members.Find(m => m.Name == currentMember.Name_PropertyAdd);
                        ExportBody(ve.Body);
                    }
                    else if (ve.Keyword.Text == "remove")
                    {
                        currentMember = currentType.Members.Find(m => m.Name == currentMember.Name_PropertyRemove);
                        ExportBody(ve.Body);
                    }
                }
            }
        }
        private IEnumerable <MemberDeclarationSyntax> GetPropertiesAndMethods()
        {
            for (var interfaceIndex = 0; interfaceIndex < _interfacesToImplement.Length; interfaceIndex++)
            {
                var interfaceType = _interfacesToImplement[interfaceIndex];

                var typedFieldName             = interfaceIndex == 0 ? (ExpressionSyntax)FieldName : ParenthesizedExpression(CastExpression(interfaceType.ToTypeSyntax(), FieldName));
                var explicitInterfaceSpecifier = ExplicitInterfaceSpecifier((NameSyntax)interfaceType.ToTypeSyntax());

                foreach (var propertyInfo in interfaceType.GetProperties().OrderBy(p => p.Name, StringComparer.Ordinal))
                {
                    ParameterInfo[] indexParameters = propertyInfo.GetIndexParameters();
                    MethodInfo      getter          = propertyInfo.GetGetMethod();
                    MethodInfo      setter          = propertyInfo.GetSetMethod();

                    BasePropertyDeclarationSyntax propertyDeclarationSyntax = (indexParameters.Length == 0
                            ? (BasePropertyDeclarationSyntax)PropertyDeclaration(propertyInfo.PropertyType.ToTypeSyntax(), propertyInfo.Name)
                            : IndexerDeclaration(propertyInfo.PropertyType.ToTypeSyntax())
                                                                               .AddParameterListParameters(indexParameters.Select(p => Parameter(Identifier(p.Name)).WithType(p.ParameterType.ToTypeSyntax())).ToArray()))
                                                                              .WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier)
                                                                              .AddAttributeLists(ExcludeFromCodeCoverageAttributeSyntax)
                                                                              .WithAdditionalAnnotations(new SyntaxAnnotation(DeclaringTypeKind, (getter?.GetBaseDefinition() ?? setter?.GetBaseDefinition())?.DeclaringType.FullName));

                    if (getter != null)
                    {
                        propertyDeclarationSyntax = propertyDeclarationSyntax.AddAccessorListAccessors(
                            AccessorDeclaration(
                                SyntaxKind.GetAccessorDeclaration,
                                Block(ReturnStatement(
                                          indexParameters.Length == 0
                                        ? (ExpressionSyntax)MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, FieldName, IdentifierName(propertyInfo.Name))
                                        : ElementAccessExpression(FieldName).AddArgumentListArguments(indexParameters.Select(p => Argument(IdentifierName(p.Name))).ToArray())))));
                    }

                    if (setter != null)
                    {
                        ExpressionSyntax assignmentTarget = indexParameters.Length == 0
                            ? (ExpressionSyntax)MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, typedFieldName, IdentifierName(propertyInfo.Name))
                            : ElementAccessExpression(FieldName).AddArgumentListArguments(indexParameters.Select(p => Argument(IdentifierName(p.Name))).ToArray());

                        propertyDeclarationSyntax = propertyDeclarationSyntax.AddAccessorListAccessors(
                            AccessorDeclaration(
                                SyntaxKind.SetAccessorDeclaration,
                                Block(ExpressionStatement(AssignmentExpression(
                                                              SyntaxKind.SimpleAssignmentExpression,
                                                              assignmentTarget,
                                                              IdentifierName("value"))))));
                    }

                    yield return(propertyDeclarationSyntax);
                }

                IOrderedEnumerable <MethodInfo> orderedMethods = interfaceType
                                                                 .GetMethods()
                                                                 .Except(interfaceType.GetProperties().SelectMany(p => p.GetAccessors()))
                                                                 .OrderBy(m => m.Name, StringComparer.Ordinal)
                                                                 .ThenBy(m => string.Join(", ", m.GetParameters().Select(p => p.ParameterType.FullName)), StringComparer.Ordinal);

                foreach (var methodInfo in orderedMethods)
                {
                    var method = MethodDeclaration(methodInfo.ReturnType.ToTypeSyntax(), methodInfo.Name)
                                 .WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier)
                                 .AddParameterListParameters(
                        methodInfo.GetParameters().Select(p =>
                                                          Parameter(Identifier(p.Name))
                                                          .WithType(p.ParameterType.ToTypeSyntax())
                                                          .WithModifiers(p.IsDefined(typeof(ParamArrayAttribute), false) ? TokenList(Token(SyntaxKind.ParamsKeyword)) : TokenList()))
                        .ToArray())
                                 .AddAttributeLists(ExcludeFromCodeCoverageAttributeSyntax)
                                 .WithBody(Block())
                                 .WithAdditionalAnnotations(new SyntaxAnnotation(DeclaringTypeKind, methodInfo.GetBaseDefinition().DeclaringType.FullName));

                    if (methodInfo.IsGenericMethod)
                    {
                        method = method.WithTypeParameterList(TypeParameterList(SeparatedList(methodInfo.GetGenericArguments().Select(t => TypeParameter(t.Name)))));
                    }

                    var methodName = methodInfo.IsGenericMethod
                        ? GenericName(methodInfo.Name).AddTypeArgumentListArguments(methodInfo.GetGenericArguments().Select(t => t.ToTypeSyntax()).ToArray())
                        : (SimpleNameSyntax)IdentifierName(methodInfo.Name);

                    var invocation = InvocationExpression(
                        MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            typedFieldName,
                            methodName),
                        ArgumentList(SeparatedList(methodInfo.GetParameters().Select(p => Argument(IdentifierName(p.Name))))));

                    var block = Block(methodInfo.ReturnType == typeof(void) ? ExpressionStatement(invocation) : (StatementSyntax)ReturnStatement(invocation));

                    method = method.WithBody(block);

                    yield return(method);
                }
            }
        }
            private VirtualTreePoint GetStartPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part)
            {
                int startPosition;

                switch (part)
                {
                    case EnvDTE.vsCMPart.vsCMPartName:
                    case EnvDTE.vsCMPart.vsCMPartAttributes:
                    case EnvDTE.vsCMPart.vsCMPartHeader:
                    case EnvDTE.vsCMPart.vsCMPartWhole:
                    case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
                    case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
                        throw Exceptions.ThrowENotImpl();

                    case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
                        if (node.AttributeLists.Count == 0)
                        {
                            throw Exceptions.ThrowEFail();
                        }

                        goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;

                    case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
                        startPosition = node.SpanStart;
                        break;

                    case EnvDTE.vsCMPart.vsCMPartNavigate:
                        var firstAccessorNode = FindFirstAccessorNode(node);
                        if (firstAccessorNode != null)
                        {
                            var line = text.Lines.GetLineFromPosition(firstAccessorNode.SpanStart);
                            var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));

                            if (firstAccessorNode.Body != null)
                            {
                                return GetBodyStartPoint(text, firstAccessorNode.Body.OpenBraceToken, firstAccessorNode.Body.CloseBraceToken, indentation);
                            }
                            else if (!firstAccessorNode.SemicolonToken.IsMissing)
                            {
                                // This is total weirdness from the old C# code model with auto props.
                                // If there isn't a body, the semi-colon is used
                                return GetBodyStartPoint(text, firstAccessorNode.SemicolonToken, firstAccessorNode.SemicolonToken, indentation);
                            }
                        }

                        throw Exceptions.ThrowEFail();

                    case EnvDTE.vsCMPart.vsCMPartBody:
                        if (node.AccessorList != null && !node.AccessorList.OpenBraceToken.IsMissing)
                        {
                            var line = text.Lines.GetLineFromPosition(node.SpanStart);
                            var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));

                            return GetBodyStartPoint(text, node.AccessorList.OpenBraceToken, node.AccessorList.CloseBraceToken, indentation);
                        }

                        throw Exceptions.ThrowEFail();

                    default:
                        throw Exceptions.ThrowEInvalidArg();
                }

                return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
            }
Esempio n. 48
0
        public static void Go(OutputWriter writer, BasePropertyDeclarationSyntax property, bool isProxy = false)
        {
            writer.WriteLine();
            //TODO, doesnt ref make things slower ?, though it makes proprties behave as in c#

            var isInterface = property.Parent is InterfaceDeclarationSyntax;

            var getter =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.GetKeyword);
            var setter =
                property.AccessorList.Accessors.SingleOrDefault(
                    o => o.Keyword.RawKind == (decimal)SyntaxKind.SetKeyword);

            var isYield  = getter != null && getter.DescendantNodes().OfType <YieldStatementSyntax>().Any();
            var isStatic = property.Modifiers.Any(k => k.IsKind(SyntaxKind.StaticKeyword));

            ITypeSymbol iface;

            ISymbol[] proxies;

            var name = MemberUtilities.GetMethodName(property, ref isInterface, out iface, out proxies);

            var modifiers      = property.Modifiers;
            var propertySymbol = (IPropertySymbol)TypeProcessor.GetDeclaredSymbol(property);
            var type           = propertySymbol.Type;


            var acccessmodifiers = MemberUtilities.GetAccessModifiers(property, isInterface || propertySymbol.IsAbstract);

            var typeString = TypeProcessor.ConvertType(type);

            var hasGetter     = getter != null;
            var getterHasBody = hasGetter && getter.Body != null;

            var hasSetter     = setter != null;
            var setterHasBody = hasSetter && setter.Body != null;



            var    indexerDeclarationSyntax = property as IndexerDeclarationSyntax;
            var    isindexer  = indexerDeclarationSyntax != null;
            string getterbody = null;

            if (getterHasBody)
            {
                getterbody = Core.WriteBlock(getter.Body, false, writer.Indent + 2);

                if (!isProxy && isYield)
                {
                    var namedTypeSymbol = propertySymbol.Type as INamedTypeSymbol;
                    if (namedTypeSymbol != null)
                    {
                        //                        var iteratortype = namedTypeSymbol.TypeArguments[0];
                        //                        getterbody=String.Format("return new __IteratorBlock!({0})(delegate(__IteratorBlock!({0}) __iter){{ {1} }});",
                        //                            TypeProcessor.ConvertType(iteratortype),getterbody);

                        var className = propertySymbol.GetYieldClassName() + (
                            (((INamedTypeSymbol)propertySymbol.Type).TypeArguments.Any() && ((INamedTypeSymbol)propertySymbol.Type).TypeArguments[0].TypeKind == TypeKind.TypeParameter) ? "__G" : "");



                        // writer.WriteLine(accessString + returnTypeString + methodSignatureString + @params2 + constraints);

                        //writer.OpenBrace();

                        if (!propertySymbol.IsStatic)
                        {
                            getterbody = writer.WriteIndentToString() + ("return new " + className + "(this);");
                        }
                        else
                        {
                            getterbody = writer.WriteIndentToString() + ("return new " + className + "();");
                        }
                    }
                }
            }
            string setterbody = null;

            if (setterHasBody)
            {
                setterbody = Core.WriteString(setter.Body, false, writer.Indent + 2);
                if (isindexer)
                {
                    setterbody += writer.WriteIndentToString() + "return value;";
                }
                else
                {
                    if (hasGetter)
                    {
                        setterbody += writer.WriteIndentToString() + "return " + name + ";";
                    }
                }
            }

            if (getter == null && setter == null)
            {
                throw new Exception("Property must have either a get or a set");
            }

            string isOverride;

            var fieldName = WriteAutoFieldName(writer, name, modifiers, isInterface, hasGetter, getterHasBody,
                                               hasSetter, setterHasBody, typeString, out isOverride, (property is IndexerDeclarationSyntax));


            BracketedParameterListSyntax @params = null;

            if (indexerDeclarationSyntax != null)
            {
                @params = indexerDeclarationSyntax.ParameterList;
            }

            string parameters = null;

            if (@params != null)
            {
                parameters = WriteMethod.GetParameterListAsString(@params.Parameters, iface: proxies == null ? iface : null, writebraces: false);
            }

            WriteGetter(writer, isProxy, hasGetter, acccessmodifiers, typeString, name, proxies == null ? iface : null, getterHasBody, modifiers, isInterface, fieldName, getterbody, parameters, indexerDeclarationSyntax != null);

            WriteSetter(writer, isProxy, hasSetter, acccessmodifiers, name, typeString, proxies == null ? iface : null, isOverride, setterHasBody, modifiers, isInterface, fieldName, setterbody, parameters, isindexer, hasGetter);

//			if (!isindexer && !isInterface) //TODO: Find a better solution
//			{
//				var fieldacccessmodifiers = acccessmodifiers.Replace ("abstract", "").Replace ("virtual","").Replace("override","");
//
//				writer.WriteLine(fieldacccessmodifiers +  "__Property!(" + typeString + ")" + name + ";");
//				if (isStatic)
//				{
//					var staticWriter = new TempWriter ();
//
//					staticWriter.WriteLine (name + String.Format (" = __Property!(" + typeString + ")(__ToDelegate(&set{0}), __ToDelegate(&get{0}));", name));
//					Context.Instance.StaticInits.Add (staticWriter.ToString ());
//				}
//				else
//				{
//					var instanceWriter = new TempWriter ();
//
//					instanceWriter.WriteLine (name + String.Format (" = __Property!(" + typeString + ")((&set{0}), (&get{0}));", name));
//					Context.Instance.InstanceInits.Add (instanceWriter.ToString ());
//				}
//			}


            if (proxies != null)
            {
                foreach (var proxy in proxies)
                {
                    if (indexerDeclarationSyntax == null)
                    {
                        setterbody = writer.WriteIndentToString() + name + "=" + "value" + ";";
                        getterbody = writer.WriteIndentToString() + "return " + name + ";";
                    }
                    else
                    {
                        string parameters2 = "";
                        if (@params != null)
                        {
                            parameters2 = WriteMethod.GetParameterListAsString(@params.Parameters, iface: null, includeTypes: false, writebraces: false);
                            // parameters2 = WriteMethod.GetParameterListAsString(@params.Parameters, iface: proxies == null ? iface : null, writebraces: false);
                        }

                        setterbody = writer.WriteIndentToString() + "return opIndexAssign(value," + parameters2 + ");";// + "=" + "value" + ";";
                        getterbody = writer.WriteIndentToString() + "return opIndex(" + parameters2 + ");";
                    }


                    parameters = null;
                    if (@params != null)
                    {
                        parameters = WriteMethod.GetParameterListAsString(@params.Parameters, iface: proxy.ContainingType, writebraces: false);
                    }

                    WriteGetter(writer, isProxy, hasGetter, acccessmodifiers, typeString, name, proxy.ContainingType, getterHasBody, modifiers, isInterface, fieldName, getterbody, parameters, isindexer);

                    WriteSetter(writer, isProxy, hasSetter, acccessmodifiers, name, typeString, proxy.ContainingType, isOverride, setterHasBody, modifiers, isInterface, fieldName, setterbody, parameters, isindexer, hasGetter);
                }
            }
        }
Esempio n. 49
0
 public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
 {
     // Can't define property inside member.
     return null;
 }
        private Doc PrintBasePropertyDeclarationSyntax(
            BasePropertyDeclarationSyntax node)
        {
            EqualsValueClauseSyntax?         initializer = null;
            ExplicitInterfaceSpecifierSyntax?explicitInterfaceSpecifierSyntax =
                null;
            Doc identifier   = Doc.Null;
            Doc eventKeyword = Doc.Null;
            ArrowExpressionClauseSyntax?expressionBody = null;
            SyntaxToken?semicolonToken = null;

            if (node is PropertyDeclarationSyntax propertyDeclarationSyntax)
            {
                expressionBody = propertyDeclarationSyntax.ExpressionBody;
                initializer    = propertyDeclarationSyntax.Initializer;
                explicitInterfaceSpecifierSyntax = propertyDeclarationSyntax.ExplicitInterfaceSpecifier;
                identifier = this.PrintSyntaxToken(
                    propertyDeclarationSyntax.Identifier
                    );
                semicolonToken = propertyDeclarationSyntax.SemicolonToken;
            }
            else if (node is IndexerDeclarationSyntax indexerDeclarationSyntax)
            {
                expressionBody = indexerDeclarationSyntax.ExpressionBody;
                explicitInterfaceSpecifierSyntax = indexerDeclarationSyntax.ExplicitInterfaceSpecifier;
                identifier = Concat(
                    this.PrintSyntaxToken(indexerDeclarationSyntax.ThisKeyword),
                    this.Print(indexerDeclarationSyntax.ParameterList)
                    );
                semicolonToken = indexerDeclarationSyntax.SemicolonToken;
            }
            else if (node is EventDeclarationSyntax eventDeclarationSyntax)
            {
                eventKeyword = this.PrintSyntaxToken(
                    eventDeclarationSyntax.EventKeyword,
                    " "
                    );
                explicitInterfaceSpecifierSyntax = eventDeclarationSyntax.ExplicitInterfaceSpecifier;
                identifier = this.PrintSyntaxToken(
                    eventDeclarationSyntax.Identifier
                    );
                semicolonToken = eventDeclarationSyntax.SemicolonToken;
            }

            Doc contents = string.Empty;

            if (node.AccessorList != null)
            {
                var separator = SpaceIfNoPreviousComment;
                if (
                    node.AccessorList.Accessors.Any(
                        o => o.Body != null ||
                        o.ExpressionBody != null ||
                        o.Modifiers.Any() ||
                        o.AttributeLists.Any()
                        )
                    )
                {
                    separator = Line;
                }

                contents = Group(
                    Concat(
                        separator,
                        this.PrintSyntaxToken(node.AccessorList.OpenBraceToken),
                        Group(
                            Indent(
                                node.AccessorList.Accessors.Select(
                                    o => this.PrintAccessorDeclarationSyntax(
                                        o,
                                        separator
                                        )
                                    )
                                .ToArray()
                                )
                            ),
                        separator,
                        this.PrintSyntaxToken(node.AccessorList.CloseBraceToken)
                        )
                    );
            }
            else if (expressionBody != null)
            {
                contents = Concat(
                    this.PrintArrowExpressionClauseSyntax(expressionBody)
                    );
            }


            var parts = new Parts();

            parts.Push(this.PrintExtraNewLines(node));
            parts.Push(this.PrintAttributeLists(node, node.AttributeLists));

            return(Group(
                       Concat(
                           Concat(parts),
                           this.PrintModifiers(node.Modifiers),
                           eventKeyword,
                           this.Print(node.Type),
                           " ",
                           explicitInterfaceSpecifierSyntax != null
                        ? Concat(
                               this.Print(explicitInterfaceSpecifierSyntax.Name),
                               this.PrintSyntaxToken(
                                   explicitInterfaceSpecifierSyntax.DotToken
                                   )
                               )
                        : Doc.Null,
                           identifier,
                           contents,
                           initializer != null
                        ? this.PrintEqualsValueClauseSyntax(initializer)
                        : Doc.Null,
                           semicolonToken.HasValue
                        ? this.PrintSyntaxToken(semicolonToken.Value)
                        : Doc.Null
                           )
                       ));
        }
Esempio n. 51
0
		private string GetReturnType(BasePropertyDeclarationSyntax syntax)
		{
			var symbol = ModelExtensions.GetSymbolInfo(_semanticModel, syntax.Type).Symbol as ITypeSymbol;
			return symbol != null ? string.Format(": {0}", ResolveTypeName(symbol)) : string.Empty;
		}
Esempio n. 52
0
        public override SyntaxNode VisitParameter(ParameterSyntax node)
        {
            node = (ParameterSyntax)base.VisitParameter(node);

            int position = -1;

            if ((position < 0) && (node.Parent.Parent is BasePropertyDeclarationSyntax))
            {
                BasePropertyDeclarationSyntax pp = (BasePropertyDeclarationSyntax)node.Parent.Parent;
                foreach (AccessorDeclarationSyntax decl in pp.AccessorList.Accessors)
                {
                    if (decl.Body != null)
                    {
                        position = decl.Body.Span.Start;
                    }
                }
            }
            if ((position < 0) && (node.Parent.Parent is BaseMethodDeclarationSyntax))
            {
                BaseMethodDeclarationSyntax pp = (BaseMethodDeclarationSyntax)node.Parent.Parent;
                if (pp.Body != null)
                {
                    position = pp.Body.Span.Start;
                }
            }
            if (position < 0)
            {
                // no scope bodies for this formal parameter - no need to record for substitution
                return(node);
            }

            ExpressionSyntax substConst;

            if (TestConstSubstAttribute(node.AttributeLists, out substConst) && !TestConstSubstSuppressionAttribute(node.AttributeLists))
            {
                ImmutableArray <ISymbol> symbols = semanticModel.LookupSymbols(position, null, node.Identifier.Text);
                if (symbols.Length != 1)
                {
                    Debug.Assert(false);
                    throw new ArgumentException(String.Format("Template contains none or multiple symbols in scope for \"{0}\" which ought to be impossible (but could happen due to template code errors)", node.Identifier.Text));
                }
                ISymbol identifierSymbol = symbols[0];

                if (substitutions.ContainsKey(identifierSymbol))
                {
                    throw new ArgumentException(String.Format("template contains multiple field names \"{0}\"", identifierSymbol.Name));
                }


                if (!substitutions.ContainsKey(identifierSymbol))
                {
                    substitutions.Add(identifierSymbol, substConst);
                    substitutionNames[identifierSymbol.Name] = false;
#pragma warning disable CS0162 // unreachable
                    if (trace)
                    {
                        Console.WriteLine("ADDCONST {0} ==> {1}", identifierSymbol.Name, substConst);
                    }
#pragma warning restore CS0162
                }
                else
                {
                    if (!substConst.IsEquivalentTo(substitutions[identifierSymbol]))
                    {
                        throw new ArgumentException(String.Format("Multiple ConstAttribute() instances on \"{0}\" declare different substitution values", identifierSymbol.Name));
                    }
                }
            }

            return(node);
        }
Esempio n. 53
0
        private ImmutableArray<ParameterSymbol> ComputeParameters(Binder binder, BasePropertyDeclarationSyntax syntax, DiagnosticBag diagnostics)
        {
            var parameterSyntaxOpt = GetParameterListSyntax(syntax);
            var parameters = MakeParameters(binder, this, parameterSyntaxOpt, diagnostics);
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;

            foreach (ParameterSymbol param in parameters)
            {
                if (!this.IsNoMoreVisibleThan(param.Type, ref useSiteDiagnostics))
                {
                    diagnostics.Add(ErrorCode.ERR_BadVisIndexerParam, _location, this, param.Type);
                }
                else if ((object)_setMethod != null && param.Name == ParameterSymbol.ValueParameterName)
                {
                    diagnostics.Add(ErrorCode.ERR_DuplicateGeneratedName, _location, param.Name);
                }
            }

            diagnostics.Add(_location, useSiteDiagnostics);
            return parameters;
        }
Esempio n. 54
0
            public void Sort(BasePropertyDeclarationSyntax propertyDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken)
            {
                var type = propertyDeclaration.FirstAncestorOrSelf <TypeDeclarationSyntax>();

                if (type == null)
                {
                    return;
                }

                if (!this.sorted.Item.TryGetValue(type, out List <MemberDeclarationSyntax> members))
                {
                    members = new List <MemberDeclarationSyntax>(type.Members);
                    this.sorted.Item[type] = members;
                }

                var fromIndex = members.IndexOf(propertyDeclaration);

                members.RemoveAt(fromIndex);
                var toIndex = 0;

                for (var i = 0; i < members.Count; i++)
                {
                    var member = members[i];
                    if (member is FieldDeclarationSyntax ||
                        member is ConstructorDeclarationSyntax ||
                        member is BaseFieldDeclarationSyntax)
                    {
                        toIndex = i + 1;
                        continue;
                    }

                    if (member is MethodDeclarationSyntax)
                    {
                        toIndex = i;
                        break;
                    }

                    var otherPropertyDeclaration = member as BasePropertyDeclarationSyntax;
                    if (otherPropertyDeclaration == null || !otherPropertyDeclaration.IsPropertyOrIndexer())
                    {
                        continue;
                    }

                    var property      = (IPropertySymbol)semanticModel.GetDeclaredSymbolSafe(propertyDeclaration, cancellationToken);
                    var otherProperty = (IPropertySymbol)semanticModel.GetDeclaredSymbolSafe(otherPropertyDeclaration, cancellationToken);
                    if (GU0020SortProperties.PropertyPositionComparer.Default.Compare(property, otherProperty) == 0 &&
                        fromIndex < i)
                    {
                        toIndex = i + 1;
                        continue;
                    }

                    if (GU0020SortProperties.PropertyPositionComparer.Default.Compare(property, otherProperty) > 0)
                    {
                        toIndex = i + 1;
                        continue;
                    }

                    if (GU0020SortProperties.PropertyPositionComparer.Default.Compare(property, otherProperty) < 0)
                    {
                        toIndex = i;
                        break;
                    }
                }

                members.Insert(toIndex, propertyDeclaration);
            }
Esempio n. 55
0
 private static BaseParameterListSyntax GetParameterListSyntax(BasePropertyDeclarationSyntax syntax)
 {
     return (syntax.Kind() == SyntaxKind.IndexerDeclaration) ? ((IndexerDeclarationSyntax)syntax).ParameterList : null;
 }
 private SyntaxNode RegisterPropertyLikeDeclarationCodeFix(SyntaxNode syntaxRoot, BasePropertyDeclarationSyntax node, IndentationSettings indentationSettings)
 {
     return(this.ReformatElement(syntaxRoot, node, node.AccessorList.OpenBraceToken, node.AccessorList.CloseBraceToken, indentationSettings));
 }
 /// <summary>
 /// Given a syntax node that declares a property, indexer or an event, get the corresponding declared symbol.
 /// </summary>
 /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The symbol that was declared.</returns>
 public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
 {
     return GetDeclaredMemberSymbol(declarationSyntax);
 }
 public static bool HasNot(this BasePropertyDeclarationSyntax decl, SyntaxKind kind) => decl.Modifiers.HasNot(kind);
            private bool ComparePropertyDeclarations(
                BasePropertyDeclarationSyntax oldProperty,
                BasePropertyDeclarationSyntax newProperty,
                SyntaxNode newNodeParent,
                CodeModelEventQueue eventQueue)
            {
                Debug.Assert(oldProperty != null && newProperty != null);

                bool same = true;

                if (!StringComparer.Ordinal.Equals(CodeModelService.GetName(oldProperty), CodeModelService.GetName(newProperty)))
                {
                    EnqueueChangeEvent(newProperty, newNodeParent, CodeModelEventType.Rename, eventQueue);
                    same = false;
                }

                // If modifiers have changed enqueue a element changed (unknown change) node
                if (!CompareModifiers(oldProperty, newProperty))
                {
                    EnqueueChangeEvent(newProperty, newNodeParent, CodeModelEventType.Unknown, eventQueue);
                    same = false;
                }

                // If return type had changed enqueue a element changed (typeref changed) node
                if (!CompareTypes(oldProperty.Type, newProperty.Type))
                {
                    EnqueueChangeEvent(newProperty, newNodeParent, CodeModelEventType.TypeRefChange, eventQueue);
                    same = false;
                }

                same &= CompareChildren(
                    CompareAttributeLists,
                    oldProperty.AttributeLists.AsReadOnlyList(),
                    newProperty.AttributeLists.AsReadOnlyList(),
                    newProperty,
                    CodeModelEventType.Unknown,
                    eventQueue);

                if (oldProperty is IndexerDeclarationSyntax)
                {
                    var oldIndexer = (IndexerDeclarationSyntax)oldProperty;
                    var newIndexer = (IndexerDeclarationSyntax)newProperty;
                    same &= CompareChildren(
                        CompareParameters,
                        oldIndexer.ParameterList.Parameters.AsReadOnlyList(),
                        newIndexer.ParameterList.Parameters.AsReadOnlyList(),
                        newIndexer,
                        CodeModelEventType.SigChange,
                        eventQueue);
                }

                return same;
            }
        /// <summary>
        /// Add the field and respect StyleCop ordering.
        /// </summary>
        /// <param name="editor">The <see cref="DocumentEditor"/>.</param>
        /// <param name="containingType">The containing type.</param>
        /// <param name="property">The <see cref="BasePropertyDeclarationSyntax"/>.</param>
        /// <param name="comparer">The <see cref="IComparer{MemberDeclarationSyntax}"/>. If null <see cref="MemberDeclarationComparer.Default"/> is used.</param>
        /// <returns>The <paramref name="editor"/>.</returns>
        public static DocumentEditor AddProperty(this DocumentEditor editor, TypeDeclarationSyntax containingType, BasePropertyDeclarationSyntax property, IComparer <MemberDeclarationSyntax>?comparer = null)
        {
            if (editor is null)
            {
                throw new System.ArgumentNullException(nameof(editor));
            }

            if (containingType is null)
            {
                throw new System.ArgumentNullException(nameof(containingType));
            }

            if (property is null)
            {
                throw new System.ArgumentNullException(nameof(property));
            }

            editor.ReplaceNode(
                containingType,
                node => node.AddSorted(property, comparer));
            return(editor);
        }