Ejemplo n.º 1
0
 public static SyntaxList <AttributeListSyntax> GenerateAttributeLists(
     ImmutableArray <AttributeData> attributes,
     CSharpCodeGenerationOptions options,
     SyntaxToken?target = null)
 {
     if (options.Context.MergeAttributes)
     {
         var attributeNodes =
             attributes.OrderBy(a => a.AttributeClass?.Name)
             .Select(a => TryGenerateAttribute(a, options))
             .WhereNotNull().ToList();
         return(attributeNodes.Count == 0
             ? default
             : SyntaxFactory.SingletonList(SyntaxFactory.AttributeList(
                                               target.HasValue ? SyntaxFactory.AttributeTargetSpecifier(target.Value) : null,
                                               SyntaxFactory.SeparatedList(attributeNodes))));
     }
     else
     {
         var attributeDeclarations =
             attributes.OrderBy(a => a.AttributeClass?.Name)
             .Select(a => TryGenerateAttributeDeclaration(a, target, options))
             .WhereNotNull().ToList();
         return(attributeDeclarations.Count == 0
             ? default
             : SyntaxFactory.List <AttributeListSyntax>(attributeDeclarations));
     }
 }
Ejemplo n.º 2
0
        public override SyntaxNode MakeSyntaxNode()
        {
            var res = SyntaxFactory.AttributeTargetSpecifier(Identifier, ColonToken);

            IsChanged = false;
            return(res);
        }
Ejemplo n.º 3
0
            private SyntaxNode ProcessNativeTypeNameAttr(AttributeSyntax nativeTypeNameAttr, out bool marshalAs)
            {
                string nativeType = nativeTypeNameAttr.ArgumentList.Arguments[0].ToString();

                nativeType = EncodeHelpers.RemoveQuotes(nativeType);

                List <AttributeSyntax> attributeNodes = new List <AttributeSyntax>();

                marshalAs = this.AddNativeTypeInfoAttribute(nativeType, attributeNodes);
                if (attributeNodes.Count == 0)
                {
                    return(null);
                }

                var ret = SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributeNodes));

                if (((AttributeListSyntax)nativeTypeNameAttr.Parent).Target is AttributeTargetSpecifierSyntax target &&
                    target.Identifier.ValueText == "return")
                {
                    ret =
                        ret.WithTarget(
                            SyntaxFactory.AttributeTargetSpecifier(
                                SyntaxFactory.Token(SyntaxKind.ReturnKeyword)));
                }

                return(ret);
            }
Ejemplo n.º 4
0
        private static AttributeListSyntax CreateAttributeList(
            ISymbol targetSymbol,
            NameSyntax attributeName,
            Diagnostic diagnostic,
            bool isAssemblyAttribute,
            SyntaxTriviaList leadingTrivia)
        {
            var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute);

            var attributes = new SeparatedSyntaxList <AttributeSyntax>()
                             .Add(SyntaxFactory.Attribute(attributeName, attributeArguments));

            AttributeListSyntax attributeList;

            if (isAssemblyAttribute)
            {
                var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword));
                attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes);
            }
            else
            {
                attributeList = SyntaxFactory.AttributeList(attributes);
            }

            return(attributeList.WithLeadingTrivia(leadingTrivia));
        }
Ejemplo n.º 5
0
        private AttributeListSyntax CreateAttributeList(
            ISymbol targetSymbol,
            Diagnostic diagnostic,
            bool isAssemblyAttribute,
            SyntaxTriviaList leadingTrivia,
            bool needsLeadingEndOfLine)
        {
            var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute);
            var attribute          = SyntaxFactory.Attribute(SyntaxFactory.ParseName(SuppressMessageAttributeName), attributeArguments);
            var attributes         = new SeparatedSyntaxList <AttributeSyntax>().Add(attribute);

            AttributeListSyntax attributeList;

            if (isAssemblyAttribute)
            {
                var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword));
                attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes);
            }
            else
            {
                attributeList = SyntaxFactory.AttributeList(attributes);
            }

            var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed;
            var triviaList      = SyntaxFactory.TriviaList();

            if (needsLeadingEndOfLine)
            {
                triviaList = triviaList.Add(endOfLineTrivia);
            }

            return(attributeList.WithLeadingTrivia(leadingTrivia.AddRange(triviaList)));
        }
Ejemplo n.º 6
0
        private static async Task TestAsync(string initialText, string attributeAddedText)
        {
            var doc     = GetDocument(initialText);
            var options = await doc.GetOptionsAsync();

            var attributeList =
                SyntaxFactory.AttributeList(
                    SyntaxFactory.SingletonSeparatedList(
                        SyntaxFactory.Attribute(
                            SyntaxFactory.IdentifierName("System.Reflection.AssemblyVersion(\"1.0.0.0\")"))))
                .WithTarget(
                    SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)));

            var syntaxRoot = await doc.GetSyntaxRootAsync();

            var editor = await DocumentEditor.CreateAsync(doc);

            editor.AddAttribute(syntaxRoot, attributeList);

            var changedDoc = editor.GetChangedDocument();

            if (attributeAddedText != null)
            {
                var formatted = await Formatter.FormatAsync(changedDoc, SyntaxAnnotation.ElasticAnnotation, options);

                var actualText = (await formatted.GetTextAsync()).ToString();

                Assert.Equal(attributeAddedText, actualText);
            }
        }
 public CompilationUnitSyntax Enrich(CompilationUnitSyntax syntax) => syntax
 .AddAttributeLists(
     SyntaxFactory.AttributeList().AddAttributes(
         SyntaxFactory.Attribute(SyntaxFactory.ParseName("System.Runtime.Versioning.TargetFramework"))
         .AddArgumentListArguments(
             SyntaxFactory.AttributeArgument(SyntaxHelpers.StringLiteral(".NETStandard,Version=v2.0")),
             SyntaxFactory.AttributeArgument(SyntaxHelpers.StringLiteral(""))
             .WithNameEquals(SyntaxFactory.NameEquals("FrameworkDisplayName"))))
     .WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))));
Ejemplo n.º 8
0
        public ScriptLoader(string generatedScriptOutput = null)
        {
            var suppressions = new Dictionary <string, ReportDiagnostic>
            {
                { "CS1998", ReportDiagnostic.Suppress }
            };


            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                                  specificDiagnosticOptions: suppressions,
                                                                  optimizationLevel: OptimizationLevel.Debug,
                                                                  platform: Platform.AnyCpu);

            var baseLibPath = Path.GetDirectoryName(typeof(object).Assembly.Location);

            var tpa = (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES");

            this.generatedScriptOutput = generatedScriptOutput;
            this.compilation           = CSharpCompilation.Create(AssemblyName, options: compilationOptions)
                                         .AddReferences(MetadataReference.CreateFromFile(typeof(ScriptLoader).Assembly.Location))
                                         .AddReferences(MetadataReference.CreateFromFile(Path.Combine(baseLibPath, "mscorlib.dll")))
                                         .AddReferences(MetadataReference.CreateFromFile(Path.Combine(baseLibPath, "System.dll")))
                                         .AddReferences(MetadataReference.CreateFromFile(Path.Combine(baseLibPath, "System.Core.dll")));

            foreach (var asmPath in tpa.Split(';'))
            {
                this.compilation = this.compilation.AddReferences(
                    MetadataReference.CreateFromFile(asmPath));
            }

            foreach (var reference in typeof(ScriptLoader).Assembly.GetReferencedAssemblies())
            {
                if (reference.CodeBase != null)
                {
                    compilation = compilation.AddReferences(MetadataReference.CreateFromFile(reference.CodeBase));
                }
            }

            var targetFrameworkUnit = SyntaxFactory.CompilationUnit()
                                      .AddAttributeLists(
                SyntaxFactory.AttributeList(
                    SyntaxFactory.SingletonSeparatedList(
                        SyntaxFactory.Attribute(SyntaxFactory.QualifiedName(
                                                    SyntaxFactory.QualifiedName(
                                                        SyntaxFactory.QualifiedName(
                                                            SyntaxFactory.IdentifierName("System"),
                                                            SyntaxFactory.IdentifierName("Runtime")),
                                                        SyntaxFactory.IdentifierName("Versioning")),
                                                    SyntaxFactory.IdentifierName("TargetFrameworkAttribute")))
                        .AddArgumentListArguments(
                            SyntaxFactory.AttributeArgument(SyntaxUtil.LiteralExpression(".NETStandard,Version=v2.1")),
                            SyntaxFactory.AttributeArgument(SyntaxUtil.LiteralExpression(""))
                            .WithNameEquals(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName("FrameworkDisplayName"))))))
                .WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))));

            this.compilation = this.compilation.AddSyntaxTrees(targetFrameworkUnit.SyntaxTree);
        }
        private static AttributeListSyntax GetAttributeListToBeAdded(string containingNamespaceName, string className)
        {
            var attributeName = SyntaxFactory.ParseName("RegisterModule");
            var attributeArgumentListSyntax    = SyntaxFactory.ParseAttributeArgumentList($"(typeof({containingNamespaceName}.{className}))");
            var separatedSyntaxList            = default(SeparatedSyntaxList <AttributeSyntax>).Add(SyntaxFactory.Attribute(attributeName, attributeArgumentListSyntax));
            var attributeTargetSpecifierSyntax = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Identifier("assembly"));
            var attributeToBeAdded             = SyntaxFactory.AttributeList(attributeTargetSpecifierSyntax, separatedSyntaxList);

            return(attributeToBeAdded);
        }
Ejemplo n.º 10
0
        protected override void Execute(
            GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource <TypeDeclarationSyntax> addCacheSource,
            ReportCacheDiagnostic <TypeDeclarationSyntax> cacheDiagnostic
            )
        {
            var namespaces = new HashSet <string>()
            {
                "OmniSharp.Extensions.LanguageServer.Protocol"
            };
            var types = syntaxReceiver.FoundNodes
                        .Concat(syntaxReceiver.Handlers)
                        .Select(
                options => {
                var semanticModel = context.Compilation.GetSemanticModel(options.SyntaxTree);
                foreach (var item in options.SyntaxTree.GetCompilationUnitRoot()
                         .Usings
                         .Where(z => z.Alias == null)
                         .Select(z => z.Name.ToFullString()))
                {
                    namespaces.Add(item);
                }

                var typeSymbol = semanticModel.GetDeclaredSymbol(options) !;

                return(SyntaxFactory.Attribute(
                           SyntaxFactory.IdentifierName("AssemblyCapabilityKey"), SyntaxFactory.AttributeArgumentList(
                               SyntaxFactory.SeparatedList(
                                   new[] {
                    SyntaxFactory.AttributeArgument(
                        SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseName(typeSymbol.ToDisplayString()))
                        ),
                }.Concat(options.AttributeLists.GetAttribute("CapabilityKey") !.ArgumentList !.Arguments)
                                   )
                               )
                           ));
            }
                )
                        .ToArray();

            if (types.Any())
            {
                var cu = SyntaxFactory.CompilationUnit()
                         .WithUsings(SyntaxFactory.List(namespaces.OrderBy(z => z).Select(z => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(z)))))
                         .AddAttributeLists(
                    SyntaxFactory.AttributeList(
                        target: SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)), SyntaxFactory.SeparatedList(types)
                        )
                    )
                         .WithLeadingTrivia(SyntaxFactory.Comment(Preamble.GeneratedByATool))
                         .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);

                context.AddSource("AssemblyCapabilityKeys.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8));
            }
        }
Ejemplo n.º 11
0
        private static AttributeListSyntax GenerateAttributeDeclaration(
            AttributeData attribute, SyntaxToken?target, CodeGenerationOptions options)
        {
            var attributeSyntax = GenerateAttribute(attribute, options);

            return(attributeSyntax == null
                ? null
                : SyntaxFactory.AttributeList(
                       target.HasValue ? SyntaxFactory.AttributeTargetSpecifier(target.Value) : null,
                       SyntaxFactory.SingletonSeparatedList(attributeSyntax)));
        }
Ejemplo n.º 12
0
        private static AttributeListSyntax?TryGenerateAttributeDeclaration(
            AttributeData attribute, SyntaxToken?target, CSharpCodeGenerationContextInfo info)
        {
            var attributeSyntax = TryGenerateAttribute(attribute, info);

            return(attributeSyntax == null
                ? null
                : SyntaxFactory.AttributeList(
                       target.HasValue
                        ? SyntaxFactory.AttributeTargetSpecifier(target.Value)
                        : null,
                       SyntaxFactory.SingletonSeparatedList(attributeSyntax)));
        }
 public CompilationUnitSyntax Enrich(CompilationUnitSyntax target) =>
 target.AddAttributeLists(
     SyntaxFactory.AttributeList().AddAttributes(
         SyntaxFactory.Attribute(SyntaxFactory.ParseName("System.Reflection.AssemblyVersion"))
         .AddArgumentListArguments(SyntaxFactory.AttributeArgument(
                                       SyntaxHelpers.StringLiteral(_settings.Version.ToString()))))
     .WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),
     SyntaxFactory.AttributeList().AddAttributes(
         SyntaxFactory.Attribute(SyntaxFactory.ParseName("System.Reflection.AssemblyFileVersion"))
         .AddArgumentListArguments(SyntaxFactory.AttributeArgument(
                                       SyntaxHelpers.StringLiteral(_settings.Version.ToString()))))
     .WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),
     SyntaxFactory.AttributeList().AddAttributes(
         SyntaxFactory.Attribute(SyntaxFactory.ParseName("System.Reflection.AssemblyInformationalVersion"))
         .AddArgumentListArguments(SyntaxFactory.AttributeArgument(
                                       SyntaxHelpers.StringLiteral(_settings.Version.ToString() + (_settings.VersionSuffix ?? "")))))
     .WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))));
Ejemplo n.º 14
0
            public override SyntaxNode VisitDelegateDeclaration(DelegateDeclarationSyntax node)
            {
                string fullName = SyntaxUtils.GetFullName(node);

                // Remove duplicate delegates in this tree
                if (this.visitedDelegateNames.Contains(fullName))
                {
                    return(null);
                }

                this.visitedDelegateNames.Add(fullName);

                string returnFullName = $"{fullName}::return";

                if (this.GetRemapInfo(returnFullName, out List <AttributeSyntax> listAttributes, node.ReturnType.ToString(), out var newType, out _))
                {
                    node = (DelegateDeclarationSyntax)base.VisitDelegateDeclaration(node);
                    if (listAttributes != null)
                    {
                        foreach (var attrNode in listAttributes)
                        {
                            var attrListNode =
                                SyntaxFactory.AttributeList(
                                    SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(attrNode))
                                .WithTarget(
                                    SyntaxFactory.AttributeTargetSpecifier(
                                        SyntaxFactory.Token(SyntaxKind.ReturnKeyword)));

                            node = node.WithAttributeLists(node.AttributeLists.Add(attrListNode));
                        }

                        if (newType != null)
                        {
                            node = node.WithReturnType(SyntaxFactory.ParseTypeName(newType).WithTrailingTrivia(SyntaxFactory.Space));
                        }
                    }

                    return(node);
                }

                return(base.VisitDelegateDeclaration(node));
            }
Ejemplo n.º 15
0
        private SyntaxNode CreateProxyClassSyntax(INamedTypeSymbol currentInterface, string className, IEnumerable <string> folders)
        {
            var targetNamespace = _project.DefaultNamespace;

            if (folders.Any())
            {
                targetNamespace = $"{targetNamespace}.{string.Join(".", folders.Select(x => $"{x.Substring(0, 1).ToUpper()}{x.Substring(1)}"))}";
            }

            var constructors = GenerateConstructors(currentInterface, className);
            var methods      = GenerateMethods(currentInterface);

            var classDeclaration = SyntaxFactory.ClassDeclaration(className)
                                   .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                                   .AddBaseListTypes(
                SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName($"Codeworx.Rest.Client.RestClient<{currentInterface.AssemblyQualifiedName()}>")),
                SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(currentInterface.AssemblyQualifiedName())))
                                   .AddMembers(constructors)
                                   .AddMembers(methods);

            var namespaceSyntax = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(targetNamespace))
                                  .AddMembers(classDeclaration)
                                  .NormalizeWhitespace();

            var result = SyntaxFactory.CompilationUnit()
                         .AddAttributeLists(
                SyntaxFactory.AttributeList()
                .WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Identifier("assembly")))
                .AddAttributes(
                    SyntaxFactory.Attribute(SyntaxFactory.ParseName("Codeworx.Rest.RestProxy"))
                    .AddArgumentListArguments(
                        SyntaxFactory.AttributeArgument(
                            SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseTypeName(currentInterface.AssemblyQualifiedName()))),
                        SyntaxFactory.AttributeArgument(
                            SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseTypeName($"{targetNamespace}.{classDeclaration.Identifier.Text}"))))))
                         .WithLeadingTrivia(
                SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// <auto-generated />"))
                         .AddMembers(namespaceSyntax);

            return(result.NormalizeWhitespace());
        }
Ejemplo n.º 16
0
        private async static Task <Document> RemoveInternalsVisibleToAttribute(Document document, SyntaxToken token, CancellationToken cancellationToken)
        {
            var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

            var attributeList = token.Parent.Parent.Parent as AttributeListSyntax;

            var tokenToRemove = token.Parent.Parent.Parent;
            var spanToRemove  = TextSpan.FromBounds(tokenToRemove.Span.Start, tokenToRemove.Span.End);

            if (attributeList.Attributes.Count == 1)
            {
                return(document.WithText(sourceText.WithChanges(new TextChange(spanToRemove, string.Empty))));
            }

            var newAttributeNodes = new List <AttributeSyntax>();

            foreach (AttributeSyntax attribute in attributeList.Attributes)
            {
                if (attribute.Name is IdentifierNameSyntax name && name.Identifier.Text == "InternalsVisibleTo")
                {
                    continue;
                }

                newAttributeNodes.Add(attribute);
            }

            var assemblyKeyword  = SyntaxFactory.Token(SyntaxKind.AssemblyKeyword);
            var colon            = SyntaxFactory.Token(SyntaxFactory.TriviaList(), SyntaxKind.ColonToken, SyntaxFactory.TriviaList(SyntaxFactory.Whitespace(" ")));
            var target           = SyntaxFactory.AttributeTargetSpecifier(assemblyKeyword, colon);
            var newAttributes    = SyntaxFactory.SeparatedList(newAttributeNodes);
            var newAttributeList = SyntaxFactory.AttributeList(SyntaxFactory.Token(SyntaxKind.OpenBracketToken), target, newAttributes, SyntaxFactory.Token(SyntaxKind.CloseBracketToken));

            var change = new TextChange(spanToRemove, newAttributeList.ToString());

            return(document.WithText(sourceText.WithChanges(change)));
        }
Ejemplo n.º 17
0
            public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
            {
                // Skip methods where we weren't given a import lib name. Should we warn the caller?
                if (node.AttributeLists.ToString().Contains("[DllImport(\"\""))
                {
                    return(null);
                }

                string fullName = SyntaxUtils.GetFullName(node);

                // Remove duplicate static methods
                if (node.Body == null)
                {
                    // If this function is supposed to be in a certain namespace, remove it if it's not.
                    // We only respect this for static methods
                    if (this.requiredNamespaces.TryGetValue(fullName, out var requiredNamespace))
                    {
                        var ns = GetEnclosingNamespace(node);
                        if (ns != requiredNamespace)
                        {
                            return(null);
                        }
                    }

                    // Remove duplicate methods in this tree
                    if (this.visitedStaticMethodNames.Contains(fullName))
                    {
                        return(null);
                    }

                    this.visitedStaticMethodNames.Add(fullName);
                }
                // Any method with a body has to be part of a call to a vtable for an interface.
                // If it's not, get rid of it
                else if (!node.Body.ToString().Contains("GetDelegateForFunctionPointer"))
                {
                    return(null);
                }

                string returnFullName = $"{fullName}::return";

                // Find remap info for the return parameter for this method and apply any that we find
                if (this.GetRemapInfo(returnFullName, out List <AttributeSyntax> listAttributes, node.ReturnType.ToString(), out var newType, out _))
                {
                    node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node);
                    if (listAttributes != null)
                    {
                        foreach (var attrNode in listAttributes)
                        {
                            var attrListNode =
                                SyntaxFactory.AttributeList(
                                    SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(attrNode))
                                .WithTarget(
                                    SyntaxFactory.AttributeTargetSpecifier(
                                        SyntaxFactory.Token(SyntaxKind.ReturnKeyword)));

                            node = node.WithAttributeLists(node.AttributeLists.Add(attrListNode));
                        }
                    }

                    if (newType != null)
                    {
                        node = node.WithReturnType(SyntaxFactory.ParseTypeName(newType).WithTrailingTrivia(SyntaxFactory.Space));
                    }

                    return(node);
                }

                return(base.VisitMethodDeclaration(node));
            }
Ejemplo n.º 18
0
        private static SyntaxTree GetAssemblyInfo(AssemblyInfo info)
        {
            return(SyntaxFactory.CompilationUnit()
                   // start: add using patterns code and set custom qualified name for assembly basic head info, example as

                   /*
                    * using System.Reflection
                    * using System.Runtime.InteropServices
                    * using System.Runtime.Versioning
                    */
                   .WithUsings(
                       SyntaxFactory.List(
                           new[]
            {
                SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName(
                                                 SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Reflection"))),
                SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName(
                                                 SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"),
                                                                             SyntaxFactory.IdentifierName("Runtime")),
                                                 SyntaxFactory.IdentifierName("InteropServices"))),
                SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName(
                                                 SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"),
                                                                             SyntaxFactory.IdentifierName("Runtime")),
                                                 SyntaxFactory.IdentifierName("Versioning")))
            }))
                   // before
                   // start: add reflection code and set custom tips text or framework version

                   /*
                    *  [0] = {AttributeListSyntax} "[assembly:TargetFramework(".NETFramework,Version=v4.5",FrameworkDisplayName=".NET Framework 4.5")]"
                    *  [1] = {AttributeListSyntax} "[assembly:AssemblyTitle("Rabbit.Rpc.ClientProxys")]"
                    *  [2] = {AttributeListSyntax} "[assembly:AssemblyProduct("Rabbit.Rpc.ClientProxys")]"
                    *  [3] = {AttributeListSyntax} "[assembly:AssemblyCopyright("Copyright ©  Rabbit")]"
                    *  [4] = {AttributeListSyntax} "[assembly:ComVisible(false)]"
                    *  [5] = {AttributeListSyntax} "[assembly:Guid("a40f0c95-b12d-4f76-a983-d7fea7a90f1d")]"
                    *  [6] = {AttributeListSyntax} "[assembly:AssemblyVersion("1.0.0.0")]"
                    *  [7] = {AttributeListSyntax} "[assembly:AssemblyFileVersion("1.0.0.0")]"
                    */
                   .WithAttributeLists(
                       SyntaxFactory.List(
                           new[]
            {
                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory
                                                                                 .Attribute(SyntaxFactory.IdentifierName("TargetFramework"))
                                                                                 .WithArgumentList(SyntaxFactory.AttributeArgumentList(
                                                                                                       SyntaxFactory.SeparatedList <AttributeArgumentSyntax>(
                                                                                                           new SyntaxNodeOrToken[]
                {
                    SyntaxFactory.AttributeArgument(
                        SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                        SyntaxFactory.Literal(".NETFramework,Version=v4.5"))),
                    SyntaxFactory.Token(SyntaxKind.CommaToken),
                    SyntaxFactory
                    .AttributeArgument(SyntaxFactory.LiteralExpression(
                                           SyntaxKind.StringLiteralExpression,
                                           SyntaxFactory.Literal(".NET Framework 4.5")))
                    .WithNameEquals(SyntaxFactory.NameEquals(
                                        SyntaxFactory.IdentifierName("FrameworkDisplayName")))
                })))))
                .WithTarget(
                    SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),

                // [AssemblyTitle("Rabbit.Rpc.ClientProxys")]
                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory
                                                                                 .Attribute(SyntaxFactory.IdentifierName("AssemblyTitle"))
                                                                                 .WithArgumentList(
                                                                                     SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                                                                                             SyntaxFactory.AttributeArgument(
                                                                                                                                 SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                                                                                                                                 SyntaxFactory.Literal(info.Title))))))))
                .WithTarget(
                    SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),

                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory
                                                                                 .Attribute(SyntaxFactory.IdentifierName("AssemblyProduct"))
                                                                                 .WithArgumentList(
                                                                                     SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                                                                                             SyntaxFactory.AttributeArgument(
                                                                                                                                 SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                                                                                                                                 SyntaxFactory.Literal(info.Product))))))))
                .WithTarget(
                    SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),

                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory
                                                                                 .Attribute(SyntaxFactory.IdentifierName("AssemblyCopyright"))
                                                                                 .WithArgumentList(
                                                                                     SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                                                                                             SyntaxFactory.AttributeArgument(
                                                                                                                                 SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                                                                                                                                 SyntaxFactory.Literal(info.Copyright))))))))
                .WithTarget(
                    SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),

                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory
                                                                                 .Attribute(SyntaxFactory.IdentifierName("ComVisible"))
                                                                                 .WithArgumentList(
                                                                                     SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                                                                                             SyntaxFactory.AttributeArgument(
                                                                                                                                 SyntaxFactory.LiteralExpression(info.ComVisible
                                                    ? SyntaxKind.TrueLiteralExpression
                                                    : SyntaxKind.FalseLiteralExpression)))))))
                .WithTarget(
                    SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),

                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory
                                                                                 .Attribute(SyntaxFactory.IdentifierName("Guid"))
                                                                                 .WithArgumentList(
                                                                                     SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                                                                                             SyntaxFactory.AttributeArgument(
                                                                                                                                 SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                                                                                                                                 SyntaxFactory.Literal(info.Guid))))))))
                .WithTarget(
                    SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),

                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory
                                                                                 .Attribute(SyntaxFactory.IdentifierName("AssemblyVersion"))
                                                                                 .WithArgumentList(
                                                                                     SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                                                                                             SyntaxFactory.AttributeArgument(
                                                                                                                                 SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                                                                                                                                 SyntaxFactory.Literal(info.Version))))))))
                .WithTarget(
                    SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),

                SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory
                                                                                 .Attribute(SyntaxFactory.IdentifierName("AssemblyFileVersion"))
                                                                                 .WithArgumentList(
                                                                                     SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                                                                                             SyntaxFactory.AttributeArgument(
                                                                                                                                 SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                                                                                                                                 SyntaxFactory.Literal(info.FileVersion))))))))
                .WithTarget(
                    SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)))
            }))
                   .NormalizeWhitespace()
                   .SyntaxTree);
        }
Ejemplo n.º 19
0
 private static SyntaxTree GetAssemblyInfo(AssemblyInfo info)
 {
     return(SyntaxFactory.CompilationUnit()
            .WithUsings(
                SyntaxFactory.List(
                    new[]
     {
         SyntaxFactory.UsingDirective(
             SyntaxFactory.QualifiedName(
                 SyntaxFactory.IdentifierName("System"),
                 SyntaxFactory.IdentifierName("Reflection"))),
         SyntaxFactory.UsingDirective(
             SyntaxFactory.QualifiedName(
                 SyntaxFactory.QualifiedName(
                     SyntaxFactory.IdentifierName("System"),
                     SyntaxFactory.IdentifierName("Runtime")),
                 SyntaxFactory.IdentifierName("InteropServices"))),
         SyntaxFactory.UsingDirective(
             SyntaxFactory.QualifiedName(
                 SyntaxFactory.QualifiedName(
                     SyntaxFactory.IdentifierName("System"),
                     SyntaxFactory.IdentifierName("Runtime")),
                 SyntaxFactory.IdentifierName("Versioning")))
     }))
            .WithAttributeLists(
                SyntaxFactory.List(
                    new[]
     {
         SyntaxFactory.AttributeList(
             SyntaxFactory.SingletonSeparatedList(
                 SyntaxFactory.Attribute(
                     SyntaxFactory.IdentifierName("TargetFramework"))
                 .WithArgumentList(
                     SyntaxFactory.AttributeArgumentList(
                         SyntaxFactory.SeparatedList <AttributeArgumentSyntax>(
                             new SyntaxNodeOrToken[] {
             SyntaxFactory.AttributeArgument(
                 SyntaxFactory.LiteralExpression(
                     SyntaxKind.StringLiteralExpression,
                     SyntaxFactory.Literal(".NETFramework,Version=v4.5"))),
             SyntaxFactory.Token(SyntaxKind.CommaToken),
             SyntaxFactory.AttributeArgument(
                 SyntaxFactory.LiteralExpression(
                     SyntaxKind.StringLiteralExpression,
                     SyntaxFactory.Literal(".NET Framework 4.5")))
             .WithNameEquals(
                 SyntaxFactory.NameEquals(
                     SyntaxFactory.IdentifierName("FrameworkDisplayName")))
         })))))
         .WithTarget(
             SyntaxFactory.AttributeTargetSpecifier(
                 SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),
         SyntaxFactory.AttributeList(
             SyntaxFactory.SingletonSeparatedList(
                 SyntaxFactory.Attribute(
                     SyntaxFactory.IdentifierName("AssemblyTitle"))
                 .WithArgumentList(
                     SyntaxFactory.AttributeArgumentList(
                         SyntaxFactory.SingletonSeparatedList(
                             SyntaxFactory.AttributeArgument(
                                 SyntaxFactory.LiteralExpression(
                                     SyntaxKind.StringLiteralExpression,
                                     SyntaxFactory.Literal(info.Title))))))))
         .WithTarget(
             SyntaxFactory.AttributeTargetSpecifier(
                 SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),
         SyntaxFactory.AttributeList(
             SyntaxFactory.SingletonSeparatedList(
                 SyntaxFactory.Attribute(
                     SyntaxFactory.IdentifierName("AssemblyProduct"))
                 .WithArgumentList(
                     SyntaxFactory.AttributeArgumentList(
                         SyntaxFactory.SingletonSeparatedList(
                             SyntaxFactory.AttributeArgument(
                                 SyntaxFactory.LiteralExpression(
                                     SyntaxKind.StringLiteralExpression,
                                     SyntaxFactory.Literal(info.Product))))))))
         .WithTarget(
             SyntaxFactory.AttributeTargetSpecifier(
                 SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),
         SyntaxFactory.AttributeList(
             SyntaxFactory.SingletonSeparatedList(
                 SyntaxFactory.Attribute(
                     SyntaxFactory.IdentifierName("AssemblyCopyright"))
                 .WithArgumentList(
                     SyntaxFactory.AttributeArgumentList(
                         SyntaxFactory.SingletonSeparatedList(
                             SyntaxFactory.AttributeArgument(
                                 SyntaxFactory.LiteralExpression(
                                     SyntaxKind.StringLiteralExpression,
                                     SyntaxFactory.Literal(info.Copyright))))))))
         .WithTarget(
             SyntaxFactory.AttributeTargetSpecifier(
                 SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),
         SyntaxFactory.AttributeList(
             SyntaxFactory.SingletonSeparatedList(
                 SyntaxFactory.Attribute(
                     SyntaxFactory.IdentifierName("ComVisible"))
                 .WithArgumentList(
                     SyntaxFactory.AttributeArgumentList(
                         SyntaxFactory.SingletonSeparatedList(
                             SyntaxFactory.AttributeArgument(
                                 SyntaxFactory.LiteralExpression(info.ComVisible
                                                     ? SyntaxKind.TrueLiteralExpression
                                                     : SyntaxKind.FalseLiteralExpression)))))))
         .WithTarget(
             SyntaxFactory.AttributeTargetSpecifier(
                 SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),
         SyntaxFactory.AttributeList(
             SyntaxFactory.SingletonSeparatedList(
                 SyntaxFactory.Attribute(
                     SyntaxFactory.IdentifierName("Guid"))
                 .WithArgumentList(
                     SyntaxFactory.AttributeArgumentList(
                         SyntaxFactory.SingletonSeparatedList(
                             SyntaxFactory.AttributeArgument(
                                 SyntaxFactory.LiteralExpression(
                                     SyntaxKind.StringLiteralExpression,
                                     SyntaxFactory.Literal(info.Guid))))))))
         .WithTarget(
             SyntaxFactory.AttributeTargetSpecifier(
                 SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),
         SyntaxFactory.AttributeList(
             SyntaxFactory.SingletonSeparatedList(
                 SyntaxFactory.Attribute(
                     SyntaxFactory.IdentifierName("AssemblyVersion"))
                 .WithArgumentList(
                     SyntaxFactory.AttributeArgumentList(
                         SyntaxFactory.SingletonSeparatedList(
                             SyntaxFactory.AttributeArgument(
                                 SyntaxFactory.LiteralExpression(
                                     SyntaxKind.StringLiteralExpression,
                                     SyntaxFactory.Literal(info.Version))))))))
         .WithTarget(
             SyntaxFactory.AttributeTargetSpecifier(
                 SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))),
         SyntaxFactory.AttributeList(
             SyntaxFactory.SingletonSeparatedList(
                 SyntaxFactory.Attribute(
                     SyntaxFactory.IdentifierName("AssemblyFileVersion"))
                 .WithArgumentList(
                     SyntaxFactory.AttributeArgumentList(
                         SyntaxFactory.SingletonSeparatedList(
                             SyntaxFactory.AttributeArgument(
                                 SyntaxFactory.LiteralExpression(
                                     SyntaxKind.StringLiteralExpression,
                                     SyntaxFactory.Literal(info.FileVersion))))))))
         .WithTarget(
             SyntaxFactory.AttributeTargetSpecifier(
                 SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)))
     }))
            .NormalizeWhitespace()
            .SyntaxTree);
 }
Ejemplo n.º 20
0
 public static SyntaxList <AttributeSyntax> GenerateAttributeLists(
     ImmutableArray <AttributeData> attributes,
     CodeGenerationOptions options,
     SyntaxToken?target = null)
 {
     if (options.MergeAttributes)
     {
         var attributeNodes = attributes.OrderBy(a => a.AttributeClass.Name).Select(a => GenerateAttribute(target.HasValue ? SyntaxFactory.AttributeTargetSpecifier(target.Value) : default, a, options)).WhereNotNull().ToList();
Ejemplo n.º 21
0
        public async Task FormatElasticTrivia()
        {
            var expected    = @"extern alias A1;

#line 99

[assembly: My]

class My : System.Attribute
{
}

class A
{
}

[My]
class B
{
}";
            var compilation = SyntaxFactory.CompilationUnit(
                externs: SyntaxFactory.SingletonList <ExternAliasDirectiveSyntax>(
                    SyntaxFactory.ExternAliasDirective("A1")),
                usings: default(SyntaxList <UsingDirectiveSyntax>),
                attributeLists: SyntaxFactory.SingletonList <AttributeListSyntax>(
                    SyntaxFactory.AttributeList(
                        SyntaxFactory.Token(
                            SyntaxFactory.TriviaList(
                                SyntaxFactory.Trivia(
                                    SyntaxFactory.LineDirectiveTrivia(
                                        SyntaxFactory.Literal("99", 99), false))),
                            SyntaxKind.OpenBracketToken,
                            SyntaxFactory.TriviaList()),
                        SyntaxFactory.AttributeTargetSpecifier(
                            SyntaxFactory.Identifier("assembly")),
                        SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(
                            SyntaxFactory.Attribute(
                                SyntaxFactory.ParseName("My"))),
                        SyntaxFactory.Token(
                            SyntaxKind.CloseBracketToken))),
                members: SyntaxFactory.List <MemberDeclarationSyntax>(
                    new MemberDeclarationSyntax[]
            {
                SyntaxFactory.ClassDeclaration(
                    default(SyntaxList <AttributeListSyntax>),
                    SyntaxFactory.TokenList(),
                    SyntaxFactory.Identifier("My"),
                    null,
                    SyntaxFactory.BaseList(
                        SyntaxFactory.SingletonSeparatedList <BaseTypeSyntax>(
                            SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("System.Attribute")))),
                    default(SyntaxList <TypeParameterConstraintClauseSyntax>),
                    default(SyntaxList <MemberDeclarationSyntax>)),
                SyntaxFactory.ClassDeclaration("A"),
                SyntaxFactory.ClassDeclaration(
                    attributeLists: SyntaxFactory.SingletonList <AttributeListSyntax>(
                        SyntaxFactory.AttributeList(
                            SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(
                                SyntaxFactory.Attribute(
                                    SyntaxFactory.ParseName("My"))))),
                    modifiers: SyntaxFactory.TokenList(),
                    identifier: SyntaxFactory.Identifier("B"),
                    typeParameterList: null,
                    baseList: null,
                    constraintClauses: default(SyntaxList <TypeParameterConstraintClauseSyntax>),
                    members: default(SyntaxList <MemberDeclarationSyntax>))
            }));

            Assert.NotNull(compilation);

            var newCompilation = await Formatter.FormatAsync(compilation, new AdhocWorkspace());

            Assert.Equal(expected, newCompilation.ToFullString());
        }
Ejemplo n.º 22
0
 public static AttributeListSyntax MakeAssemblyAttribute(this AttributeListSyntax attr)
 => attr.WithTarget(SyntaxFactory.AttributeTargetSpecifier(
                        SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)));