示例#1
0
        public void AddMissingNamespaces_VB()
        {
            var src =
                @"Namespace Test
{
}
";

            var document    = src.CreateDocument(LanguageNames.VisualBasic);
            var compilation = document.Project.GetCompilationAsync().Result;
            var namespaces  = new NamespaceSet();

            namespaces.Add(compilation.GetKnownType(KnownTypes.Attribute));

            var editor = DocumentEditor.CreateAsync(document).Result;

            editor.AddMissingNamespaces(namespaces, null, ImportedNamespace.AddImports, CancellationToken.None).Wait();

            var expected =
                @"Imports System

Namespace Test
{
}
";

            Assert.AreEqual(expected, editor.FormatAsync().Result.GetSourceCode());
        }
示例#2
0
        private async Task <(Document Document, SyntaxAnnotation PropertyAnnotation)> AddCustomValidatorPropertyAsync(string name,
                                                                                                                      INamedTypeSymbol modelAttributeType, INamedTypeSymbol modelMemberAttributeType, CancellationToken ct)
        {
            var editor = await DocumentEditor.CreateAsync(Document, ct);

            var g         = editor.Generator;
            var entryType = Compilation.GetKnownType(KnownTypes.CustomValidatorEntry);
            var imports   = new NamespaceSet
            {
                modelAttributeType,
                modelMemberAttributeType,
                entryType
            };

            var property = g.PropertyDeclaration(name, g.IdentifierName(entryType.Name), Accessibility.Private, DeclarationModifiers.ReadOnly,
                                                 getAccessorStatements: GenerateCustomValidatorGetter(g));
            var propertyAnnotation = new SyntaxAnnotation();

            property = GenerateAttribute(property, modelMemberAttributeType.Name.ToAttributeName()).WithAdditionalAnnotations(Formatter.Annotation, propertyAnnotation);

            editor.AddMember(ModelClass, property);

            await AddMissingNamespaces(editor, imports, ct);

            var result = await editor.FormatAsync(ct);

            return(result, propertyAnnotation);
        }
        private async Task<Solution> GenerateMissingFactoryMethodAsync(CodeFixContext context, CancellationToken ct)
        {
            var document = context.Document;
            var syntaxTree = await document.GetSyntaxTreeAsync(ct).ConfigureAwait(false);
            var root = await document.GetSyntaxRootAsync(ct).ConfigureAwait(false);
            var semanticModel = await document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
            var compilation = semanticModel.Compilation;

            var diagnostic = context.Diagnostics.First<Diagnostic>();
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            var dbMockType = GetClassSymbol(root, semanticModel, diagnosticSpan, out var classNode, ct);
            var dbSessionType = dbMockType.GetArgumentType(compilation.GetKnownType(KnownTypes.DbMockOf), compilation);

            var imports = new NamespaceSet
            {
                dbMockType,
                dbSessionType,
                compilation.GetKnownType(KnownTypes.TaskOf),
                compilation.GetKnownType(KnownTypes.IProgressOf),
                compilation.GetKnownType(KnownTypes.CancellationToken)
            };

            var editor = await DocumentEditor.CreateAsync(document, ct);
            var g = editor.Generator;
            var methodDeclaration = GenerateMethodDeclaration(g, compilation, dbMockType, dbSessionType).WithAdditionalAnnotations(Formatter.Annotation);
            editor.InsertMembers(classNode, 0, new SyntaxNode[] { methodDeclaration });

            await editor.AddMissingNamespacesAsync(imports, compilation, dbMockType.ContainingNamespace, syntaxTree, semanticModel, ct);
            var result = await editor.FormatAsync(ct);
            return result.Project.Solution;
        }
示例#4
0
        public async Task <Document> AddPrimaryKeyAsync(string pkTypeName, DataSet <PrimaryKeyEntry> entries, string keyTypeName, string refTypeName, CancellationToken ct)
        {
            if (!CanAddPrimaryKey || entries == null || entries.Count == 0)
            {
                return(null);
            }

            var editor = await DocumentEditor.CreateAsync(Document, ct);

            var g       = editor.Generator;
            var imports = new NamespaceSet();

            var pkClass  = GeneratePkClass(g, imports, pkTypeName, entries).WithAdditionalAnnotations(Formatter.Annotation);
            var pkCreate = GeneratePkCreate(g, "CreatePrimaryKey", pkTypeName, entries).WithAdditionalAnnotations(Formatter.Annotation);
            var keyClass = string.IsNullOrEmpty(keyTypeName) ? null : GenerateKeyOrRefClass(g, imports, keyTypeName, "Key", pkTypeName, "CreatePrimaryKey", entries).WithAdditionalAnnotations(Formatter.Annotation);
            var refClass = string.IsNullOrEmpty(refTypeName) ? null : GenerateKeyOrRefClass(g, imports, refTypeName, "Ref", pkTypeName, "CreateForeignKey", entries).WithAdditionalAnnotations(Formatter.Annotation);

            editor.InsertMembers(ModelClass, 0, (new SyntaxNode[] { pkClass, pkCreate, keyClass, refClass }).Where(x => x != null));

            var genericName = g.GenericName("Model", g.QualifiedName(g.IdentifierName(ModelType.Name), g.IdentifierName(pkTypeName))).WithAdditionalAnnotations(Formatter.Annotation);

            editor.ReplaceNode(BaseModel, genericName);
            await AddMissingNamespaces(editor, imports, ct);

            return(await editor.FormatAsync(ct));
        }
示例#5
0
        private async Task <Document> AddForeignKeyAsync(INamedTypeSymbol fkType, string fkName, DataSet <ForeignKeyEntry> entries, CancellationToken ct = default(CancellationToken))
        {
            var editor = await DocumentEditor.CreateAsync(Document, ct);

            var g       = editor.Generator;
            var imports = new NamespaceSet
            {
                fkType
            };

            var backingFieldName       = GetBackingFieldName(fkName);
            var backingFieldAnnotation = new SyntaxAnnotation();
            var fieldDeclaration       = g.FieldDeclaration(backingFieldName, GenerateFkType(g, fkType), Accessibility.Private).WithAdditionalAnnotations(Formatter.Annotation, backingFieldAnnotation);

            var assignment         = g.AssignmentStatement(g.IdentifierName(backingFieldName), g.ObjectCreationExpression(GenerateFkType(g, fkType), GenerateArguments(g, entries)));
            var propertyGetter     = GenerateFkPropertyGetter(g, backingFieldName, assignment);
            var propertyAnnotation = new SyntaxAnnotation();
            var property           = g.PropertyDeclaration(fkName, GenerateFkType(g, fkType), Accessibility.Public, DeclarationModifiers.ReadOnly, getAccessorStatements: propertyGetter)
                                     .WithAdditionalAnnotations(Formatter.Annotation, propertyAnnotation);

            await AddMissingNamespaces(editor, imports, ct);

            editor.AddMember(ModelClass, fieldDeclaration);
            editor.AddMember(ModelClass, property);

            return(await KeepTogetherAsync(await editor.FormatAsync(ct), backingFieldAnnotation, propertyAnnotation, ct));
        }
示例#6
0
        private SyntaxNode[] GeneratePkParams(SyntaxGenerator g, NamespaceSet imports, DataSet <PrimaryKeyEntry> entries)
        {
            var _      = entries._;
            var result = new SyntaxNode[entries.Count];

            for (int i = 0; i < result.Length; i++)
            {
                var type = _.Column[i].Type;
                imports.Add(type);
                var        parameter     = g.ParameterDeclaration(_.ConstructorParamName[i], g.IdentifierName(type.Name));
                var        sortDirection = _.SortDirection[i];
                SyntaxNode sortAttribute = null;
                if (sortDirection == SortDirection.Ascending)
                {
                    sortAttribute = g.Attribute(g.IdentifierName("Asc"));
                }
                else if (sortDirection == SortDirection.Descending)
                {
                    sortAttribute = g.Attribute(g.IdentifierName("Desc"));
                }
                if (sortAttribute != null)
                {
                    imports.Add(Compilation.GetKnownType(KnownTypes.AscAttribute));
                    parameter = g.AddAttributes(parameter, sortAttribute);
                }
                result[i] = parameter;
            }

            return(result);
        }
示例#7
0
        public void AddMissingNamespaces_multiple_append()
        {
            var src =
                @"using DevZest.Data;

namespace Test
{
}
";

            var document    = src.CreateDocument();
            var compilation = document.Project.GetCompilationAsync().Result;
            var namespaces  = new NamespaceSet
            {
                compilation.GetKnownType(KnownTypes.Attribute),
                compilation.GetKnownType(KnownTypes.AscAttribute)
            };

            var editor = DocumentEditor.CreateAsync(document).Result;

            editor.AddMissingNamespaces(namespaces, null, ImportedNamespace.AddUsings, CancellationToken.None).Wait();

            var expected =
                @"using DevZest.Data;
using DevZest.Data.Annotations;
using System;

namespace Test
{
}
";

            Assert.AreEqual(expected, editor.FormatAsync().Result.GetSourceCode());
        }
示例#8
0
        private async Task<Document> AddDbTableAsync(INamedTypeSymbol modelType, string name, string dbName, string description, CancellationToken ct = default(CancellationToken))
        {
            var editor = await DocumentEditor.CreateAsync(Document, ct);
            var g = editor.Generator;
            var imports = new NamespaceSet
            {
                modelType,
                Compilation.GetKnownType(KnownTypes.DbTableOf)
            };
            var needDbTableAttribute = NeedTableAttribute(dbName, description);
            if (needDbTableAttribute)
                imports.Add(Compilation.GetKnownType(KnownTypes.DbTableAttribute));

            var backingFieldName = GetBackingFieldName(name);
            var backingFieldAnnotation = new SyntaxAnnotation();
            var fieldDeclaration = g.FieldDeclaration(backingFieldName, GenerateDbTableType(g, modelType), Accessibility.Private).WithAdditionalAnnotations(Formatter.Annotation, backingFieldAnnotation);

            var getTable = g.InvocationExpression(g.IdentifierName("GetTable"), g.Argument(RefKind.Ref, g.IdentifierName(backingFieldName)));
            var propertyGetter = g.ReturnStatement(getTable);
            var property = g.PropertyDeclaration(name, GenerateDbTableType(g, modelType), Accessibility.Public, DeclarationModifiers.ReadOnly, getAccessorStatements: new SyntaxNode[] { propertyGetter });
            if (needDbTableAttribute)
                property = GenerateDbTableAttribute(g, property, dbName, description);
            var propertyAnnotation = new SyntaxAnnotation();
            property = property.WithAdditionalAnnotations(Formatter.Annotation, propertyAnnotation);

            await AddMissingNamespaces(editor, imports, ct);
            editor.AddMember(DbClass, fieldDeclaration);
            editor.AddMember(DbClass, property);

            var result = await KeepTogetherAsync(await editor.FormatAsync(ct), backingFieldAnnotation, propertyAnnotation, ct);
            return result;
        }
示例#9
0
        private SyntaxNode GenerateProjectionClass(SyntaxGenerator g, NamespaceSet imports, string className, DataSet <ProjectionEntry> entries)
        {
            imports.Add(Compilation.GetKnownType(KnownTypes.Projection));
            var baseType    = g.IdentifierName("Projection");
            var constructor = GenerateStaticConstructorForColumnRegistration(g, imports, Language, ModelType, className, entries);
            var properties  = GenerateColumnProperties(g, imports, entries);

            return(g.ClassDeclaration(className, accessibility: Accessibility.Public, baseType: baseType, members: constructor.Concat(null, properties)));
        }
示例#10
0
        public static void Add(this NamespaceSet namespaces, ITypeSymbol type)
        {
            var containingNamespace = type.ContainingNamespace;

            if (containingNamespace != null)
            {
                namespaces.Add(containingNamespace);
            }
        }
示例#11
0
        private static SyntaxNode GenerateColumnRegistration(SyntaxGenerator g, NamespaceSet imports, string language, INamedTypeSymbol modelType, string className, IPropertySymbol column, IFieldSymbol mounter)
        {
            var lambdaExpressionParam = g.ParameterDeclaration(g.GetterLambdaParamName(language), g.IdentifierName(className));
            var lambdaExpression      = g.ValueReturningLambdaExpression(new SyntaxNode[] { lambdaExpressionParam }, g.GetterBody(language, column.Name));
            var mounterArgument       = g.Argument(GenerateMounterIdentifier(g, imports, modelType, mounter));
            var invocation            = g.InvocationExpression(g.IdentifierName("Register"), g.Argument(lambdaExpression), mounterArgument);

            return(g.ExpressionStatement(invocation));
        }
示例#12
0
        private static SyntaxNode GenerateMounterIdentifier(SyntaxGenerator g, NamespaceSet imports, INamedTypeSymbol modelType, IFieldSymbol mounter)
        {
            if (mounter.ContainingType == modelType)
            {
                return(g.IdentifierName(mounter.Name));
            }

            imports.Add(mounter.ContainingType);
            return(g.QualifiedName(g.IdentifierName(mounter.ContainingType.Name), g.IdentifierName(mounter.Name)));
        }
示例#13
0
        private SyntaxNode GenerateKeyOrRefClass(SyntaxGenerator g, NamespaceSet imports, string className, string baseTypeName, string pkTypeName, string pkCreateMethodName, DataSet <PrimaryKeyEntry> entries)
        {
            imports.Add(Compilation.GetKnownType(KnownTypes.KeyOf));
            var baseType    = g.GenericName(baseTypeName, g.IdentifierName(pkTypeName));
            var constructor = GenerateStaticConstructorForColumnRegistration(g, imports, Language, ModelType, className, entries);
            var pkCreate    = GeneratePkCreate(g, pkCreateMethodName, pkTypeName, entries);
            var properties  = GenerateColumnProperties(g, imports, entries);

            return(g.ClassDeclaration(className, accessibility: Accessibility.Public, baseType: baseType, members: constructor.Concat(pkCreate, properties)));
        }
示例#14
0
        private SyntaxNode GeneratePkClass(SyntaxGenerator g, NamespaceSet imports, string pkTypeName, DataSet <PrimaryKeyEntry> entries)
        {
            imports.Add(Compilation.GetKnownType(KnownTypes.CandidateKey));
            var baseType    = g.IdentifierName(nameof(KnownTypes.CandidateKey));
            var parameters  = GeneratePkParams(g, imports, entries);
            var arguments   = GeneratePkArguments(g, entries);
            var constructor = g.ConstructorDeclaration(pkTypeName, accessibility: Accessibility.Public, parameters: parameters, baseConstructorArguments: arguments);

            return(g.ClassDeclaration(pkTypeName, accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed, baseType: baseType, members: new SyntaxNode[] { constructor }));
        }
示例#15
0
        private async Task<Document> AddRelationshipAsync(IPropertySymbol dbTable, string name, IPropertySymbol foreignKey, IPropertySymbol refTable,
            string description, ForeignKeyRule deleteRule, ForeignKeyRule updateRule, CancellationToken ct = default(CancellationToken))
        {
            var editor = await DocumentEditor.CreateAsync(Document, ct);
            var g = editor.Generator;
            var declarationAttributeType = Compilation.GetKnownType(KnownTypes.RelationshipAttribute);
            var ruleType = deleteRule != ForeignKeyRule.None || updateRule != ForeignKeyRule.None ? Compilation.GetKnownType(KnownTypes.ForeignKeyRule) : null;
            var implementationAttributeType = Compilation.GetKnownType(KnownTypes._RelationshipAttribute);
            var modelType = dbTable.GetModelType();
            var keyMappingType = Compilation.GetKnownType(KnownTypes.KeyMapping);
            var imports = new NamespaceSet
            {
                declarationAttributeType,
                implementationAttributeType,
                modelType,
                keyMappingType
            };
            if (ruleType != null)
                imports.Add(ruleType);

            var paramName = ModelParamName;
            var methodBody = GenerateImplementationMethodBody();
            var method = g.MethodDeclaration(name, new SyntaxNode[] { g.ParameterDeclaration(paramName, g.IdentifierName(modelType.Name)) }, null,
                g.IdentifierName(keyMappingType.Name), Accessibility.Private, default(DeclarationModifiers), statements: new SyntaxNode[] { methodBody });
            method = GenerateAttribute(method, implementationAttributeType.Name.ToAttributeName()).WithAdditionalAnnotations(Formatter.Annotation);

            editor.AddMember(DbClass, method);

            var argument = g.NameOfExpression(g.IdentifierName(name));
            var arguments = g.AttributeArgument(argument).Concat(GenerateAdditionalArguments()).ToArray();
            var dbTableNode = GetSyntaxNode(dbTable);
            editor.ReplaceNode(dbTableNode, GenerateAttribute(dbTableNode, declarationAttributeType.Name.ToAttributeName(), GetLeadingWhitespaceTrivia(dbTableNode), arguments));

            await AddMissingNamespaces(editor, imports, ct);

            return await editor.FormatAsync(ct);

            IEnumerable<SyntaxNode> GenerateAdditionalArguments()
            {
                if (!string.IsNullOrWhiteSpace(description))
                    yield return g.AttributeArgument("Description", g.LiteralExpression(description));
                if (deleteRule != ForeignKeyRule.None)
                    yield return g.AttributeArgument("DeleteRule", g.DottedName(string.Format("{0}.{1}", ruleType.Name, deleteRule)));
                if (updateRule != ForeignKeyRule.None)
                    yield return g.AttributeArgument("UpdateRule", g.DottedName(string.Format("{0}.{1}", ruleType.Name, updateRule)));
            }

            SyntaxNode GenerateImplementationMethodBody()
            {
                var fkExpr = g.DottedName(string.Format("{0}.{1}", paramName, foreignKey.Name));
                var joinParam = dbTable == refTable ? g.IdentifierName(paramName) : GenerateJoinParam(g, refTable);
                return g.ReturnStatement(g.InvocationExpression(g.MemberAccessExpression(fkExpr, "Join"), joinParam));
            }
        }
示例#16
0
        private async Task <Document> AddKeyOrRefAsync(string keyOrRefTypeName, DataSet <PrimaryKeyEntry> entries, string baseTypeName, string pkCreateMethodName, CancellationToken ct)
        {
            var editor = await DocumentEditor.CreateAsync(Document, ct);

            var g                     = editor.Generator;
            var imports               = new NamespaceSet();
            var keyOrRefClass         = GenerateKeyOrRefClass(g, imports, keyOrRefTypeName, baseTypeName, PkType.Name, pkCreateMethodName, entries).WithAdditionalAnnotations(Formatter.Annotation);
            var lastNodeToAddKeyOrRef = GetLastNodeToAddKeyOrRef();

            editor.InsertAfter(lastNodeToAddKeyOrRef, keyOrRefClass);
            await AddMissingNamespaces(editor, imports, ct);

            return(await editor.FormatAsync(ct));
        }
示例#17
0
        public static async Task AddMissingNamespaces(this DocumentEditor editor, NamespaceSet namespaces, IReadOnlyList <ImportedNamespace> importedNamespaces,
                                                      Func <SyntaxNode, IEnumerable <SyntaxNode>, SyntaxNode> addUsings, CancellationToken ct)
        {
            var orderedNamespaces = namespaces.OrderBy((x => x.ToDisplayString())).ToArray();

            if (orderedNamespaces.Length == 0)
            {
                return;
            }

            var g = editor.Generator;

            if (importedNamespaces == null || importedNamespaces.Count == 0)
            {
                var root = await editor.GetChangedDocument().GetSyntaxRootAsync(ct);

                var newRoot = addUsings(root, orderedNamespaces.Select(x => g.GenerateNamespaceImportDeclaration(x)));
                editor.ReplaceNode(root, newRoot);
                return;
            }

            for (int i = 0; i < orderedNamespaces.Length; i++)
            {
                var namespaceSymbol = orderedNamespaces[i];
                var index           = namespaceSymbol.GetIndexToInsertBefore(importedNamespaces);
                if (index < 0)
                {
                    continue;
                }

                if (index == importedNamespaces.Count)
                {
                    var lastNode = importedNamespaces.LastOrDefault().SyntaxNode;
                    Append(editor, lastNode, orderedNamespaces, i);
                    return;
                }

                var newNode = g.GenerateNamespaceImportDeclaration(namespaceSymbol);
                editor.InsertBefore(importedNamespaces[index].SyntaxNode, newNode);
            }
        }
示例#18
0
        public static async Task AddMissingNamespacesAsync(this DocumentEditor editor, NamespaceSet namespaces,
                                                           Compilation compilation, INamespaceSymbol containingNamespace, SyntaxTree syntaxTree, SemanticModel semanticModel, CancellationToken ct)
        {
            namespaces = new NamespaceSet(namespaces); // Make a copy because namespaces is a input parameter

            namespaces.ExceptWith(containingNamespace.GetImplicitlyImportedNamespaces());
            if (namespaces.Count == 0)
            {
                return;
            }

            var globalImports = compilation.GetGlobalImports().ToArray();

            if (globalImports.Length > 0)
            {
                namespaces.RemoveWhere(x => globalImports.Contains(x.ToDisplayString()));
            }

            var importedNamespaces = ImportedNamespace.GetImportedNamespaces(syntaxTree, semanticModel);
            await editor.AddMissingNamespaces(namespaces, importedNamespaces, ImportedNamespace.GetAddFunc(semanticModel.Language), ct);
        }
示例#19
0
        public async Task <Document> AddProjectionAsync(string typeName, DataSet <ProjectionEntry> entries, CancellationToken ct)
        {
            var editor = await DocumentEditor.CreateAsync(Document, ct);

            var g                       = editor.Generator;
            var imports                 = new NamespaceSet();
            var projectionClass         = GenerateProjectionClass(g, imports, typeName, entries).WithAdditionalAnnotations(Formatter.Annotation);
            var lastNodeToAddProjection = GetLastNodeToAddProjection();

            if (lastNodeToAddProjection != null)
            {
                editor.InsertAfter(lastNodeToAddProjection, projectionClass);
            }
            else
            {
                editor.InsertMembers(ModelClass, 0, new SyntaxNode[] { projectionClass });
            }
            await AddMissingNamespaces(editor, imports, ct);

            return(await editor.FormatAsync(ct));
        }
示例#20
0
        private async Task <(Document Document, SyntaxAnnotation PropertyAnnotation)> AddCheckPropertyAsync(string name,
                                                                                                            INamedTypeSymbol modelAttributeType, INamedTypeSymbol modelMemberAttributeType, CancellationToken ct = default(CancellationToken), params INamedTypeSymbol[] typesToImport)
        {
            var editor = await DocumentEditor.CreateAsync(Document, ct);

            var g           = editor.Generator;
            var booleanType = Compilation.GetKnownType(KnownTypes._Boolean);
            var imports     = new NamespaceSet
            {
                modelAttributeType,
                modelMemberAttributeType,
                booleanType
            };

            if (typesToImport != null && typesToImport.Length > 0)
            {
                for (int i = 0; i < typesToImport.Length; i++)
                {
                    var typeToImport = typesToImport[i];
                    if (typeToImport != null)
                    {
                        imports.Add(typeToImport);
                    }
                }
            }

            var propertyGetter     = g.GenerateNotImplemented(Compilation);
            var property           = g.PropertyDeclaration(name, g.IdentifierName(booleanType.Name), Accessibility.Private, DeclarationModifiers.ReadOnly, getAccessorStatements: new SyntaxNode[] { propertyGetter });
            var propertyAnnotation = new SyntaxAnnotation();

            property = GenerateAttribute(property, modelMemberAttributeType.Name.ToAttributeName()).WithAdditionalAnnotations(Formatter.Annotation, propertyAnnotation);

            editor.AddMember(ModelClass, property);

            await AddMissingNamespaces(editor, imports, ct);

            var result = await editor.FormatAsync(ct);

            return(result, propertyAnnotation);
        }
        private async Task <(Document Document, SyntaxAnnotation MethodAnnotation)> AddComputationMethodAsync(string name,
                                                                                                              INamedTypeSymbol modelAttributeType, INamedTypeSymbol modelMemberAttributeType, CancellationToken ct = default(CancellationToken), params INamedTypeSymbol[] typesToImport)
        {
            var editor = await DocumentEditor.CreateAsync(Document, ct);

            var g        = editor.Generator;
            var voidType = Compilation.GetSpecialType(SpecialType.System_Void);
            var imports  = new NamespaceSet
            {
                modelAttributeType,
                modelMemberAttributeType
            };

            if (typesToImport != null && typesToImport.Length > 0)
            {
                for (int i = 0; i < typesToImport.Length; i++)
                {
                    var typeToImport = typesToImport[i];
                    if (typeToImport != null)
                    {
                        imports.Add(typeToImport);
                    }
                }
            }

            var methodBody       = g.GenerateNotImplemented(Compilation);
            var method           = g.MethodDeclaration(name, null, null, null, Accessibility.Private, default(DeclarationModifiers), statements: new SyntaxNode[] { methodBody });
            var methodAnnotation = new SyntaxAnnotation();

            method = GenerateAttribute(method, modelMemberAttributeType.Name.ToAttributeName()).WithAdditionalAnnotations(Formatter.Annotation, methodAnnotation);

            editor.AddMember(ModelClass, method);

            await AddMissingNamespaces(editor, imports, ct);

            var result = await editor.FormatAsync(ct);

            return(result, methodAnnotation);
        }
示例#22
0
        internal async Task <(Document Document, TextSpan?TextSpan)> AddMemberAttribute(ISymbol symbol, INamedTypeSymbol attributeClass,
                                                                                        string specAttributeKnownType, string namedRequiresArgument = "RequiresArgument", CancellationToken ct = default(CancellationToken))
        {
            var editor = await DocumentEditor.CreateAsync(Document, ct);

            var g       = editor.Generator;
            var imports = new NamespaceSet {
                attributeClass
            };

            var syntaxNode = GetSyntaxNode(symbol);
            var leadingWhitespaceTrivia = GetLeadingWhitespaceTrivia(syntaxNode);
            var hasArgumentList         = HasArgumentList(attributeClass, specAttributeKnownType, namedRequiresArgument);
            var argumentListAnnotation  = hasArgumentList ? new SyntaxAnnotation() : null;
            var newSyntaxNode           = GenerateAttribute(syntaxNode, attributeClass.Name.ToAttributeName(), leadingWhitespaceTrivia, argumentListAnnotation);

            editor.ReplaceNode(syntaxNode, newSyntaxNode);

            await AddMissingNamespaces(editor, imports, ct);

            var resultDocument = await editor.FormatAsync(ct);

            TextSpan?textSpan;

            if (argumentListAnnotation != null)
            {
                var resultRoot = await resultDocument.GetSyntaxRootAsync(ct);

                var argumentListSyntax = resultRoot.GetAnnotatedNodes(argumentListAnnotation).Single();
                textSpan = new TextSpan(argumentListSyntax.FullSpan.Start + 1, 0);
            }
            else
            {
                textSpan = null;
            }

            return(resultDocument, textSpan);
        }
示例#23
0
        private static NamespaceSet GetImports(this DataSet <DataSetEntry> entries, Compilation compilation)
        {
            var result = new NamespaceSet();
            var _      = entries._;

            for (int i = 0; i < entries.Count; i++)
            {
                var referencedTypes = _.ReferencedTypes[i];
                using (StringReader reader = new StringReader(referencedTypes))
                {
                    for (var referencedType = reader.ReadLine(); referencedType != null; referencedType = reader.ReadLine())
                    {
                        var type = compilation.GetTypeByMetadataName(referencedType);
                        if (type != null)
                        {
                            result.Add(type);
                        }
                    }
                }
            }

            return(result);
        }
示例#24
0
 protected Task AddMissingNamespaces(DocumentEditor editor, NamespaceSet namespaces, CancellationToken ct)
 {
     return(editor.AddMissingNamespacesAsync(namespaces, Compilation, ContainingNamespace, SyntaxTree, SemanticModel, ct));
 }
示例#25
0
        private IEnumerable <SyntaxNode> GenerateColumnProperties <T>(SyntaxGenerator g, NamespaceSet imports, DataSet <T> entries)
            where T : ProjectionEntry, new()
        {
            var _ = entries._;

            for (int i = 0; i < entries.Count; i++)
            {
                var column = _.Column[i];
                var type   = column.Type;
                imports.Add(type);
                foreach (var result in GenerateColumnProperty(g, type, column.Name))
                {
                    yield return(result);
                }
            }
        }
示例#26
0
 private static SyntaxNode GenerateStaticConstructorForColumnRegistration <T>(SyntaxGenerator g, NamespaceSet imports, string language, INamedTypeSymbol modelType, string className, DataSet <T> entries)
     where T : ProjectionEntry, new()
 {
     return(g.ConstructorDeclaration(className, modifiers: DeclarationModifiers.Static,
                                     statements: GenerateColumnRegistration(g, imports, language, modelType, className, entries)));
 }
示例#27
0
        private static SyntaxNode[] GenerateColumnRegistration <T>(SyntaxGenerator g, NamespaceSet imports, string language, INamedTypeSymbol modelType, string className, DataSet <T> entries)
            where T : ProjectionEntry, new()
        {
            var _      = entries._;
            var result = new SyntaxNode[entries.Count];

            for (int i = 0; i < result.Length; i++)
            {
                result[i] = GenerateColumnRegistration(g, imports, language, modelType, className, _.Column[i], _.Mounter[i]);
            }

            return(result);
        }