/// <summary>
        /// Réordonne les assignations d'un constructeur.
        /// </summary>
        /// <param name="document">Le document.</param>
        /// <param name="constructeur">Le constructeur.</param>
        /// <param name="jetonAnnulation">Le jeton d'annulation.</param>
        /// <returns>Le nouveau document.</returns>
        private async Task<Document> OrdonnerAssignations(Document document, ConstructorDeclarationSyntax constructeur, CancellationToken jetonAnnulation)
        {
            // On récupère la racine et le modèle sémantique.
            var racine = await document
                .GetSyntaxRootAsync(jetonAnnulation)
                .ConfigureAwait(false);
            var modèleSémantique = await document.GetSemanticModelAsync(jetonAnnulation);

            // On récupère le corps du constructeur.
            var corps = constructeur.ChildNodes().First(nœud => nœud as BlockSyntax != null) as BlockSyntax;

            // On récupère toutes les conditions sur les paramètres.
            var conditions = Partagé.TrouveConditionsParametres(corps.Statements, constructeur.ParameterList, modèleSémantique);

            // On récupère les assignations et on les ordonne.
            var assignations = Partagé.TrouverAssignations(corps.Statements, modèleSémantique)
                .OrderBy(e => e.ToString());

            // On construit le nouveau corps du constructeur.
            var corpsOrdonné = corps.WithStatements(
                SyntaxFactory.List(
                    conditions
                        .Concat(assignations)
                        .Concat(corps.Statements
                            .Except(conditions)
                            .Except(assignations))));

            // Et on met à jour la racine.
            var nouvelleRacine = racine.ReplaceNode(corps, corpsOrdonné);

            return document.WithSyntaxRoot(nouvelleRacine);
        }
 public WithConstructorInitializerLocalsBinder(Binder enclosing, ConstructorDeclarationSyntax declaration)
     : base(enclosing, enclosing.Flags)
 {
     Debug.Assert(declaration.Initializer != null);
     this.scope = declaration;
     this.initializerArgumentList = declaration.Initializer.ArgumentList;
 }
 public static ClassDeclarationSyntax Create(string name, BaseTypeSyntax[] baseTypes, ConstructorDeclarationSyntax constructor, MemberDeclarationSyntax[] body)
 {
     return SyntaxFactory.ClassDeclaration(name)
         .AddBaseListTypes(baseTypes)
         .AddMembers(constructor)
         .AddMembers(body);            
 }
        private SourceConstructorSymbol(
            SourceMemberContainerTypeSymbol containingType,
            Location location,
            ConstructorDeclarationSyntax syntax,
            MethodKind methodKind,
            DiagnosticBag diagnostics) :
            base(containingType, syntax.GetReference(), syntax.Body.GetReferenceOrNull(), ImmutableArray.Create(location))
        {
            bool modifierErrors;
            var declarationModifiers = this.MakeModifiers(syntax.Modifiers, methodKind, location, diagnostics, out modifierErrors);
            this.flags = MakeFlags(methodKind, declarationModifiers, returnsVoid: true, isExtensionMethod: false);

            var bodyOpt = syntax.Body;
            if (bodyOpt != null)
            {
                if (IsExtern)
                {
                    diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this);
                }
            }

            var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers);
            if (info != null)
            {
                diagnostics.Add(info, location);
            }

            if (!modifierErrors)
            {
                this.CheckModifiers(methodKind, location, diagnostics);
            }
        }
        /// <summary>
        /// if the child class already has a constructor, 
        /// a new parameter will be added to the constructor
        /// </summary>
        /// <param name="oldConstructor">constructor to which
        /// we are going to add the new parameter</param>
        /// <returns>the constructor with the additional new parameter</returns>
        public ConstructorDeclarationSyntax ExtendExistingConstructor(
            ConstructorDeclarationSyntax oldConstructor)
        {
            if (oldConstructor.IsStatic())
                return oldConstructor;

            var parameterName = _mixin.Name.ConvertFieldNameToParameterName();
            // if there is already a parameter with the same name, skip further processing
            var alreadyHasParameter = oldConstructor.ParameterList.Parameters.Any(x => x.Identifier.Text == parameterName);
            if (alreadyHasParameter)
                return oldConstructor;

            // first rule: extend the constructors parameter list
            var parameter = CreateConstructorParameterForMixin(parameterName);
            var newConstructor = oldConstructor.AddParameterListParameters(parameter);
            // second rule: check for initializer
            // if we have no initializer or a base initializer, do the assignment in this constructor
            // but do not delegate the parameter to further constructors
            var initializer = oldConstructor.Initializer;
            if(initializer == null || initializer.IsKind(SyntaxKind.BaseConstructorInitializer))
            {
                newConstructor = newConstructor
                    .AddBodyStatements(CreateAssigmentStatementForConstructorBody(parameterName));
            }
            return newConstructor;
        }  
        public static SyntaxNode IntroduceFieldFromConstructor(SyntaxNode root, ConstructorDeclarationSyntax constructorStatement, ParameterSyntax parameter)
        {
            var oldClass = constructorStatement.FirstAncestorOrSelf<ClassDeclarationSyntax>();
            var newClass = oldClass;
            var fieldName = parameter.Identifier.ValueText;
            var fieldType = parameter.Type;
            var members = ExtractMembersFromClass(oldClass.Members);

            var addMember = false;
            if (!members.Any(p => p.Key == fieldName && p.Value == fieldType.ToString()))
            {
                var identifierPostFix = 0;
                while (members.Any(p => p.Key == fieldName))
                    fieldName = parameter.Identifier.ValueText + ++identifierPostFix;

                addMember = true;
            }

            var assignmentField = SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                               SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(),
                                               SyntaxFactory.IdentifierName(fieldName)), SyntaxFactory.IdentifierName(parameter.Identifier.ValueText)));
            var newConstructor = constructorStatement.WithBody(constructorStatement.Body.AddStatements(assignmentField));
            newClass = newClass.ReplaceNode(constructorStatement, newConstructor);

            if (addMember)
            {
                var newField = SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(parameter.Type)
                                    .WithVariables(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(fieldName)))))
                                    .WithModifiers(SyntaxFactory.TokenList(new[] { SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword) }))
                                    .WithAdditionalAnnotations(Formatter.Annotation);
                newClass = newClass.WithMembers(newClass.Members.Insert(0, newField)).WithoutAnnotations(Formatter.Annotation);
            }
            var newRoot = root.ReplaceNode(oldClass, newClass);
            return newRoot;
        }
        public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
        {
            if(this._targetConstructor == null || node.ParameterList.ToString() == this._targetConstructor.ParameterList.ToString())
            {
                var fieldName = this._relatedField.Declaration.Variables
                    .Select(p => p.Identifier.Text)
                    .FirstOrDefault();

                var paramName = fieldName.TrimStart('_');

                if (this._rewriteParams)
                {
                    var newParam = SyntaxFactory.Parameter(SyntaxFactory.Identifier(paramName))
                                .WithType(this._relatedField.Declaration.Type);

                    var newConstructorParams = node.ParameterList.AddParameters(newParam);

                    node = node.WithParameterList(newConstructorParams);
                }

                var newStatement = SyntaxExtenders.AssignmentStatement("this." + fieldName, paramName);
                var newStatements = node.Body.Statements.Insert(0, newStatement);

                node = node.WithBody(node.Body.WithStatements(newStatements));
            }

            return base.VisitConstructorDeclaration(node);
        }
        internal static SyntaxNode AddStatementToConstructorBody(SyntaxNode root, ConstructorDeclarationSyntax constructor, StatementSyntax statement)
        {
            var body = constructor.Body ?? SyntaxFactory.Block();

            return root.ReplaceNode(root.GetCurrentNode(constructor), constructor.WithBody(
                    body.WithStatements(SyntaxFactory.List(new[] { statement }.Concat(body.Statements)))
                ));
        }
Example #9
0
 internal void EntryPoint(ConstructorDeclarationSyntax ctor)
 {
     _entry = ctor;
     foreach (var param in ctor.ParameterList.Parameters)
     {
         addProducer(param.Identifier.ToString(), param.Type);
     }
 }
        static bool IsEmpty(ConstructorDeclarationSyntax constructorDeclaration)
        {
            if (constructorDeclaration.Initializer != null && constructorDeclaration.Initializer.ArgumentList.Arguments.Count > 0)
                return false;

            return constructorDeclaration.ParameterList.Parameters.Count == 0 &&
                EmptyDestructorAnalyzer.IsEmpty(constructorDeclaration.Body);
        }
 public static SourceConstructorSymbol CreateConstructorSymbol(
     SourceMemberContainerTypeSymbol containingType,
     ConstructorDeclarationSyntax syntax,
     DiagnosticBag diagnostics)
 {
     var methodKind = syntax.Modifiers.Any(SyntaxKind.StaticKeyword) ? MethodKind.StaticConstructor : MethodKind.Constructor;
     return new SourceConstructorSymbol(containingType, syntax.Identifier.GetLocation(), syntax, methodKind, diagnostics);
 }
Example #12
0
        public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
        {
            ConstructorWalker walker = this.CreateSyntaxWalker<ConstructorWalker>(node);
            walker.Visit(node);
            this.Constructors.Add(walker);

            base.VisitConstructorDeclaration(node);
        }
        public static void Go(OutputWriter writer, ConstructorDeclarationSyntax constructor)
        {
            //Only write out static constructors here.  If we encounter an instance constructor, we can ignore it since it's already written out by WriteType
            if (constructor.Modifiers.Any(SyntaxKind.StaticKeyword))
                WriteStaticConstructor(writer, constructor, null);
            else
				WriteInstanceConstructor(writer, constructor,null);
        }
        public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
        {
            if(!node.Modifiers.Any(predicate => predicate.Kind() == SyntaxKind.StaticKeyword))
            {
                this._nonStaticConstructors.Add(node);
            }

            base.VisitConstructorDeclaration(node);
        }
        public ConstructorDeclarationTranslation(ConstructorDeclarationSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
        {
            Identifier = syntax.Identifier.Get(this);

            if (syntax.Initializer != null)
            {
                Initializer = syntax.Initializer.Get<ConstructorInitializerTranslation>(this);
            }
        }
        public static SyntaxNode RemoveInitializer(SyntaxNode root, ConstructorDeclarationSyntax constructor)
        {
            var annotation = new SyntaxAnnotation();
            var ctor = constructor;
            var newRoot = root;
            newRoot = newRoot.ReplaceNode(ctor, ctor.WithAdditionalAnnotations(annotation));
            ctor = (ConstructorDeclarationSyntax)newRoot.GetAnnotatedNodes(annotation).First();
            var initializer = ctor.Initializer;

            if (RedundantInheritanceListCodeFixProvider.HasLineEnding(constructor.ParameterList))
            {
                newRoot = newRoot.RemoveNode(initializer, SyntaxRemoveOptions.KeepNoTrivia);
                ctor = (ConstructorDeclarationSyntax)newRoot.GetAnnotatedNodes(annotation).First();

                if (ctor.Body != null &&
                    ctor.Body.HasLeadingTrivia)
                {
                    var lastTrivia = ctor.Body.GetLeadingTrivia().Last();
                    newRoot = lastTrivia.IsKind(SyntaxKind.EndOfLineTrivia)
                        ? newRoot.ReplaceNode(
                            ctor.Body,
                            ctor.Body.WithoutLeadingTrivia())
                        : newRoot.ReplaceNode(
                            ctor.Body,
                            ctor.Body.WithLeadingTrivia(lastTrivia));
                }
            }
            else
            {
                var trailingTrivia = SyntaxFactory.TriviaList();
                if (initializer.HasTrailingTrivia)
                {
                    trailingTrivia = initializer.GetTrailingTrivia();
                }
                newRoot = newRoot.RemoveNode(initializer, SyntaxRemoveOptions.KeepNoTrivia);
                ctor = (ConstructorDeclarationSyntax)newRoot.GetAnnotatedNodes(annotation).First();

                if (ctor.Body != null &&
                    ctor.Body.HasLeadingTrivia)
                {
                    var lastTrivia = ctor.Body.GetLeadingTrivia().Last();
                    newRoot = newRoot.ReplaceNode(
                        ctor.Body,
                        ctor.Body.WithLeadingTrivia(trailingTrivia.Add(lastTrivia)));
                }
                else
                {
                    if (initializer.HasTrailingTrivia)
                    {
                        newRoot = newRoot.ReplaceNode(ctor, ctor.WithTrailingTrivia(trailingTrivia));
                    }
                }
            }

            ctor = (ConstructorDeclarationSyntax)newRoot.GetAnnotatedNodes(annotation).First();
            return newRoot.ReplaceNode(ctor, ctor.WithoutAnnotations(annotation));
        }
 public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
 {
     if (node == null)
         return null;
     var symbol = _semanticModel.GetDeclaredSymbol(node);
     node = (ConstructorDeclarationSyntax)base.VisitConstructorDeclaration(node);
     if (!IsPrivateOrInternal(symbol.DeclaredAccessibility))
         node = (ConstructorDeclarationSyntax)ApplyDocComment(node, symbol.GetDocumentationCommentId());
     return node;
 }
        public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
        {
            if (IsIgnoreMember(node.Modifiers)) { return; }

            var modifiers = GetMemberModifiersText(node.Modifiers);
            var name = node.Identifier.ToString();
            var args = node.ParameterList.Parameters.Select(p => $"{p.Identifier}:{p.Type}");

            WriteLine($"{modifiers}{name}({string.Join(", ", args)})");
        }
 public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
 {
     node = (ConstructorDeclarationSyntax)base.VisitConstructorDeclaration(node);
     if(!node.IsStatic())  // ignore static constructors
         node = _injectMixinIntoConstructor.ExtendExistingConstructor(node);
     // remember that class already has a constructor,
     // so no need to create a new one
     _SourceClassHasConstructor = true;
     return node;
 }
        private static void ReportForUnimplemented(CodeRefactoringContext context, IEnumerable<NamedSymbol> unimplemntedProperties, SemanticModel semanticModel, ConstructorDeclarationSyntax node)
        {
            ;
            var symbols = node.ParameterList.Parameters.Where(x => ImplementsSomethingFor(x.Type, unimplemntedProperties, semanticModel))
                .Distinct();

            foreach (var symbol in symbols)
                context.RegisterRefactoring(
                    new FixConstructorBody( node.Body, symbol.Identifier.Text, semanticModel, context.Document));
        }
        private static async Task<Document> ReplaceConstructorInDocumentAsync(
            Document document,
            ConstructorDeclarationSyntax oldConstructor,
            ConstructorDeclarationSyntax newConstructor,
            CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken);
            var newRoot = root.ReplaceNode(oldConstructor, new[] { newConstructor });

            return document.WithSyntaxRoot(newRoot);
        }
Example #22
0
 public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
 {
     if (node.ParameterList.Parameters.Count == 0)
         return node
             .WithBody(
                 SyntaxFactory.Block(
                     statements: SyntaxFactory.List(node.Body.Statements.Union(new [] { SyntaxFactory.ParseStatement("DataContext = vm;") }))))
             .WithParameterList(
                 SyntaxFactory.ParameterList(
                     SyntaxFactory.SeparatedList(
                         new[] { SyntaxFactory.Parameter(SyntaxFactory.Identifier("vm")).WithType(SyntaxFactory.ParseTypeName(_viewModelTypeName)) })));
     return base.VisitConstructorDeclaration(node);
 }
        public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
        {
            // ignore static constructors
            if (node.IsStatic())
                return;

            var constructor = new Constructor();
            // read parameters
            var parameterSyntaxReader = new ParameterSyntaxReader(constructor, _semantic);
            parameterSyntaxReader.Visit(node);
            _constructors.AddConstructor(constructor);
            base.VisitConstructorDeclaration(node);
        }
Example #24
0
        public static ConstructorDeclarationSyntax CtorInjection(ConstructorDeclarationSyntax ctor, IEnumerable<KeyValuePair<string, TypeSyntax>> values)
        {
            var old = ctor;
            var newCtor = old;

            foreach (var pair in values)
            {

                //TODO: check it doesn't contain expression already
                //newCtor.AddBodyStatements(CreateCtorBody())
            }

            return ctor;
        }
		/// <summary>
		///   Normalizes the <paramref name="declaration" />.
		/// </summary>
		public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax declaration)
		{
			var methodSymbol = declaration.GetMethodSymbol(SemanticModel);
			if (!methodSymbol.ContainingType.IsFaultEffect(SemanticModel))
				return declaration;

			try
			{
				_inConstructor = true;
				return base.VisitConstructorDeclaration(declaration);
			}
			finally
			{
				_inConstructor = false;
			}
		}
Example #26
0
 public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
 {
     var z = model.GetDeclaredSymbol(node);
       var builder = tcb.GetBuilderFor(z.DeclaredAccessibility);
       builder.AppendWithIndent(node.Identifier.Text).Append("(");
       var pars = node.ParameterList.Parameters.ToList();
       for (int i = 0; i < pars.Count; ++i)
       {
     var p = pars[i];
     var c = model.GetDeclaredSymbol(p);
     builder.Append(ArgumentTypeFor(c.Type)).Append(" ").Append(p.Identifier.ToString());
     if (i + 1 < pars.Count)
       builder.Append(", ");
       }
       builder.AppendLine(");");
       base.VisitConstructorDeclaration(node);
 }
        public ConstructorParameterContext(Document document, string parameterName, string propertyName, TypeSyntax type, ConstructorDeclarationSyntax constructor, TextSpan textSpan, SyntaxNode root)
        {
            Contract.Requires(document != null);
            Contract.Requires(parameterName != null);
            Contract.Requires(propertyName != null);
            Contract.Requires(type != null);
            Contract.Requires(constructor != null);
            Contract.Requires(root != null);

            Document = document;
            Constructor = constructor;
            Type = type;
            ParameterName = parameterName;
            PropertyName = propertyName;
            TextSpan = textSpan;
            Root = root;
        }
        private static void Analyze(
            SyntaxNodeAnalysisContext context,
            ConstructorDeclarationSyntax constructor)
        {
            var initializer = constructor.Initializer;
            var colon = initializer.ColonToken;

            if (!colon.IsFirstInLine())
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, initializer.GetLocation()));
                return;
            }

            if (colon.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia))
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, initializer.GetLocation()));
            }
        }
Example #29
0
        private static ConstructorDeclarationSyntax UseExpressionBodyIfDesired(
            Workspace workspace, ConstructorDeclarationSyntax declaration, ParseOptions options)
        {
            if (declaration.ExpressionBody == null)
            {
                var preferExpressionBody = workspace.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors).Value;
                if (preferExpressionBody)
                {
                    var expressionBody = declaration.Body.TryConvertToExpressionBody(options);
                    if (expressionBody != null)
                    {
                        return declaration.WithBody(null)
                                          .WithExpressionBody(expressionBody)
                                          .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                    }
                }
            }

            return declaration;
        }
        private static TextSpan CreateSpanForConstructorDeclaration(ConstructorDeclarationSyntax constructorSyntax)
        {
            if (constructorSyntax.Initializer != null)
            {
                //  [SomeAttribute] public MyCtorName(params int[] values): [|base()|] { ... }
                var start = constructorSyntax.Initializer.ThisOrBaseKeyword.SpanStart;
                var end = constructorSyntax.Initializer.ArgumentList.CloseParenToken.Span.End;
                return TextSpan.FromBounds(start, end);
            }

            if (constructorSyntax.Modifiers.Any(SyntaxKind.StaticKeyword))
            {
                // [SomeAttribute] static MyCtorName(...) [|{|] ... }
                var start = constructorSyntax.Body.OpenBraceToken.SpanStart;
                var end = constructorSyntax.Body.OpenBraceToken.Span.End;
                return TextSpan.FromBounds(start, end);
            }

            //  [SomeAttribute] [|public MyCtorName(params int[] values)|] { ... }
            return CreateSpan(constructorSyntax.Modifiers, constructorSyntax.Identifier, constructorSyntax.ParameterList.CloseParenToken);
        }