public static void Go(OutputWriter writer, ConstructorInitializerSyntax method)
        {
            writer.WriteIndent();
            //    var symbl = TypeProcessor.GetSymbolInfo(method);
            //	var mysymbl = TypeProcessor.GetSymbolInfo(method.Parent);

            //   var className = symbl.Symbol.ContainingType;
            if (method.ThisOrBaseKeyword.RawKind == (int) SyntaxKind.ThisKeyword)
                writer.Write("this");
            else
                writer.Write("super");
//                writer.Write(TypeProcessor.ConvertType(className));

            writer.Write("(");
            bool first = true;
            foreach (var expression in method.ArgumentList.Arguments)
            {
                if (first)
                    first = false;
                else
                    writer.Write(", ");

                Core.Write(writer, expression.Expression);
            }
            writer.Write(")");
        }
Пример #2
0
        private ConstructorDeclarationSyntax ParseConstructorDeclaration(string typeName, SyntaxListBuilder <AnnotationSyntax> attributes, SyntaxListBuilder modifiers, TypeParameterListSyntax typeParameterList)
        {
            var name = this.ParseIdentifierToken();

            Debug.Assert(name.ValueText == typeName);

            var saveTerm = this._termState;

            this._termState |= TerminatorState.IsEndOfMethodSignature;
            try
            {
                var paramList = this.ParseParenthesizedParameterList(allowThisKeyword: false, allowDefaults: true, allowAttributes: true, allowFieldModifiers: false);


                JavaThrowsListClauseSyntax throws = this.ParseJavaThrowsListClause(true);

                ConstructorInitializerSyntax initializer = null;
                if (this.CurrentToken.Kind == SyntaxKind.ColonToken)
                {
                    bool isStatic = modifiers != null && modifiers.Any(SyntaxKind.StaticKeyword);
                    initializer = this.ParseConstructorInitializer(name.ValueText, isStatic);
                }

                BlockSyntax body;
                SyntaxToken semicolon;
                this.ParseBodyOrSemicolon(out body, out semicolon);

                return(_syntaxFactory.ConstructorDeclaration(attributes, modifiers.ToTokenList(), typeParameterList, name, paramList, throws, initializer, body, semicolon));
            }
            finally
            {
                this._termState = saveTerm;
            }
        }
        > GetConstructorInitializerParameterLists(
            SemanticModel semanticModel,
            int position,
            ConstructorInitializerSyntax constructorInitializer,
            CancellationToken cancellationToken
        )
        {
            var within = semanticModel.GetEnclosingNamedType(position, cancellationToken);
            if (
                within != null
                && (within.TypeKind == TypeKind.Struct || within.TypeKind == TypeKind.Class)
            )
            {
                var type =
                    constructorInitializer.Kind() == SyntaxKind.BaseConstructorInitializer
                        ? within.BaseType
                        : within;

                if (type != null)
                {
                    return type.InstanceConstructors
                        .Where(c => c.IsAccessibleWithin(within))
                        .Select(c => c.Parameters);
                }
            }

            return null;
        }
Пример #4
0
        public static void Go(OutputWriter writer, ConstructorInitializerSyntax method)
        {
            writer.WriteIndent();
            //    var symbl = TypeProcessor.GetSymbolInfo(method);
            //	var mysymbl = TypeProcessor.GetSymbolInfo(method.Parent);

            //   var className = symbl.Symbol.ContainingType;
            if (method.ThisOrBaseKeyword.RawKind == (int)SyntaxKind.ThisKeyword)
            {
                writer.Write("this");
            }
            else
            {
                writer.Write("super");
            }
//                writer.Write(TypeProcessor.ConvertType(className));

            writer.Write("(");
            bool first = true;

            foreach (var expression in method.ArgumentList.Arguments)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    writer.Write(", ");
                }

                Core.Write(writer, expression.Expression);
            }
            writer.Write(")");
        }
Пример #5
0
        public static void Write(this ConstructorInitializerSyntax syntax, IIndentedTextWriterWrapper textWriter, IContext context)
        {
            var symbol = (IMethodSymbol)context.SemanticModel.GetSymbolInfo(syntax).Symbol;

            if (syntax.Kind() == SyntaxKind.BaseConstructorInitializer)
            {
                textWriter.Write("(element % _M.DOT_LVL(typeObject.Level - 1))._C_0_");
                context.SignatureWriter.WriteSignature(symbol.Parameters.Select(p => p.Type).ToArray(), textWriter);
            }
            else if (syntax.Kind() == SyntaxKind.ThisConstructorInitializer)
            {
                textWriter.Write("(element % _M.DOT_LVL(typeObject.Level))");

                var signatureWriter      = textWriter.CreateTextWriterAtSameIndent();
                var hasGenericComponents = context.SignatureWriter.WriteSignature(symbol.Parameters.Select(p => p.Type).ToArray(), signatureWriter);

                if (hasGenericComponents)
                {
                    textWriter.Write("['_C_0_'..(");
                    textWriter.AppendTextWriter(signatureWriter);
                    textWriter.Write(")]");
                }
                else
                {
                    textWriter.Write("._C_0_");
                    textWriter.AppendTextWriter(signatureWriter);
                }
            }

            syntax.ArgumentList.Write(textWriter, context);

            textWriter.WriteLine(";");
        }
Пример #6
0
            public override void VisitConstructorInitializer(ConstructorInitializerSyntax node)
            {
                var ctor = this.semanticModel.GetSymbolSafe(node, this.cancellationToken);

                if (ctor != null)
                {
                    for (var i = 0; i < node.ArgumentList.Arguments.Count; i++)
                    {
                        var arg = node.ArgumentList.Arguments[i].Expression as IdentifierNameSyntax;
                        if (this.constructor.ParameterList.Parameters.TryGetSingle(x => x.Identifier.ValueText == arg?.Identifier.ValueText, out ParameterSyntax match))
                        {
                            if (this.ParameterNameMap.ContainsKey(match))
                            {
                                this.ParameterNameMap[match] = null;
                            }
                            else
                            {
                                if (ctor.Parameters.Length - 1 <= i &&
                                    ctor.Parameters[ctor.Parameters.Length - 1].IsParams)
                                {
                                    this.ParameterNameMap.Add(match, null);
                                }
                                else
                                {
                                    this.ParameterNameMap.Add(match, ctor.Parameters[i].Name);
                                }
                            }
                        }
                    }
                }

                base.VisitConstructorInitializer(node);
            }
Пример #7
0
        public override void VisitConstructorInitializer(ConstructorInitializerSyntax node)
        {
            var binder = _enclosing.WithAdditionalFlags(BinderFlags.ConstructorInitializer);

            AddToMap(node, binder);
            VisitConstructorInitializerArgumentList(node, node.ArgumentList, binder);
        }
Пример #8
0
 private static TextSpan CreateSpanForConstructorInitializer(
     ConstructorInitializerSyntax constructorInitializer
     ) =>
 CreateSpan(
     constructorInitializer.ThisOrBaseKeyword,
     constructorInitializer.ArgumentList.CloseParenToken
     );
Пример #9
0
        public override void VisitConstructorInitializer(ConstructorInitializerSyntax node)
        {
            if (this.method.MethodKind == MethodKind.Constructor)
            {
                var calledCtor = this.semanticModel.GetSymbolSafe(node, this.cancellationToken);
                if (this.IsValidCtor(calledCtor))
                {
                    var callingCtor = this.semanticModel.GetDeclaredSymbolSafe(node.Parent, this.cancellationToken) as IMethodSymbol;
                    if (SymbolComparer.Equals(calledCtor.ContainingType, callingCtor?.ContainingType))
                    {
                        this.initializers.Add(node);
                    }
                    else if (this.ctors.Contains(callingCtor))
                    {
                        this.initializers.Add(node);
                    }
                }
            }
            else
            {
                this.initializers.Add(node);
            }

            base.VisitConstructorInitializer(node);
        }
Пример #10
0
        private bool ReplacementBreaksConstructorInitializer(ConstructorInitializerSyntax ctorInitializer, ConstructorInitializerSyntax newCtorInitializer)
        {
            var attributeSym    = this.OriginalSemanticModel.GetSymbolInfo(ctorInitializer).Symbol;
            var newAttributeSym = this.SpeculativeSemanticModel.GetSymbolInfo(newCtorInitializer).Symbol;

            return(!SymbolsAreCompatible(attributeSym, newAttributeSym));
        }
        public static void Analyze(SyntaxNodeAnalysisContext context, ConstructorDeclarationSyntax constructor)
        {
            if (constructor.ParameterList?.Parameters.Any() == false &&
                constructor.Body?.Statements.Any() == false)
            {
                SyntaxTokenList modifiers = constructor.Modifiers;

                if (modifiers.Contains(SyntaxKind.PublicKeyword) &&
                    !modifiers.Contains(SyntaxKind.StaticKeyword))
                {
                    ConstructorInitializerSyntax initializer = constructor.Initializer;

                    if (initializer == null ||
                        initializer.ArgumentList?.Arguments.Any() == false)
                    {
                        if (IsSingleInstanceConstructor(constructor) &&
                            constructor
                            .DescendantTrivia(constructor.Span)
                            .All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                        {
                            context.ReportDiagnostic(DiagnosticDescriptors.RemoveRedundantConstructor, constructor);
                        }
                    }
                }
            }
        }
Пример #12
0
        private bool ReplacementBreaksConstructorInitializer(ConstructorInitializerSyntax ctorInitializer, ConstructorInitializerSyntax newCtorInitializer)
        {
            var originalSymbol = this.OriginalSemanticModel.GetSymbolInfo(ctorInitializer, CancellationToken).Symbol;
            var newSymbol      = this.SpeculativeSemanticModel.GetSymbolInfo(newCtorInitializer, CancellationToken).Symbol;

            return(!SymbolsAreCompatible(originalSymbol, newSymbol));
        }
Пример #13
0
 public static Doc PrintWithConditionalSpace(
     ConstructorInitializerSyntax node,
     string groupId
     )
 {
     return(Print(node, groupId));
 }
        private bool TryGetConstructorInitializer(
            SyntaxNode root,
            int position,
            ISyntaxFactsService syntaxFacts,
            SignatureHelpTriggerReason triggerReason,
            CancellationToken cancellationToken,
            out ConstructorInitializerSyntax expression
            )
        {
            if (
                !CommonSignatureHelpUtilities.TryGetSyntax(
                    root,
                    position,
                    syntaxFacts,
                    triggerReason,
                    IsTriggerToken,
                    IsArgumentListToken,
                    cancellationToken,
                    out expression
                    )
                )
            {
                return(false);
            }

            return(expression.ArgumentList != null);
        }
Пример #15
0
 public static ITypeSymbol GetTypeSymbol(
     this SemanticModel semanticModel,
     ConstructorInitializerSyntax constructorInitializer,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(Microsoft.CodeAnalysis.CSharp.CSharpExtensions
            .GetTypeInfo(semanticModel, constructorInitializer, cancellationToken)
            .Type);
 }
 private static bool IsArgumentListToken(
     ConstructorInitializerSyntax expression,
     SyntaxToken token
     )
 {
     return(expression.ArgumentList != null &&
            expression.ArgumentList.Span.Contains(token.SpanStart) &&
            token != expression.ArgumentList.CloseParenToken);
 }
        private bool TryGetConstructorInitializer(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ConstructorInitializerSyntax expression)
        {
            if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression))
            {
                return false;
            }

            return expression.ArgumentList != null;
        }
Пример #18
0
 // TODO 0 where is this used? I changed it and nothing broke
 public static Doc Print(ConstructorInitializerSyntax node)
 {
     return(Doc.Indent(
                Doc.HardLine,
                Token.Print(node.ColonToken, " "),
                Token.Print(node.ThisOrBaseKeyword),
                ArgumentList.Print(node.ArgumentList)
                ));
 }
Пример #19
0
 internal override bool TryGetSpeculativeSemanticModelCore(
     SyntaxTreeSemanticModel parentModel,
     int position,
     ConstructorInitializerSyntax constructorInitializer,
     out SemanticModel speculativeModel
     )
 {
     throw ExceptionUtilities.Unreachable;
 }
Пример #20
0
        public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan)
        {
            if (initializer == null)
            {
                return(false);
            }

            return(initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan)));
        }
Пример #21
0
 public static ITypeSymbol GetTypeSymbol(
     this SemanticModel semanticModel,
     ConstructorInitializerSyntax constructorInitializer,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(semanticModel
            .GetTypeInfo(constructorInitializer, cancellationToken)
            .Type);
 }
Пример #22
0
 public new void AddChildren()
 {
     base.AddChildren();
     Kind                  = Node.Kind();
     _identifier           = ((ConstructorDeclarationSyntax)Node).Identifier;
     _identifierIsChanged  = false;
     _initializer          = ((ConstructorDeclarationSyntax)Node).Initializer;
     _initializerIsChanged = false;
 }
Пример #23
0
        private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext context)
        {
            var constructor = (ConstructorDeclarationSyntax)context.Node;

            if (constructor.ContainsDiagnostics)
            {
                return;
            }

            if (constructor.ParameterList?.Parameters.Any() != false)
            {
                return;
            }

            if (constructor.Body?.Statements.Any() != false)
            {
                return;
            }

            SyntaxTokenList modifiers = constructor.Modifiers;

            if (!modifiers.Contains(SyntaxKind.PublicKeyword))
            {
                return;
            }

            if (modifiers.Contains(SyntaxKind.StaticKeyword))
            {
                return;
            }

            ConstructorInitializerSyntax initializer = constructor.Initializer;

            if (initializer != null &&
                initializer.ArgumentList?.Arguments.Any() != false)
            {
                return;
            }

            if (!IsSingleInstanceConstructor(constructor))
            {
                return;
            }

            if (constructor.HasDocumentationComment())
            {
                return;
            }

            if (!constructor.DescendantTrivia(constructor.Span).All(f => f.IsWhitespaceOrEndOfLineTrivia()))
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.RemoveRedundantConstructor, constructor);
        }
Пример #24
0
        private static bool IsInitializerEmptyOrRedundant(ConstructorInitializerSyntax initializer)
        {
            if (initializer == null)
            {
                return(true);
            }

            return(initializer.ArgumentList.Arguments.Count == 0 &&
                   initializer.ThisOrBaseKeyword.IsKind(SyntaxKind.BaseKeyword));
        }
Пример #25
0
 private Doc PrintConstructorInitializerSyntax(
     ConstructorInitializerSyntax node)
 {
     return(Indent(
                HardLine,
                this.PrintSyntaxToken(node.ColonToken, " "),
                this.PrintSyntaxToken(node.ThisOrBaseKeyword),
                this.PrintArgumentListSyntax(node.ArgumentList)
                ));
 }
Пример #26
0
 public static ConstructorDeclarationSyntax ConstructorDeclaration(
     IEnumerable <SyntaxKind> modifiers, string className, IEnumerable <ParameterSyntax> parameters = null,
     IEnumerable <StatementSyntax> statements = null, ConstructorInitializerSyntax constructorInitializer = null)
 {
     return(Syntax.ConstructorDeclaration(className)
            .WithModifiers(TokenList(modifiers))
            .WithParameterList(Syntax.ParameterList(parameters.ToSeparatedList()))
            .WithBody(Syntax.Block(statements.ToSyntaxList()))
            .WithInitializer(constructorInitializer));
 }
Пример #27
0
        private static ArgumentSyntax CriteriaArg(ConstructorInitializerSyntax initializer, IMethodSymbol ctor)
        {
            if (ctor.Parameters[0].Type == KnownSymbol.FuncOfT &&
                ctor.Parameters[1].Type == KnownSymbol.IObservableOfT)
            {
                return(initializer.ArgumentList.Arguments[0]);
            }

            return(initializer.ArgumentList.Arguments[1]);
        }
Пример #28
0
        private Block BuildConstructorInitializer(ConstructorInitializerSyntax initializer, Block currentBlock)
        {
            currentBlock.ReversedInstructions.Add(initializer);

            var arguments = initializer.ArgumentList == null
                ? Enumerable.Empty <ExpressionSyntax>()
                : initializer.ArgumentList.Arguments.Select(a => a.Expression);

            return(BuildExpressions(arguments, currentBlock));
        }
Пример #29
0
 internal override bool TryGetSpeculativeSemanticModelCore(
     SyntaxTreeSemanticModel parentModel,
     int position,
     ConstructorInitializerSyntax constructorInitializer,
     out SemanticModel speculativeModel
     )
 {
     speculativeModel = null;
     return(false);
 }
Пример #30
0
        private MethodDeclarationSyntax ParseMethodDeclaration(
            SyntaxListBuilder <AnnotationSyntax> attributes,
            SyntaxListBuilder modifiers,
            TypeSyntax type,
            SyntaxToken identifier,
            TypeParameterListSyntax typeParameterList, bool isDtor)
        {
            // Parse the name (it could be qualified)
            var saveTerm = this._termState;

            this._termState |= TerminatorState.IsEndOfMethodSignature;

            var paramList = this.ParseParenthesizedParameterList(allowThisKeyword: true, allowDefaults: true,
                                                                 allowAttributes: true, allowFieldModifiers: true);

            JavaThrowsListClauseSyntax throws = this.ParseJavaThrowsListClause(true);


            if (this.CurrentToken.Kind == SyntaxKind.ColonToken)
            {
                // Use else if, rather than if, because if we see both a constructor initializer and a constraint clause, we're too lost to recover.
                var colonToken = this.CurrentToken;
                // Set isStatic to false because pretending we're in a static constructor will just result in more errors.
                ConstructorInitializerSyntax initializer = this.ParseConstructorInitializer(identifier.ValueText, isStatic: false);
                initializer = this.AddErrorToFirstToken(initializer, ErrorCode.ERR_UnexpectedCharacter, colonToken.Text);
                //CONSIDER: better error code?
                paramList = AddTrailingSkippedSyntax(paramList, initializer);

                // CONSIDER: Parsing an invalid constructor initializer could, conceivably, get us way
                // off track.  If this becomes a problem, an alternative approach would be to generalize
                // EatTokenWithPrejudice in such a way that we can just skip everything until we recognize
                // our context again (perhaps an open brace).
            }


            this._termState = saveTerm;

            BlockSyntax body;
            SyntaxToken semicolon;

            this.ParseBodyOrSemicolon(out body, out semicolon);


            return
                (_syntaxFactory.MethodDeclaration(isDtor ? SyntaxKind.DestructorDeclaration : SyntaxKind.MethodDeclaration,
                                                  attributes,
                                                  modifiers.ToTokenList(),
                                                  typeParameterList,
                                                  type,
                                                  identifier,
                                                  paramList,
                                                  throws,
                                                  body,
                                                  semicolon));
        }
            public override void VisitConstructorInitializer(ConstructorInitializerSyntax node)
            {
                if (this.visited.Add(node) &&
                    this.semanticModel.GetSymbolSafe(node, this.cancellationToken) is IMethodSymbol ctor &&
                    ctor.TrySingleDeclaration(this.cancellationToken, out ConstructorDeclarationSyntax declaration))
                {
                    this.Visit(declaration);
                }

                base.VisitConstructorInitializer(node);
            }
Пример #32
0
            public override void VisitConstructorInitializer(ConstructorInitializerSyntax node)
            {
                var ctor = this.semanticModel.GetSymbolSafe(node, this.cancellationToken);

                if (ctor.TryGetSingleDeclaration(this.cancellationToken, out ConstructorDeclarationSyntax declaration))
                {
                    this.Visit(declaration);
                }

                base.VisitConstructorInitializer(node);
            }
 public static ConstructorDeclarationSyntax ConstructorDeclaration(
     SyntaxList<AttributeListSyntax> attributeLists,
     SyntaxTokenList modifiers,
     SyntaxToken identifier,
     ParameterListSyntax parameterList,
     ConstructorInitializerSyntax initializer,
     ArrowExpressionClauseSyntax expressionBody)
     => ConstructorDeclaration(
         attributeLists,
         modifiers,
         identifier,
         parameterList,
         initializer,
         default(BlockSyntax),
         expressionBody,
         default(SyntaxToken));
 public ConstructorDeclarationSyntax Update(
     SyntaxList<AttributeListSyntax> attributeLists,
     SyntaxTokenList modifiers, 
     SyntaxToken identifier,
     ParameterListSyntax parameterList, 
     ConstructorInitializerSyntax initializer, 
     BlockSyntax body, 
     SyntaxToken semicolonToken)
     => Update(
         attributeLists, 
         modifiers, 
         identifier, 
         parameterList, 
         initializer, 
         body, 
         default(ArrowExpressionClauseSyntax), 
         semicolonToken);
        private async Task<Document> PropagateConstructorParams(
            Document document, 
            ConstructorInitializerSyntax constructorInitializerNode, 
            ImmutableArray<IParameterSymbol> baseConstrParams, 
            CancellationToken cancellationToken)
        {
            var semanticModel = await document.GetSemanticModelAsync();
            var classDecl = constructorInitializerNode.FirstAncestorOrSelf<ClassDeclarationSyntax>();
            var classSymbol = semanticModel.GetDeclaredSymbol(classDecl);
            var constructorDecl = constructorInitializerNode.FirstAncestorOrSelf<ConstructorDeclarationSyntax>();

            var constructorSymbol = classSymbol.Constructors
                .Where(p => p.Parameters.Count() == constructorDecl.ParameterList.Parameters.Count)
                .FirstOrDefault();

            var invArgList = constructorInitializerNode.ArgumentList;
            var declParamList = constructorDecl.ParameterList;

            int idx = -1;
            foreach(var baseP in baseConstrParams)
            {
                idx++;

                if (constructorSymbol.Parameters.Any(p => p.Type.Name == baseP.Type.Name))
                    continue;

                declParamList = declParamList.AddParameters(
                    SyntaxFactory.Parameter(
                        SyntaxFactory.Identifier(baseP.Name))
                    .WithType(
                        SyntaxFactory.IdentifierName(baseP.Type.Name)));

                invArgList = SyntaxFactory.ArgumentList(invArgList.Arguments.Insert(idx, SyntaxFactory.Argument(SyntaxFactory.IdentifierName(baseP.Name))));
            }

            var root = await document.GetSyntaxRootAsync();

            var newConstructor = constructorDecl.WithParameterList(declParamList)
                .WithInitializer(constructorInitializerNode.WithArgumentList(invArgList));

            root = root.ReplaceNode(constructorDecl, newConstructor);


            return document.WithSyntaxRoot(root);
        }
        public ConstructorInitializerTranslation(ConstructorInitializerSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
        {

            ThisOrBaseKeyword = syntax.ThisOrBaseKeyword.Get(this);
            ArgumentList = syntax.ArgumentList.Get<ArgumentListTranslation>(this);
        }
Пример #37
0
        /// <summary>
        /// Gets a list of method or indexed property symbols for a syntax node.
        /// </summary>
        /// <param name="initializer">The syntax node to get semantic information for.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        public ImmutableArray<ISymbol> GetMemberGroup(ConstructorInitializerSyntax initializer, CancellationToken cancellationToken = default(CancellationToken))
        {
            CheckSyntaxNode(initializer);

            return CanGetSemanticInfo(initializer)
                ? StaticCast<ISymbol>.From(this.GetMemberGroupWorker(initializer, SymbolInfoOptions.DefaultOptions, cancellationToken))
                : ImmutableArray<ISymbol>.Empty;
        }
Пример #38
0
        /// <summary>
        /// Gets type information about a constructor initializer.
        /// </summary>
        /// <param name="constructorInitializer">The syntax node to get semantic information for.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        public TypeInfo GetTypeInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken))
        {
            CheckSyntaxNode(constructorInitializer);

            return CanGetSemanticInfo(constructorInitializer)
                ? GetTypeInfoWorker(constructorInitializer, cancellationToken)
                : CSharpTypeInfo.None;
        }
Пример #39
0
        /// <summary>
        /// Bind the constructor initializer in the context of the specified location and get semantic information
        /// such as type, symbols and diagnostics. This method is used to get semantic information about a constructor
        /// initializer that did not actually appear in the source code.
        /// 
        /// NOTE: This will only work in locations where there is already a constructor initializer.
        /// </summary>
        /// <param name="position">A character position used to identify a declaration scope and accessibility. This
        /// character position must be within the FullSpan of the Root syntax node in this SemanticModel.
        /// Furthermore, it must be within the span of an existing constructor initializer.
        /// </param>
        /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. This syntax node
        /// need not and typically does not appear in the source code referred to SemanticModel instance.</param>
        /// <returns>The semantic information for the topmost node of the constructor initializer.</returns>
        public SymbolInfo GetSpeculativeSymbolInfo(int position, ConstructorInitializerSyntax constructorInitializer)
        {
            Debug.Assert(CanGetSemanticInfo(constructorInitializer, isSpeculative: true));

            position = CheckAndAdjustPosition(position);

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

            // NOTE: since we're going to be depending on a MemberModel to do the binding for us,
            // we need to find a constructor initializer in the tree of this semantic model.
            // NOTE: This approach will not allow speculative binding of a constructor initializer
            // on a constructor that didn't formerly have one.
            // TODO: Should we support positions that are not in existing constructor initializers?
            // If so, we will need to build up the context that would otherwise be built up by
            // InitializerMemberModel.
            var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<ConstructorInitializerSyntax>().FirstOrDefault();

            if (existingConstructorInitializer == null)
            {
                return SymbolInfo.None;
            }

            MemberSemanticModel memberModel = GetMemberModel(existingConstructorInitializer);

            if (memberModel == null)
            {
                return SymbolInfo.None;
            }

            var binder = this.GetEnclosingBinder(position);
            if (binder != null)
            {
                var diagnostics = DiagnosticBag.GetInstance();

                if (constructorInitializer.ArgumentList != null)
                {
                    binder = new ExecutableCodeBinder(constructorInitializer.ArgumentList, binder.ContainingMemberOrLambda, binder);
                }

                var bnode = memberModel.Bind(binder, constructorInitializer, diagnostics);
                var binfo = memberModel.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, bnode, bnode, boundNodeForSyntacticParent: null, binderOpt: binder);
                diagnostics.Free();
                return binfo;
            }
            else
            {
                return SymbolInfo.None;
            }
        }
        private static bool IsInitializerEmptyOrRedundant(ConstructorInitializerSyntax initializer)
        {
            if (initializer == null)
            {
                return true;
            }

            return initializer.ArgumentList != null &&
                !initializer.ArgumentList.Arguments.Any() &&
                initializer.ThisOrBaseKeyword.IsKind(SyntaxKind.BaseKeyword);
        }
Пример #41
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitConstructorInitializer(ConstructorInitializerSyntax node)
 {
     this.OnNodeVisited(node);
     if (!this.traverseRootOnly) base.VisitConstructorInitializer(node);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 public override sealed void VisitConstructorInitializer(ConstructorInitializerSyntax node)
 {
     this.OnNodeVisited(node, this.type.IsInstanceOfType(node));
     base.VisitConstructorInitializer(node);
 }
 private IEnumerable<ITypeSymbol> InferTypeInConstructorInitializer(ConstructorInitializerSyntax initializer, int index, ArgumentSyntax argument = null)
 {
     var info = this.semanticModel.GetSymbolInfo(initializer, cancellationToken);
     var methods = info.GetBestOrAllSymbols().OfType<IMethodSymbol>();
     return InferTypeInArgument(index, methods, argument);
 }
        /// <summary>
        /// the constructor initializer will be extended
        /// so that it will accept the mixin as parameter.
        /// See rule 3 from above
        /// </summary>
        /// <param name="oldConstructorInitializer"></param>
        /// <returns></returns>
        public ConstructorInitializerSyntax ExtendConstructorInitialization(
            ConstructorInitializerSyntax oldConstructorInitializer)
        {
            // don't do anything if initializer points to base
            if (oldConstructorInitializer.IsKind(SyntaxKind.BaseConstructorInitializer))
                return oldConstructorInitializer;
            var parameterName = _mixin.Name.ConvertFieldNameToParameterName();

            // arguments that are already used in the constructor initializer
            var arguments = oldConstructorInitializer
                .ArgumentList
                .Arguments
                .ToArray();

            // the initializer can have default parameters that are not visible in the syntax tree,
            // therefore we have to use some additional semantic information here
            var initalizerSymbol = _semantic.GetSymbolInfo(oldConstructorInitializer).Symbol as IMethodSymbol;
            if (initalizerSymbol != null)
            {
                var constructorArguments = new List<ConstructorArgument>();

                // special case: the initializer does not have any parameters yet
                // so we simply add one
                if(initalizerSymbol.Parameters.Length == 0)
                {
                    return oldConstructorInitializer
                        .AddArgumentListArguments(
                            Argument(IdentifierName(parameterName)));
                }

                // otherwise, try to map the arguments from the initializer
                // with the parameters of the constructor and add the new argument
                // at the correct position
                for (var i=0; i < initalizerSymbol.Parameters.Length;i++)
                {
                    var parameter = initalizerSymbol.Parameters[i];
                    // this constructor argument will hold our new mixin
                    if (parameter.Name == parameterName)
                    {
                        constructorArguments.Add(
                            new ConstructorArgument(
                                parameter.Name,
                                expression: IdentifierName(parameterName),
                                isMixinParameter: true));
                    }
                    else
                    {
                        // we either have an argument with an explicit name
                        // or we have an argument at the same position
                        // or we can ommit this parameter
                        ArgumentSyntax argument = arguments
                            .Where(x => x.NameColon != null)
                            .FirstOrDefault(x => x.NameColon.Name.GetText().ToString() == parameter.Name);
                        // argument identified by name or by position
                        if (argument == null)
                            if (arguments.Length > i)
                                argument = arguments[i];
                        if (argument != null)
                            constructorArguments.Add(new ConstructorArgument(parameter.Name,expression: argument.Expression));
                        else // no argument found => argument was omitted
                            constructorArguments.Add(new ConstructorArgument(parameter.Name,canBeOmitted:true));
                    }
                }

                // now we have to check again if we must use explicit naming
                // this is the case if a previous parameter is omitted but
                // the current one is not
                ConstructorArgument previous = null;
                foreach (var constructorArgument in constructorArguments)
                {
                    constructorArgument.NeedsExplicitNaming =
                        previous != null &&
                        previous.CanBeOmitted &&
                        !constructorArgument.CanBeOmitted;
                    previous = constructorArgument;
                }                    

                // create the new initializer by recreating the complete argument list
                var newConstructorInitializer = oldConstructorInitializer
                    .WithArgumentList(ArgumentList()
                    .AddArguments(constructorArguments
                        .Where(x => x.Expression != null)
                        .Select(x => x.NeedsExplicitNaming ? 
                            Argument(NameColon(x.Name), default(SyntaxToken),x.Expression) : 
                            Argument(x.Expression))                           
                        .ToArray()));
                return newConstructorInitializer;
            }

            return oldConstructorInitializer;
        } 
 private static bool IsArgumentListToken(ConstructorInitializerSyntax expression, SyntaxToken token)
 {
     return expression.ArgumentList != null &&
         expression.ArgumentList.Span.Contains(token.SpanStart) &&
         token != expression.ArgumentList.CloseParenToken;
 }
Пример #46
0
        public void VisitConstructorInitializer(ConstructorInitializerSyntax node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            node.Validate();

            if (_writer.Configuration.LineBreaksAndWrapping.Other.PlaceConstructorInitializerOnSameLine)
            {
                _writer.WriteSpace();
            }
            else
            {

                _writer.WriteLine();

                _writer.PushIndent();
                _writer.WriteIndent();
            }

            _writer.WriteSyntax(Syntax.Colon);
            _writer.WriteSpace();
            _writer.WriteKeyword(node.Kind == ThisOrBase.This ? PrinterKeyword.This : PrinterKeyword.Base);
            node.ArgumentList.Accept(this);

            if (!_writer.Configuration.LineBreaksAndWrapping.Other.PlaceConstructorInitializerOnSameLine)
                _writer.PopIndent();
        }
 /// <summary>
 /// Creates a SemanticModel for a constructor initializer (": this(...)" or ": base(...)").
 /// </summary>
 internal static InitializerSemanticModel Create(CSharpCompilation compilation, ConstructorInitializerSyntax syntax, MethodSymbol methodSymbol, Binder rootBinder)
 {
     return new InitializerSemanticModel(compilation, syntax, methodSymbol, rootBinder);
 }
Пример #48
0
            public override void VisitConstructorInitializer(ConstructorInitializerSyntax node)
            {
                base.VisitConstructorInitializer(node);

                var method = context.SemanticModel.GetSymbolInfo(node).Symbol as IMethodSymbol;
                if (method != null)
                {
                    CheckArguments(node.ArgumentList.Arguments, method.Parameters);
                }
            }
        private static void RegisterActionForBaseCall(CodeFixContext context, SyntaxNode root, ConstructorInitializerSyntax initializer)
        {
            var constructor = initializer.Parent as ConstructorDeclarationSyntax;
            if (constructor == null)
            {
                return;
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    TitleRemoveBaseCall,
                    c =>
                    {
                        var newRoot = RemoveInitializer(root, constructor);
                        return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                    },
                    TitleRemoveBaseCall),
                context.Diagnostics);
        }
Пример #50
0
        internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel)
        {
            position = CheckAndAdjustPosition(position);

            var model = this.GetMemberModel(position);
            if (model != null)
            {
                return model.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel);
            }

            speculativeModel = null;
            return false;
        }
Пример #51
0
        /// <summary>
        /// Returns what symbol(s), if any, the given constructor initializer syntax bound to in the program.
        /// </summary>
        /// <param name="constructorInitializer">The syntax node to get semantic information for.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        public SymbolInfo GetSymbolInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken))
        {
            CheckSyntaxNode(constructorInitializer);

            return CanGetSemanticInfo(constructorInitializer)
                ? GetSymbolInfoWorker(constructorInitializer, SymbolInfoOptions.DefaultOptions, cancellationToken)
                : SymbolInfo.None;
        }
Пример #52
0
 /// <summary>
 /// Get a SemanticModel object that is associated with a constructor initializer that did not appear in
 /// this source code. This can be used to get detailed semantic information about sub-parts
 /// of a constructor initializer that did not appear in source code. 
 /// 
 /// NOTE: This will only work in locations where there is already a constructor initializer.
 /// </summary>
 /// <param name="position">A character position used to identify a declaration scope and accessibility. This
 /// character position must be within the FullSpan of the Root syntax node in this SemanticModel.
 /// Furthermore, it must be within the span of an existing constructor initializer.
 /// </param>
 /// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer.
 /// This node should not be present in the syntax tree associated with this object.</param>
 /// <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic
 /// information associated with syntax nodes within <paramref name="constructorInitializer"/>.</param>
 /// <returns>Flag indicating whether a speculative semantic model was created.</returns>
 /// <exception cref="ArgumentException">Throws this exception if the <paramref name="constructorInitializer"/> node is contained any SyntaxTree in the current Compilation.</exception>
 /// <exception cref="ArgumentNullException">Throws this exception if <paramref name="constructorInitializer"/> is null.</exception>
 /// <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="SemanticModel.IsSpeculativeSemanticModel"/> is true.
 /// Chaining of speculative semantic model is not supported.</exception>
 public bool TryGetSpeculativeSemanticModel(int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel)
 {
     CheckModelAndSyntaxNodeToSpeculate(constructorInitializer);
     return TryGetSpeculativeSemanticModelCore((SyntaxTreeSemanticModel)this, position, constructorInitializer, out speculativeModel);
 }
 private static bool IsInitializerRedundant(ConstructorInitializerSyntax initializer)
 {
     return initializer.IsKind(SyntaxKind.BaseConstructorInitializer) &&
         initializer.ArgumentList != null &&
         !initializer.ArgumentList.Arguments.Any();
 }
Пример #54
0
 internal abstract bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel);
 internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel)
 {
     throw ExceptionUtilities.Unreachable;
 }
Пример #56
0
 internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel)
 {
     speculativeModel = null;
     return false;
 }
 public override SyntaxNode VisitConstructorInitializer(ConstructorInitializerSyntax node)
 {
     node = (ConstructorInitializerSyntax)base.VisitConstructorInitializer(node);
     node = _injectMixinIntoConstructor.ExtendConstructorInitialization(node);
     return node;
 }