Ejemplo n.º 1
0
        private static async Task <Tuple <Compilation, SemanticModel, SyntaxTree, NamespaceDeclarationSyntaxInfo> > VerifyCompilation(Compilation compilation, NamespaceDeclarationSyntaxInfo namespaceNode)
        {
            SemanticModel semanticModel;
            var           tree = namespaceNode.Syntax.SyntaxTree;

            if (tree == null)
            {
                var compilationUnit = SyntaxFactory.CompilationUnit()
                                      .WithMembers(SyntaxFactory.List(new[] { (MemberDeclarationSyntax)namespaceNode.Syntax }));
                var cu   = CSharpSyntaxTree.Create(compilationUnit);
                var root = await cu.GetRootAsync().ConfigureAwait(false);

                namespaceNode.Syntax = root.ChildNodes().First();
                var newCompilation = compilation.AddSyntaxTrees(cu);
                semanticModel = newCompilation.GetSemanticModel(cu);
                return(new Tuple <Compilation, SemanticModel, SyntaxTree, NamespaceDeclarationSyntaxInfo>(newCompilation, semanticModel, cu, namespaceNode));
            }

            var result = AddToCompilation(compilation, tree);

            compilation   = result.Item1;
            tree          = result.Item2;
            semanticModel = compilation.GetSemanticModel(tree);
            return(new Tuple <Compilation, SemanticModel, SyntaxTree, NamespaceDeclarationSyntaxInfo>(compilation, semanticModel, tree, namespaceNode));
        }
Ejemplo n.º 2
0
        private static Tuple <Compilation, SyntaxTree> AddToCompilation(Compilation compilation, SyntaxTree tree)
        {
            if (!compilation.ContainsSyntaxTree(tree))
            {
                var newTree = tree;
                if (!tree.HasCompilationUnitRoot)
                {
                    var childNodes = tree.GetRoot()
                                     .ChildNodes()
                                     .AsArray();
                    newTree = CSharpSyntaxTree.Create(SyntaxFactory.CompilationUnit()
                                                      .WithMembers(
                                                          SyntaxFactory.List(childNodes.OfType <MemberDeclarationSyntax>()))
                                                      .WithUsings(
                                                          SyntaxFactory.List(childNodes.OfType <UsingDirectiveSyntax>()))
                                                      .WithExterns(
                                                          SyntaxFactory.List(childNodes.OfType <ExternAliasDirectiveSyntax>())));
                }

                var comp = compilation.AddSyntaxTrees(newTree);
                return(new Tuple <Compilation, SyntaxTree>(comp, newTree));
            }

            return(new Tuple <Compilation, SyntaxTree>(compilation, tree));
        }
Ejemplo n.º 3
0
        public void Run(CsAssembly csAssembly, string generatedCodeFolder)
        {
            if (string.IsNullOrEmpty(generatedCodeFolder))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(generatedCodeFolder));
            }

            var directoryToCreate = new HashSet <string>(StringComparer.CurrentCulture);

            // Remove the generated directory before creating it
            if (!directoryToCreate.Contains(generatedCodeFolder))
            {
                directoryToCreate.Add(generatedCodeFolder);
                if (Directory.Exists(generatedCodeFolder))
                {
                    foreach (var oldGeneratedFile in Directory.EnumerateFiles(generatedCodeFolder, "*.cs", SearchOption.AllDirectories))
                    {
                        try
                        {
                            File.Delete(oldGeneratedFile);
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
            }

            if (!Directory.Exists(generatedCodeFolder))
            {
                Directory.CreateDirectory(generatedCodeFolder);
            }

            logger.Message("Process Assembly => {0}", generatedCodeFolder);

            var trees = new[]
            {
                CreateTree("Enumerations", ns => ns.Enums, generators.Enum),
                CreateTree("Structures", ns => ns.Structs, generators.Struct),
                CreateTree("Functions", ns => ns.Classes, generators.Group),
                CreateTree("Interfaces", ns => ns.Interfaces, generators.Interface)
            };

            SyntaxTree CreateTree <T>(string fileName, Func <CsNamespace, IEnumerable <T> > membersFunc,
                                      IMultiCodeGenerator <T, MemberDeclarationSyntax> generator) where T : CsBase =>
            CSharpSyntaxTree.Create(
                GenerateCompilationUnit(
                    csAssembly.Namespaces.Select(
                        ns => GenerateNamespaceDeclaration(ns, membersFunc(ns), generator)
                        )
                    ),
                path : Path.Combine(generatedCodeFolder, $"{fileName}.cs")
                );

            foreach (var tree in trees)
            {
                File.WriteAllText(tree.FilePath, tree.GetCompilationUnitRoot().ToFullString());
            }
        }
Ejemplo n.º 4
0
        public static Assembly ToAssembly(CompilationUnitSyntax root, string asmName, string?outputFile, IReadOnlyCollection <MetadataReference> references, Func <Compilation, Compilation>?customConfig = null, CancellationToken cancellation = default)
        {
            string
                separator = $",{Environment.NewLine}",
                src       = root.NormalizeWhitespace(eol: Environment.NewLine).ToFullString(),
                refs      = string.Join(separator, references.Select(r => r.Display));

            Debug.WriteLine(src);
            Debug.WriteLine(refs);

            Compilation compilation = CSharpCompilation.Create
                                      (
                assemblyName: asmName,
                syntaxTrees: new []
            {
                CSharpSyntaxTree.Create
                (
                    root: root
                )
            },
                references: references,
                options: CompilationOptionsFactory.Create()
                                      );

            if (customConfig is not null)
            {
                compilation = customConfig(compilation);
            }

            using Stream stm = outputFile != null?File.Create(outputFile) : (Stream) new MemoryStream();

            EmitResult result = compilation.Emit(stm, cancellationToken: cancellation);

            Debug.WriteLine(string.Join(separator, result.Diagnostics));

            if (!result.Success)
            {
                string failures = string.Join(separator, result
                                              .Diagnostics
                                              .Where(d => d.Severity == DiagnosticSeverity.Error));

                #pragma warning disable CA2201 // To preserve backward compatibility, don't throw specific exception here
                var ex = new Exception(Resources.COMPILATION_FAILED);
                #pragma warning restore CA2201

                IDictionary extra = ex.Data;

                extra.Add(nameof(failures), failures);
                extra.Add(nameof(src), src);
                extra.Add(nameof(references), refs);

                throw ex;
            }

            stm.Seek(0, SeekOrigin.Begin);

            return(AssemblyLoadContext
                   .Default
                   .LoadFromStream(stm));
        }
Ejemplo n.º 5
0
        public Type Compile()
        {
            if (expressions.Count != 1)
            {
                throw new Exception("HAML node stack misaligned. Expected only 1 root node.");
            }
            FlushStringRun();
            _renderMethod = _renderMethod.AddBodyStatements(SyntaxFactory.Block(expressions.Peek()));

            _compilationTargetClass = _compilationTargetClass.AddMembers(_renderMethod);
            _compilationUnit        = _compilationUnit
                                      .AddMembers(_compilationTargetClass);
            _compilationUnit = _compilationUnit.NormalizeWhitespace("    ", true);
            _compilation     = _compilation.AddSyntaxTrees(CSharpSyntaxTree.Create(_compilationUnit));
            MemoryStream stream = new MemoryStream();
            EmitResult   result = _compilation.Emit(stream);

            _compilation.Emit("Output.dll");
            if (!result.Success)
            {
                throw new HamlCompilationFailedException(result.Diagnostics);
            }
            stream.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(stream);

            return(assembly.GetType(_compilationTargetClass.Identifier.Text));
        }
Ejemplo n.º 6
0
        /// <summary>
        ///     If diagnostics is enabled, this method writes
        /// </summary>
        /// <param name="target"></param>
        /// <param name="assemblyName"></param>
        /// <param name="syntaxTrees"></param>
        /// <param name="suffix"></param>
        /// <returns></returns>
        async Task WriteDiagnostics(MyApiTarget target, string assemblyName, IEnumerable <SyntaxTree> syntaxTrees, string suffix = null)
        {
            string outputPath;

            if (!GetDiagnosticsOutputPath(target, assemblyName, out outputPath))
            {
                return;
            }
            suffix = suffix ?? "";
            foreach (var syntaxTree in syntaxTrees)
            {
                var root = await syntaxTree.GetRootAsync().ConfigureAwait(false);

                var normalizedTree = CSharpSyntaxTree.Create((CSharpSyntaxNode)root.NormalizeWhitespace(), path: syntaxTree.FilePath);
                var fileName       = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(syntaxTree.FilePath) + suffix + Path.GetExtension(syntaxTree.FilePath));
                if (!fileName.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".cs";
                }
                using (var stream = MyFileSystem.OpenWrite(fileName))
                {
                    var writer = new StreamWriter(stream);
                    await writer.WriteAsync(normalizedTree.ToString()).ConfigureAwait(false);

                    await writer.FlushAsync().ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 7
0
        private static CSharpCompilation GenerateCode(string assemblyName, SourceText sourceText, string sourceCodePath,
                                                      bool isReleaseBuild)
        {
            var options    = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Default);
            var syntaxTree = CSharpSyntaxTree.ParseText(sourceText, options, path: sourceCodePath);

            var syntaxRootNode = syntaxTree.GetRoot() as CSharpSyntaxNode;
            var encoded        = CSharpSyntaxTree.Create(syntaxRootNode, null, sourceCodePath, Encoding.UTF8);

            var compilation = CSharpCompilation.Create(
                assemblyName,
                new[] { encoded },
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                .WithOptimizationLevel(isReleaseBuild ? OptimizationLevel.Release : OptimizationLevel.Debug)
                .WithPlatform(Platform.AnyCpu)
                .WithAllowUnsafe(true));

            var references   = new List <MetadataReference>();
            var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);

            foreach (var x in Directory.EnumerateFiles(assemblyPath, "*.dll"))
            {
                var fileName = Path.GetFileName(x);

                if (fileName.IndexOf("Native", StringComparison.Ordinal) == -1 &&
                    (fileName.StartsWith("System.") || fileName.StartsWith("Microsoft.")))
                {
                    references.Add(MetadataReference.CreateFromFile(x));
                }
            }

            compilation = compilation.AddReferences(references);

            return(compilation);
        }
Ejemplo n.º 8
0
        public void CreateTreeWithDiagnostics()
        {
            var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress));
            var tree    = CSharpSyntaxTree.Create(SyntaxFactory.ParseCompilationUnit(""), diagnosticOptions: options);

            Assert.Same(options, tree.DiagnosticOptions);
        }
Ejemplo n.º 9
0
        private Tuple <SyntaxTree[], List <EmbeddedText> > CreateSyntaxTree(string outputDir, string migrationName)
        {
            string[] sourceFilePaths = Directory.GetFiles(outputDir, "*.cs", SearchOption.TopDirectoryOnly);

            var encoding       = Encoding.UTF8;
            var syntaxTreeList = new List <SyntaxTree>();
            var embeddedTexts  = new List <EmbeddedText>();

            ///添加一个空类,防止首次生成返回null导致上下文转向查找当前运行程序集
            var emptyTypeText = "namespace _" + Guid.NewGuid().ToString("N") + "{class Class1{}}";

            syntaxTreeList.Add(CSharpSyntaxTree.ParseText(emptyTypeText));
            foreach (var path in sourceFilePaths)
            {
                var text       = File.ReadAllText(path);
                var syntaxTree = CSharpSyntaxTree.ParseText(
                    text,
                    new CSharpParseOptions(),
                    path: path);

                var syntaxRootNode = syntaxTree.GetRoot() as CSharpSyntaxNode;
                var encoded        = CSharpSyntaxTree.Create(syntaxRootNode, null, path, encoding);
                syntaxTreeList.Add(encoded);
                var buffer = encoding.GetBytes(text);
                embeddedTexts.Add(EmbeddedText.FromSource(path, SourceText.From(buffer, buffer.Length, encoding, canBeEmbedded: true)));
            }
            return(Tuple.Create(syntaxTreeList.ToArray(), embeddedTexts));
        }
Ejemplo n.º 10
0
 public IEnumerable <SyntaxTree> Generate()
 {
     yield return(CSharpSyntaxTree.Create(
                      SyntaxFactory.CompilationUnit()
                      .Enrich(_enrichers)
                      .NormalizeWhitespace()));
 }
Ejemplo n.º 11
0
            private SyntaxTree AddNames(SyntaxTree tree, Dictionary <string, MovedData> namespaceToMovedData)
            {
                TreeRewriterForAdding treeRewriter = new TreeRewriterForAdding(this, namespaceToMovedData);
                var newRoot = (CSharpSyntaxNode)treeRewriter.Visit(tree.GetRoot());

                return(CSharpSyntaxTree.Create(newRoot, null));
            }
Ejemplo n.º 12
0
        public static SyntaxTree CleanSyntaxTree(SyntaxTree tree, Dictionary <string, string> remaps, Dictionary <string, Dictionary <string, string> > enumAdditions, HashSet <string> enumsMakeFlags, Dictionary <string, string> requiredNamespaces, Dictionary <string, string> staticLibs, HashSet <string> nonEmptyStructs, HashSet <string> enumMemberNames, string filePath)
        {
            TreeRewriter treeRewriter = new TreeRewriter(remaps, enumAdditions, enumsMakeFlags, requiredNamespaces, staticLibs, nonEmptyStructs, enumMemberNames);
            var          newRoot      = (CSharpSyntaxNode)treeRewriter.Visit(tree.GetRoot());

            return(CSharpSyntaxTree.Create(newRoot, null, filePath));
        }
        internal string Convert(string input)
        {
            var syntaxTree = CSharpSyntaxTree.ParseText(input);

            var rootNode = CSharpSyntaxTree.Create(syntaxTree.GetRoot() as CSharpSyntaxNode).GetRoot();
            var classes  = rootNode.DescendantNodes().OfType <ClassDeclarationSyntax>();

            foreach (var c in classes)
            {
                var methods = c.Members.OfType <MethodDeclarationSyntax>();

                foreach (var m in methods)
                {
                    var attributeList = m.AttributeLists
                                        .FirstOrDefault(al => al.Attributes.Any(a => a.Name.ToString() == ExpectedExceptionConverter.exceptionName));

                    var attribute = attributeList.Attributes
                                    .FirstOrDefault(a => a.Name.ToString() == ExpectedExceptionConverter.exceptionName);

                    var exceptionName = GetExceptionName(attribute);

                    var oldBody = m.Body.AddStatements();

                    var invocationStatement = SyntaxFactory.ParseStatement($"Assert.Throws<{exceptionName}>(()=>{m.Body.ToFullString().TrimEnd(Environment.NewLine.ToCharArray())});");

                    var newMethod = m.WithAttributeLists(m.AttributeLists.Remove(attributeList))
                                    .WithBody(m.Body.WithStatements(new SyntaxList <StatementSyntax>()).AddStatements(invocationStatement));

                    rootNode = rootNode.ReplaceNode(m, newMethod);
                }
            }

            return(rootNode.NormalizeWhitespace().ToFullString());
        }
Ejemplo n.º 14
0
        private static Compilation MakeContractsClassFor(Project project, Compilation original, string interfacename, string filename, string parameters)
        {
            #region CodeContracts
            Contract.Requires(project != null);
            Contract.Requires(original != null);
            Contract.Requires(interfacename != null);
            Contract.Requires(filename != null);
            Contract.Ensures(Contract.Result <Compilation>() != null);
            #endregion CodeContracts

            var st   = original.SyntaxTrees.Where(x => x.FilePath.Equals(filename, StringComparison.OrdinalIgnoreCase)).First();
            var doc  = project.GetDocument(st);
            var sm   = original.GetSemanticModel(st);
            var node = st.GetRoot().DescendantNodes().Where(x => x.CSharpKind() == SyntaxKind.InterfaceDeclaration &&
                                                            sm.GetDeclaredSymbol(x).GetDocumentationCommentId().Equals(interfacename)).First() as InterfaceDeclarationSyntax;
            var        parent   = node.Parent;
            var        newclass = MakeContractsClassForNode(interfacename, parameters);
            var        mem      = newclass as MemberDeclarationSyntax;
            SyntaxNode newnode  = null;
            if (parent.CSharpKind() == SyntaxKind.ClassDeclaration)
            {
                var classdecl = parent as ClassDeclarationSyntax;
                var newdecl   = classdecl.AddMembers(mem);
                newnode = parent.Parent.ReplaceNode(parent, newdecl);
            }
            if (parent.CSharpKind() == SyntaxKind.NamespaceDeclaration)
            {
                var namedecl = parent as NamespaceDeclarationSyntax;
                var newdecl  = namedecl.AddMembers(mem);
                newnode = parent.Parent.ReplaceNode(parent, newdecl);
            }
            var newst = CSharpSyntaxTree.Create(newnode.SyntaxTree.GetRoot() as CSharpSyntaxNode, null, st.FilePath, null);
            return(original.ReplaceSyntaxTree(st, newst));
        }
Ejemplo n.º 15
0
        public ITestable Compile(AppDomain appDomain, CompilationUnitSyntax syntax)
        {
            string assemblyName = Guid.NewGuid().ToString();
            var    syntaxTree   = CSharpSyntaxTree.Create(syntax);
            var    compilation  = CSharpCompilation.Create(
                assemblyName,
                new[] { syntaxTree },
                _references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream()) {
                var compilationResult = compilation.Emit(ms);
                if (compilationResult.Success)
                {
                    TestClassProxy proxy = (TestClassProxy)appDomain.CreateInstanceAndUnwrap(
                        typeof(TestClassProxy).Assembly.FullName,
                        "PatternGuidedGP.Compiler.CSharp.TestClassProxy");
                    //TestClassProxy proxy = new TestClassProxy();
                    proxy.Initialize(ms.GetBuffer(), "ProblemClass", "Test");
                    return(proxy);
                }
                else
                {
                    // removed output because of compilation errors: division by constant 0

                    /*Logger.WriteLine(0, "Code does not compile:");
                     * Logger.WriteLine(0, syntax.NormalizeWhitespace().ToString());
                     * foreach (var error in compilationResult.Diagnostics) {
                     *      Logger.WriteLine(0, error.ToString());
                     * }*/
                }
                return(null);
            }
        }
        public void AddFile(string code, string filename)
        {
            var buffer = Encoding.UTF8.GetBytes(code);

            var path = filename;

            if (_options?.EmitFile == true)
            {
                var root = _options?.RootPath
                           ?? Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "GeneratedSources");
                Directory.CreateDirectory(root);
                path         = Path.Combine(root, filename);
                using var fs = new FileStream(path, FileMode.Create);
                fs.Write(buffer, 0, buffer.Length);
            }

            var sourceText = SourceText.From(buffer, buffer.Length, Encoding.UTF8, canBeEmbedded: true);

            var syntaxTree = CSharpSyntaxTree.ParseText(
                sourceText,
                new CSharpParseOptions(),
                path);

            var syntaxRootNode = syntaxTree.GetRoot() as CSharpSyntaxNode;
            var encoded        = CSharpSyntaxTree.Create(syntaxRootNode, null, path, Encoding.UTF8);

            _codes.Add(encoded);
        }
Ejemplo n.º 17
0
        private static async Task <Tuple <Compilation, SemanticModel, TypeDeclarationSyntaxInfo> > VerifyCompilation(Compilation compilation, TypeDeclarationSyntaxInfo typeNode)
        {
            var tree = typeNode.Syntax.SyntaxTree;

            if (tree == null)
            {
                var cu = CSharpSyntaxTree.Create(
                    SyntaxFactory
                    .CompilationUnit()
                    .WithMembers(SyntaxFactory.List(new[] { (MemberDeclarationSyntax)typeNode.Syntax })));
                var root = await cu.GetRootAsync().ConfigureAwait(false);

                typeNode.Syntax = (TypeDeclarationSyntax)root.ChildNodes().First();
                var newCompilation = compilation.AddSyntaxTrees(cu);
                var semanticModel  = newCompilation.GetSemanticModel(cu);
                return(new Tuple <Compilation, SemanticModel, TypeDeclarationSyntaxInfo>(newCompilation, semanticModel, typeNode));
            }

            var result     = AddToCompilation(compilation, tree);
            var childNodes = result.Item2.GetRoot().DescendantNodesAndSelf();

            typeNode.Syntax = childNodes.OfType <TypeDeclarationSyntax>().First();
            return(new Tuple <Compilation, SemanticModel, TypeDeclarationSyntaxInfo>(
                       result.Item1,
                       result.Item1.GetSemanticModel(result.Item2),
                       typeNode));
        }
Ejemplo n.º 18
0
        private SyntaxTree ParseCode(SourceText sourceText, string codePath)
        {
            var tree = CSharpSyntaxTree.ParseText(sourceText, ParseOptions, codePath);
            var root = tree.GetRoot();

            if (root is CompilationUnitSyntax c)
            {
                var members = c.Members;

                // add .Dump() to the last bare expression
                var lastMissingSemicolon = c.Members.OfType <GlobalStatementSyntax>()
                                           .LastOrDefault(m => m.Statement is ExpressionStatementSyntax expr && expr.SemicolonToken.IsMissing);
                if (lastMissingSemicolon != null)
                {
                    var statement = (ExpressionStatementSyntax)lastMissingSemicolon.Statement;

                    members = members.Replace(lastMissingSemicolon,
                                              SyntaxFactory.GlobalStatement(
                                                  SyntaxFactory.ExpressionStatement(
                                                      SyntaxFactory.InvocationExpression(
                                                          SyntaxFactory.MemberAccessExpression(
                                                              SyntaxKind.SimpleMemberAccessExpression,
                                                              statement.Expression,
                                                              SyntaxFactory.IdentifierName(nameof(ObjectExtensions.Dump)))))));
                }

                root = c.WithMembers(members);
            }

            var rootNode = root as CSharpSyntaxNode;

            return(CSharpSyntaxTree.Create(rootNode, ParseOptions, codePath, sourceText.Encoding));
            // return tree.WithRootAndOptions(root, _parseOptions);
        }
Ejemplo n.º 19
0
        /// <summary>
        ///     Creates a new rewritten syntax tree with instruction- and call chain depth counting.
        /// </summary>
        /// <returns></returns>
        public async Task <SyntaxTree> Rewrite()
        {
            var root = (CSharpSyntaxNode)await m_syntaxTree.GetRootAsync().ConfigureAwait(false);

            m_semanticModel = m_compilation.GetSemanticModel(m_syntaxTree);
            root            = (CSharpSyntaxNode)Visit(root);
            return(CSharpSyntaxTree.Create(root, path: m_syntaxTree.FilePath));
        }
Ejemplo n.º 20
0
        SyntaxTree CreateTree(SyntaxNode root)
        {
            var options = new CSharpParseOptions(
                documentationMode: DocumentationMode.None,
                kind: SourceCodeKind.Script);

            return(CSharpSyntaxTree.Create((CompilationUnitSyntax)root, options, tree.FilePath, Encoding.UTF8));
        }
Ejemplo n.º 21
0
        internal static CodeAnalysis.SyntaxTree GenerateAssemblyMetadata(IEnumerable <MetadataReference> references)
        {
            var aliases = references
                          .Select(reference => reference.Properties.Aliases.FirstOrDefault(alias => alias.StartsWith(DotnetCoreDll.ReferenceAlias))) // FIXME: improve...
                          .Where(alias => alias != null);
            var typeName =
                QualifiedName(
                    AliasQualifiedName(
                        IdentifierName(Token(SyntaxKind.GlobalKeyword)),
                        IdentifierName("System")),
                    IdentifierName("Type"));
            var metadataTypeNodes =
                aliases.Select(alias =>
                               TypeOfExpression(
                                   QualifiedName(
                                       AliasQualifiedName(IdentifierName(alias), IdentifierName(DotnetCoreDll.MetadataNamespace)),
                                       IdentifierName(DotnetCoreDll.MetadataType))));
            var dependenciesInitializer =
                ArrayCreationExpression(
                    ArrayType(typeName).WithOmittedRankSpecifiers())
                .WithInitializer(
                    InitializerExpression(
                        SyntaxKind.ArrayInitializerExpression,
                        SeparatedList <ExpressionSyntax>(metadataTypeNodes)));
            var metadataField =
                FieldDeclaration(
                    VariableDeclaration(
                        ArrayType(typeName).WithOmittedRankSpecifiers())
                    .WithVariables(
                        SingletonSeparatedList(
                            VariableDeclarator(Identifier(DotnetCoreDll.Dependencies))
                            .WithInitializer(
                                EqualsValueClause(dependenciesInitializer)))))
                .WithModifiers(
                    TokenList(
                        Token(SyntaxKind.PublicKeyword),
                        Token(SyntaxKind.StaticKeyword),
                        Token(SyntaxKind.ReadOnlyKeyword)));
            var classDef =
                ClassDeclaration(DotnetCoreDll.MetadataType)
                .WithModifiers(
                    TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)))
                .WithMembers(
                    SingletonList <MemberDeclarationSyntax>(metadataField));
            var namespaceDef =
                NamespaceDeclaration(IdentifierName(DotnetCoreDll.MetadataNamespace))
                .WithMembers(
                    SingletonList <MemberDeclarationSyntax>(classDef));

            var compilation =
                CompilationUnit()
                .WithExterns(
                    List(aliases.Select(Identifier).Select(ExternAliasDirective)))
                .WithMembers(
                    SingletonList <MemberDeclarationSyntax>(namespaceDef));

            return(CSharpSyntaxTree.Create(compilation));
        }
Ejemplo n.º 22
0
        protected override void Implementation(CodeFileCSharp input, Parameters inputParameters, IMetadataRecorder metadataRecorder, ILogger logger)
        {
            AttributeAdder serializableAttributeAdder = new AttributeAdder(inputParameters.PropertiesToDecorate);
            var            newRoot = serializableAttributeAdder.Visit(input.SyntaxTree.GetRoot());

            var outFile = this.Outputs[OutStreamName].CreateCodeFile(input.Name) as CodeFileCSharp;

            outFile.SyntaxTree = CSharpSyntaxTree.Create(newRoot as CSharpSyntaxNode);
        }
Ejemplo n.º 23
0
        private void GenerateCallToBaseConstructor(ref CSharpCompilation compilation, INamedTypeSymbol classSymbol)
        {
            var rewriter = new CallBaseConstructorRewriter(classSymbol, classSymbol.BaseType);

            var original  = compilation.SyntaxTrees[0];
            var rewritten = CSharpSyntaxTree.Create((CSharpSyntaxNode)rewriter.Visit(original.GetRoot()));

            compilation = compilation.ReplaceSyntaxTree(original, rewritten);
        }
Ejemplo n.º 24
0
        public void WithFilePath_Null()
        {
            SyntaxTree oldTree = new CSharpSyntaxTree.DummySyntaxTree();

            Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath);
            oldTree = SyntaxFactory.ParseSyntaxTree("", path: "old.cs");
            Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath);
            Assert.Equal(string.Empty, SyntaxFactory.ParseSyntaxTree("", path: null).FilePath);
            Assert.Equal(string.Empty, CSharpSyntaxTree.Create((CSharpSyntaxNode)oldTree.GetRoot(), path: null).FilePath);
        }
Ejemplo n.º 25
0
        private SyntaxTree RunTransformations(SyntaxTree tree, SemanticModel semanticModel)
        {
            SyntaxNode root;

            tree.TryGetRoot(out root);

            var cu = (CompilationUnitSyntax)((CompilationUnitSyntax)root).Accept(new ValueTypeToLocalVariableVisitor(semanticModel));

            return(CSharpSyntaxTree.Create(cu));
        }
        public async Task BasicTest()
        {
            using var dbManager = new DbManager(new DbManagerTest(), new SqlConnection("Initial Catalog=TestDatabase;"), new GenTablesOptions(ConnectionType.MsSql, "fake", "Tab", "", "MyTables", verbosity: Verbosity.Quite));

            var tables = await dbManager.SelectTables();

            Assert.AreEqual(2, tables.Count);

            var tableMap = tables.ToDictionary(t => t.DbName);

            IReadOnlyDictionary <TableRef, ClassDeclarationSyntax> existingCode = new Dictionary <TableRef, ClassDeclarationSyntax>();

            var generator =
                new TableClassGenerator(tableMap, "MyCompany.MyProject.Tables", existingCode);


            var trees = tables.Select(t => CSharpSyntaxTree.Create(generator.Generate(t, out _))).ToList();

            var compilation = CSharpCompilation.Create("Tables", trees, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            compilation = compilation.AddReferences(
                MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location),
                MetadataReference.CreateFromFile(typeof(object).Assembly.GetAssemblyLocation()),
                MetadataReference.CreateFromFile(Assembly.Load("System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").Location),
                MetadataReference.CreateFromFile(typeof(SqQueryBuilder).Assembly.GetAssemblyLocation()));

            MemoryStream ms = new MemoryStream();

            var emitResult = compilation.Emit(ms);

            if (!emitResult.Success)
            {
                Assert.Fail(emitResult.Diagnostics.FirstOrDefault()?.GetMessage());
            }

            var assembly = Assembly.Load(ms.ToArray());

            var allTypes = assembly.GetTypes();

            var table1 = (TableBase)Activator.CreateInstance(allTypes.Find(t => t.Name == tables[0].Name));

            Assert.NotNull(table1);
            var table2 = (TableBase)Activator.CreateInstance(allTypes.Find(t => t.Name == tables[1].Name));

            Assert.NotNull(table2);


            string table1ExpectedSql = "CREATE TABLE [dbo].[TableZ]([Id] int NOT NULL  IDENTITY (1, 1) DEFAULT (0),[ValueA] [nvarchar](255) NOT NULL DEFAULT (''),[Value_A] decimal(2,6),CONSTRAINT [PK_dbo_TableZ] PRIMARY KEY ([Id]));";

            Assert.AreEqual(table1ExpectedSql, TSqlExporter.Default.ToSql(table1.Script.Create()));

            string table2ExpectedSql = "CREATE TABLE [dbo].[TableA]([Id] int NOT NULL  IDENTITY (1, 1) DEFAULT (0),[Value] datetime NOT NULL DEFAULT (GETUTCDATE()),CONSTRAINT [PK_dbo_TableA] PRIMARY KEY ([Id]),CONSTRAINT [FK_dbo__TableA_to_dbo__TableZ] FOREIGN KEY ([Id]) REFERENCES [dbo].[TableZ]([Id]),INDEX [IX_dbo_TableA_Value_DESC] UNIQUE([Value] DESC));";

            Assert.AreEqual(table2ExpectedSql, TSqlExporter.Default.ToSql(table2.Script.Create()));
        }
        /// <summary>
        /// Rewrites a syntax tree using the specified rewriter.
        /// </summary>
        private static CSharpSyntaxTree RewriteSyntaxTree(CSharpSyntaxTree tree, SemanticModel semanticModel, Func <SemanticModel, CSharpSyntaxRewriter> rewriter)
        {
            var rewrittenRoot = rewriter(semanticModel).Visit(tree.GetRoot());

            if (rewrittenRoot != tree.GetRoot())
            {
                return((CSharpSyntaxTree)CSharpSyntaxTree.Create((CSharpSyntaxNode)rewrittenRoot, tree.Options, tree.FilePath, tree.Encoding));
            }

            return(tree);
        }
Ejemplo n.º 28
0
 public static void CloneContent(CodeFileCSharp source, CodeFileCSharp target, IMetadataRecorder metadataRecorder, Dictionary <string, string> metadataTags = null, object metadataObject = null)
 {
     if (source.SyntaxTree != null)
     {
         var sourceRoot = (CSharpSyntaxNode)source.SyntaxTree.GetRoot();
         var targetTree = CSharpSyntaxTree.Create(sourceRoot);
         var targetRoot = targetTree.GetRoot();
         target.SyntaxTree = targetTree;
         metadataRecorder.SymbolSourcingFrom(source.NodePathService, sourceRoot, target.NodePathService, targetRoot, metadataTags ?? new Dictionary <string, string>(), metadataObject);
     }
 }
Ejemplo n.º 29
0
        public static string ConvertStatement(string java)
        {
            var statement       = JavaParser.parseStatement(java);
            var options         = new JavaConversionOptions();
            var context         = new ConversionContext(options);
            var statementSyntax = StatementVisitor.VisitStatement(context, statement);

            var tree = CSharpSyntaxTree.Create(statementSyntax);

            return(tree.GetText().ToString());
        }
Ejemplo n.º 30
0
        private static string ConvertStatement(string java)
        {
            var declaration             = JavaParser.parseBodyDeclaration(java);
            var options                 = new JavaConversionOptions();
            var context                 = new ConversionContext(options);
            var arrayCreationExpression = (ArrayCreationExpr)((Node)((MethodDeclaration)declaration.getChildrenNodes().get(1)).getBody().getStmts().get(0)).getChildrenNodes().get(0);
            var expressionSyntax        = ExpressionVisitor.VisitExpression(context, arrayCreationExpression).NormalizeWhitespace();

            var tree = CSharpSyntaxTree.Create(expressionSyntax);

            return(tree.GetText().ToString());
        }