private static string GetNewFilePath(Document document, TypeDeclarationSyntax declaration)
 {
     var oldFilePath = document.FilePath;
     var oldFileDirectory = Path.GetDirectoryName(document.FilePath);
     var newFilePath = Path.Combine(oldFileDirectory, declaration.Identifier.Text + ".cs");
     return newFilePath;
 }
 public ClassStructDeclarationTranslation(TypeDeclarationSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
 {
     if (syntax.BaseList != null)
     {
         BaseList = syntax.BaseList.Get<BaseListTranslation>(this);                
     }           
 }
示例#3
0
		private static IEnumerable<string> GetContainingTypeName(TypeDeclarationSyntax syntax)
		{
			for (var typeDeclaration = syntax; typeDeclaration != null; typeDeclaration = typeDeclaration.Parent as TypeDeclarationSyntax)
			{
				yield return typeDeclaration.Identifier.ValueText;
			}
		}
 private static TypeDeclarationSyntax AddDisposeDeclarationToDisposeMethod(VariableDeclaratorSyntax variableDeclarator, TypeDeclarationSyntax type, INamedTypeSymbol typeSymbol)
 {
     var disposableMethod = typeSymbol.GetMembers("Dispose").OfType<IMethodSymbol>().FirstOrDefault(d => d.Arity == 0);
     var disposeStatement = SyntaxFactory.ParseStatement($"{variableDeclarator.Identifier.ToString()}.Dispose();");
     TypeDeclarationSyntax newType;
     if (disposableMethod == null)
     {
         var disposeMethod = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "Dispose")
               .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
               .WithBody(SyntaxFactory.Block(disposeStatement))
               .WithAdditionalAnnotations(Formatter.Annotation);
         newType = ((dynamic)type).AddMembers(disposeMethod);
     }
     else
     {
         var existingDisposeMethod = (MethodDeclarationSyntax)disposableMethod.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax();
         if (type.Members.Contains(existingDisposeMethod))
         {
             var newDisposeMethod = existingDisposeMethod.AddBodyStatements(disposeStatement)
                 .WithAdditionalAnnotations(Formatter.Annotation);
             newType = type.ReplaceNode(existingDisposeMethod, newDisposeMethod);
         }
         else
         {
             //we will simply anotate the code for now, but ideally we would change another document
             //for this to work we have to be able to fix more than one doc
             var fieldDeclaration = variableDeclarator.Parent.Parent;
             var newFieldDeclaration = fieldDeclaration.WithTrailingTrivia(SyntaxFactory.ParseTrailingTrivia($"//add {disposeStatement.ToString()} to the Dispose method on another file.").AddRange(fieldDeclaration.GetTrailingTrivia()))
                 .WithLeadingTrivia(fieldDeclaration.GetLeadingTrivia());
             newType = type.ReplaceNode(fieldDeclaration, newFieldDeclaration);
         }
     }
     return newType;
 }
        private static void AnalyzeType(SyntaxNodeAnalysisContext context, TypeDeclarationSyntax typeDeclaration)
        {
            var previousFieldReadonly = true;
            var previousAccessLevel = AccessLevel.NotSpecified;
            var previousMemberStatic = true;
            foreach (var member in typeDeclaration.Members)
            {
                var field = member as FieldDeclarationSyntax;
                if (field == null)
                {
                    continue;
                }

                var currentFieldReadonly = field.Modifiers.Any(SyntaxKind.ReadOnlyKeyword);
                var currentAccessLevel = AccessLevelHelper.GetAccessLevel(field.Modifiers);
                currentAccessLevel = currentAccessLevel == AccessLevel.NotSpecified ? AccessLevel.Private : currentAccessLevel;
                var currentMemberStatic = field.Modifiers.Any(SyntaxKind.StaticKeyword);
                if (currentAccessLevel == previousAccessLevel
                    && currentMemberStatic
                    && previousMemberStatic
                    && currentFieldReadonly
                    && !previousFieldReadonly)
                {
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, NamedTypeHelpers.GetNameOrIdentifierLocation(field), AccessLevelHelper.GetName(currentAccessLevel)));
                }

                previousFieldReadonly = currentFieldReadonly;
                previousAccessLevel = currentAccessLevel;
                previousMemberStatic = currentMemberStatic;
            }
        }
示例#6
0
        /// <summary>
        /// Réordonne les membres d'un type.
        /// </summary>
        /// <param name="document">Le document.</param>
        /// <param name="type">Le type.</param>
        /// <param name="jetonAnnulation">Le jeton d'annulation.</param>
        /// <returns>Le nouveau document.</returns>
        private async Task<Document> OrdonnerMembres(Document document, TypeDeclarationSyntax type, CancellationToken jetonAnnulation)
        {
            // On récupère la racine.
            var racine = await document
                .GetSyntaxRootAsync(jetonAnnulation)
                .ConfigureAwait(false);
            var modèleSémantique = await document.GetSemanticModelAsync(jetonAnnulation);

            // Pour une raison étrange, TypeDeclarationSyntax n'expose pas WithMembers() alors que les trois classes qui en héritent l'expose.
            // Il faut donc gérer les trois cas différemment...
            SyntaxNode nouveauType;
            if (type is ClassDeclarationSyntax)
            {
                nouveauType = (type as ClassDeclarationSyntax)
                    .WithMembers(SyntaxFactory.List(Partagé.OrdonnerMembres(type.Members, modèleSémantique)));
            }
            else if (type is InterfaceDeclarationSyntax)
            {
                nouveauType = (type as InterfaceDeclarationSyntax)
                    .WithMembers(SyntaxFactory.List(Partagé.OrdonnerMembres(type.Members, modèleSémantique)));
            }
            else
            {
                nouveauType = (type as StructDeclarationSyntax)
                    .WithMembers(SyntaxFactory.List(Partagé.OrdonnerMembres(type.Members, modèleSémantique)));
            }

            // Et on met à jour la racine.
            var nouvelleRacine = racine.ReplaceNode(type, nouveauType);

            return document.WithSyntaxRoot(nouvelleRacine);
        }
示例#7
0
		public IEnumerable<MethodDeclarationSyntax> GetPossibleStaticMethods(TypeDeclarationSyntax type)
		{
			return type.DescendantNodes()
				.OfType<MethodDeclarationSyntax>()
				.Where(x => !x.Modifiers.Any(SyntaxKind.StaticKeyword))
				.Where(CanBeMadeStatic)
				.AsArray();
		}
示例#8
0
文件: Scope.cs 项目: mpmedia/Excess
        public static void AddType(this Scope scope, TypeDeclarationSyntax type)
        {
            var types = scope.find<List<TypeDeclarationSyntax>>("__additionalTypes");
            if (types == null)
                throw new InvalidOperationException("document scope not initialized");

            types.Add(type);
        }
 private void AnalyzeType(SyntaxTreeAnalysisContext context, TypeDeclarationSyntax typeDeclaration)
 {
     var numberOfFields = typeDeclaration.Members.Count(member => member is FieldDeclarationSyntax);
     if (numberOfFields > MaximumNumberOfFields)
     {
         context.ReportDiagnostic(Diagnostic.Create(Rule, typeDeclaration.Identifier.GetLocation(), typeDeclaration.Identifier.Text, numberOfFields));
     }
 }
 internal static bool TypeDeclarationCompiles(TypeDeclarationSyntax generatedType)
 {
     var newTypes = new List<TypeDeclarationSyntax>();
     newTypes.Add(generatedType);
     var tree = GetTestSyntaxTreeWithTypes(newTypes);
     var compilation = CreateCompilation(tree);
     var diags = compilation.GetDiagnostics();
     return !diags.Any(diag => diag.Severity == DiagnosticSeverity.Error);
 }
 private async Task<Solution> MoveToMatchingFileAsync(Document document, SyntaxNode syntaxTree, TypeDeclarationSyntax declaration, CancellationToken cancellationToken)
 {
     var otherTypeDeclarationsInFile = syntaxTree.DescendantNodes().Where(originalNode => TypeDeclarationOtherThan(declaration, originalNode)).ToList();
     string newFilePath = GetNewFilePath(document, declaration);
     var newDocumentSyntaxTree = GetNewDocumentSyntaxTree(syntaxTree, otherTypeDeclarationsInFile);
     var newFile = document.Project.AddDocument(newFilePath, newDocumentSyntaxTree.GetText(), document.Folders);
     var solutionWithClassRemoved = GetDocumentWithClassDeclarationRemoved(newFile.Project, document, syntaxTree, declaration, otherTypeDeclarationsInFile);
     
     return document.Project.RemoveDocument(document.Id).Solution;
 }
示例#12
0
        private static TypeDeclarationSyntax ExpandType(TypeDeclarationSyntax original, TypeDeclarationSyntax updated, IEnumerable<ExpandablePropertyInfo> properties, SemanticModel model, Workspace workspace)
        {
            Debug.Assert(original != updated);

            return updated
                .WithBackingFields(properties, workspace)
                .WithBaseType(original, model)
                .WithPropertyChangedEvent(original, model, workspace)
                .WithSetPropertyMethod(original, model, workspace);
        }
 private ClassType DetermineClassType(TypeDeclarationSyntax declaration)
 {
     if (declaration.Keyword.RawKind == InterfaceKeywordToken) return ClassType.Other;
     var isDataStructure = HasPublicProperties(declaration) || HasPublicFields(declaration);
     var isObject = HasMethods(declaration);
     if (isDataStructure && isObject && HasNotOnlyConstOrReadonlyFields(declaration)) return ClassType.Hybrid;
     if (isObject) return ClassType.Object;
     if (isDataStructure) return ClassType.DataStructure;
     return ClassType.Other;
 }
 private static InterfaceDeclarationSyntax MakeInterface(TypeDeclarationSyntax typeSyntax)
 {
     return SyntaxFactory.InterfaceDeclaration(
         attributeLists: typeSyntax.AttributeLists,
         modifiers: typeSyntax.Modifiers,
         identifier: typeSyntax.Identifier,
         typeParameterList: typeSyntax.TypeParameterList,
         baseList: typeSyntax.BaseList,
         constraintClauses: typeSyntax.ConstraintClauses,
         members: MakeInterfaceSyntaxList(typeSyntax.Members)).NormalizeWhitespace();
 }
示例#15
0
        public static TypeDeclarationSyntax AddNamedTypeTo(
            ICodeGenerationService service,
            TypeDeclarationSyntax destination,
            INamedTypeSymbol namedType,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var declaration = GenerateNamedTypeDeclaration(service, namedType, GetDestination(destination), options);
            var members = Insert(destination.Members, declaration, options, availableIndices);

            return AddMembersTo(destination, members);
        }
示例#16
0
        internal static TypeDeclarationSyntax AddConversionTo(
            TypeDeclarationSyntax destination,
            IMethodSymbol method,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var methodDeclaration = GenerateConversionDeclaration(method, GetDestination(destination), options);

            var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastOperator);

            return AddMembersTo(destination, members);
        }
        internal static TypeDeclarationSyntax AddMethodTo(
            TypeDeclarationSyntax destination,
            IMethodSymbol method,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var methodDeclaration = GenerateMethodDeclaration(method, GetDestination(destination), options);

            // Create a clone of the original type with the new method inserted. 
            var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastMethod);

            return AddMembersTo(destination, members);
        }
 private static bool TryReplaceTypeMembers(TypeDeclarationSyntax typeDeclarationSyntax, IEnumerable<MemberDeclarationSyntax> membersDeclaration, IEnumerable<MemberDeclarationSyntax> sortedMembers, out TypeDeclarationSyntax orderedType)
 {
     var sortedMembersQueue = new Queue<MemberDeclarationSyntax>(sortedMembers);
     var orderChanged = false;
     orderedType = typeDeclarationSyntax.ReplaceNodes(
         membersDeclaration,
         (original, rewritten) =>
         {
             var newMember = sortedMembersQueue.Dequeue();
             if (!orderChanged && !original.Equals(newMember)) orderChanged = true;
             return newMember;
         });
     return orderChanged;
 }
示例#19
0
		private static TypeMetricKind GetMetricKind(TypeDeclarationSyntax type)
		{
			switch (type.Kind())
			{
				case SyntaxKind.ClassDeclaration:
					return TypeMetricKind.Class;
				case SyntaxKind.StructDeclaration:
					return TypeMetricKind.Struct;
				case SyntaxKind.InterfaceDeclaration:
					return TypeMetricKind.Interface;
				default:
					return TypeMetricKind.Unknown;
			}
		}
        // This code was copied from the Roslyn code base (and slightly modified). It can be removed if
        // TypeDeclarationSyntaxExtensions.WithModifiers is made public (Roslyn issue #2186)
        private static TypeDeclarationSyntax ReplaceModifiers(TypeDeclarationSyntax node, SyntaxTokenList modifiers)
        {
            switch (node.Kind())
            {
            case SyntaxKind.ClassDeclaration:
                return ((ClassDeclarationSyntax)node).WithModifiers(modifiers);
            case SyntaxKind.InterfaceDeclaration:
                return ((InterfaceDeclarationSyntax)node).WithModifiers(modifiers);
            case SyntaxKind.StructDeclaration:
                return ((StructDeclarationSyntax)node).WithModifiers(modifiers);
            }

            return node;
        }
 private static TypeDeclarationSyntax AddIDisposableImplementationToType(TypeDeclarationSyntax type, INamedTypeSymbol typeSymbol)
 {
     var iDisposableInterface = typeSymbol.AllInterfaces.FirstOrDefault(i => i.ToString() == "System.IDisposable");
     if (iDisposableInterface != null) return type;
     var newBaseList = type.BaseList != null
         ? type.BaseList.AddTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseName("System.IDisposable").WithAdditionalAnnotations(Simplifier.Annotation)))
         : SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(new BaseTypeSyntax[] {
                 SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseName("System.IDisposable").WithAdditionalAnnotations(Simplifier.Annotation)) }));
     TypeDeclarationSyntax newType = ((dynamic)type)
         .WithBaseList(newBaseList)
         .WithIdentifier(SyntaxFactory.Identifier(type.Identifier.Text));//this line is stupid, it is here only to remove the line break at the end of the identifier that roslyn for some reason puts there
     newType = newType.WithAdditionalAnnotations(Formatter.Annotation);//can't chain because this would be an ext.method on a dynamic type
     return newType;
 }
示例#22
0
        private async Task<Document> AddModifier(Document document, TypeDeclarationSyntax typeDecl, SyntaxKind modifier, CancellationToken cancellationToken)
        {
            var classDeclaration = typeDecl as ClassDeclarationSyntax;
            if (classDeclaration == null)
            {
                return document;
            }

            var newClassDeclaration = classDeclaration.AddModifiers(SyntaxFactory.Token(modifier));
            var root = await document.GetSyntaxRootAsync();
            var newRoot = root.ReplaceNode(classDeclaration, newClassDeclaration);

            return document.WithSyntaxRoot(newRoot);         
        }
示例#23
0
        internal static TypeDeclarationSyntax AddConstructorTo(
            TypeDeclarationSyntax destination,
            IMethodSymbol constructor,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var constructorDeclaration = GenerateConstructorDeclaration(constructor, GetDestination(destination), options);

            // Generate after the last constructor, or after the last field, or at the start of the
            // type.
            var members = Insert(destination.Members, constructorDeclaration, options,
                availableIndices, after: LastConstructorOrField, before: FirstMember);

            return AddMembersTo(destination, members);
        }
        private async Task<Solution> AddXmlComment(Document document, TypeDeclarationSyntax typeDeclarlationSyntax, CancellationToken cancellationToken)
        {
            var syntaxTrivia = SyntaxFactory.DocumentationCommentExterior(@"/// <summary>
///
/// </summary>");
            var tokenList = SyntaxFactory.TokenList(SyntaxFactory.XmlTextLiteral(SyntaxFactory.TriviaList(SyntaxFactory.DocumentationCommentExterior("@///")), "test", "test", SyntaxFactory.TriviaList()));
            var xmlText = SyntaxFactory.XmlText().WithTextTokens(tokenList);
            var xmlTokenList = SyntaxFactory.SingletonList<XmlNodeSyntax>(xmlText);
            var xmlComment = SyntaxFactory.DocumentationCommentTrivia(SyntaxKind.MultiLineDocumentationCommentTrivia, xmlTokenList);

            

            // Returning solution for now because I don't know how to set the value.
            return document.Project.Solution;
        }
示例#25
0
        internal static TypeDeclarationSyntax AddFieldTo(
            TypeDeclarationSyntax destination,
            IFieldSymbol field,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var declaration = GenerateFieldDeclaration(field, GetDestination(destination), options);

            // Place the field after the last field or const, or at the start of the type
            // declaration.
            var members = Insert(destination.Members, declaration, options, availableIndices,
                after: m => LastField(m, declaration), before: FirstMember);

            return AddMembersTo(destination, members);
        }
示例#26
0
        internal static TypeDeclarationSyntax AddOperatorTo(
            TypeDeclarationSyntax destination,
            IMethodSymbol method,
            Workspace workspace,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var methodDeclaration = GenerateOperatorDeclaration(
                method, GetDestination(destination), workspace, options,
                destination?.SyntaxTree.Options ?? options.ParseOptions);

            var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastOperator);

            return AddMembersTo(destination, members);
        }
示例#27
0
        internal static string GetConventionalFileName(TypeDeclarationSyntax typeDeclaration, FileNamingConvention convention)
        {
            if (typeDeclaration.TypeParameterList == null)
            {
                return GetSimpleFileName(typeDeclaration);
            }

            switch (convention)
            {
            case FileNamingConvention.Metadata:
                return GetMetadataFileName(typeDeclaration);

            default:
                return GetStyleCopFileName(typeDeclaration);
            }
        }
示例#28
0
        internal static TypeDeclarationSyntax AddEventTo(
            TypeDeclarationSyntax destination,
            IEventSymbol @event,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var declaration = GenerateEventDeclaration(@event, GetDestination(destination), options);

            var members = Insert(destination.Members, declaration, options, availableIndices,
                after: list => AfterMember(list, declaration), before: list => BeforeMember(list, declaration));

            // Find the best place to put the field.  It should go after the last field if we already
            // have fields, or at the beginning of the file if we don't.

            return AddMembersTo(destination, members);
        }
示例#29
0
        internal static TypeDeclarationSyntax AddPropertyTo(
            TypeDeclarationSyntax destination,
            IPropertySymbol property,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var declaration = GeneratePropertyOrIndexer(property, GetDestination(destination), options);

            // Create a clone of the original type with the new method inserted. 
            var members = Insert(destination.Members, declaration, options,
                availableIndices, after: LastPropertyOrField, before: FirstMember);

            // Find the best place to put the field.  It should go after the last field if we already
            // have fields, or at the beginning of the file if we don't.
            return AddMembersTo(destination, members);
        }
        private string GetNewTypeName(TypeDeclarationSyntax containingType, SemanticModel model)
        {
            const string defaultName = "MyType";

            var @namespace = model.GetDeclaredSymbol(containingType).ContainingNamespace;
            var types = @namespace.GetMembers().OfType<ITypeSymbol>().Select(t => t.Name);

            var name = defaultName;

            int count = 1;
            while (types.Contains(name))
            {
                name = defaultName + count++;
            }

            return name;
        }
示例#31
0
 // Syntax
 public static bool IsPartial(this TypeDeclarationSyntax type)
 {
     return(type.Modifiers.Select(i => i.Kind()).Contains(SyntaxKind.PartialKeyword));
 }
示例#32
0
        public static bool IsChildOf(this TypeDeclarationSyntax type, string name)
        {
            var @base = type.BaseList?.Types.FirstOrDefault();

            return(@base?.ToString() == name);
        }
示例#33
0
 public static IEnumerable <MethodDeclarationSyntax> GetMethods(this TypeDeclarationSyntax type, string name)
 {
     return(type.Members.OfType <MethodDeclarationSyntax>().Where(i => i.Identifier.ValueText == name));
 }
示例#34
0
        internal static bool IsInTypeParameterList(int position, TypeDeclarationSyntax typeDecl)
        {
            var typeParameterListOpt = typeDecl.TypeParameterList;

            return(typeParameterListOpt != null && IsBeforeToken(position, typeParameterListOpt, typeParameterListOpt.GreaterThanToken));
        }
示例#35
0
        public SyntaxList <StatementSyntax> InsertGeneratedClassMemberDeclarations(SyntaxList <StatementSyntax> convertedStatements, CSS.TypeDeclarationSyntax typeNode, bool isModule)
        {
            var propertyBlocks = typeNode.Members.OfType <CSS.PropertyDeclarationSyntax>()
                                 .Where(e => e.AccessorList != null && e.AccessorList.Accessors.Any(a => a.Body == null && a.ExpressionBody == null && a.Modifiers.ContainsDeclaredVisibility()))
                                 .ToList();

            return(convertedStatements.InsertRange(0, ConvertToDeclarationStatement(propertyBlocks, isModule)));
        }