Example #1
0
 internal static string DeclarationToString(ITypeDeclaration declaration)
 {
     try
     {
         StringWriter    sw = new StringWriter();
         ILanguageWriter lw = new CSharpWriter() as ILanguageWriter;
         SourceNode      sn = lw.GenerateSource(declaration);
         LanguageWriter.WriteSourceNode(sw, sn);
         sw.Close();
         string s = sw.ToString();
         return(s);
     }
     catch (Exception ex)
     {
         return("[ERROR WRITING DECLARATION: " + ex.Message + "]"); // +ist;
     }
 }
Example #2
0
        public static object ProcessQueryClass(InferenceEngine engine, Type type, MethodInfo singleQuery)
        {
            var typeDecl        = RoslynDeclarationProvider.GetTypeDeclaration(type, false);
            var queryTransform  = new QueryTransform(engine, singleQuery);
            var compiledQueries = queryTransform.Transform(typeDecl);

            bool showCode = false;

            if (showCode)
            {
                var sw = new StringWriter();
                var lw = new CSharpWriter();
                var sn = lw.GenerateSource(compiledQueries);
                LanguageWriter.WriteSourceNode(sw, sn);
                var sourceCode = sw.ToString();
            }

            return(engine.Compiler.CompileWithoutParams <object>(new[] { compiledQueries }.ToList()));
        }
Example #3
0
        /// <summary>
        /// Compiles a type declaration and returns its generated code.
        /// </summary>
        /// <param name="td">A type declaration.</param>
        /// <returns>The code generated for the specified type declaration.</returns>
        private dynamic CompileTypeDeclaration(ITypeDeclaration td)
        {
            // Get the source code
            StringWriter    sw = new StringWriter();
            ILanguageWriter lw = new CSharpWriter() as ILanguageWriter;
            SourceNode      sn = lw.GenerateSource(td);

            LanguageWriter.WriteSourceNode(sw, sn);
            String sourceCode = sw.ToString();

            // Compile the code

            // Delete duplicates
            var allAssemblies = AppDomain.CurrentDomain.GetAssemblies().GroupBy(x => x.FullName).Select(x => x.First());

            var cc = new CodeCompiler();

            cc.includeDebugInformation = true;
            cc.generateInMemory        = true;
            cc.writeSourceFiles        = false;
            cc.compilerChoice          = CompilerChoice.Auto;
            CompilerResults cr = cc.Compile(null, new List <string>()
            {
                sourceCode
            }, allAssemblies.ToArray());

            foreach (string err in cr.Errors)
            {
                Console.WriteLine(err);
            }

            // There should be no errors
            Assert.Empty(cr.Errors);

            // Now get the generated code
            Type    inferenceType = CodeCompiler.GetCompiledType(cr, td);
            dynamic gen           = Activator.CreateInstance(inferenceType);

            return(gen);
        }
Example #4
0
        public List <string> WriteSource(List <ITypeDeclaration> typeDeclarations, IList <string> filenames, out ICollection <Assembly> referencedAssemblies)
        {
            Stopwatch watch = null;

            if (showProgress)
            {
                watch = new Stopwatch();
                watch.Start();
            }
            List <string> sources       = new List <string>();
            bool          needFilenames = (!this.generateInMemory) || this.writeSourceFiles;

            if (needFilenames)
            {
                string dirname = Path.GetFullPath(GeneratedSourceFolder);
                Directory.CreateDirectory(dirname);
            }
            referencedAssemblies = new Set <Assembly>();
            foreach (ITypeDeclaration td in typeDeclarations)
            {
                StringWriter    sw = new StringWriter();
                ILanguageWriter lw = new CSharpWriter() as ILanguageWriter;
                SourceNode      sn = lw.GenerateSource(td);
                LanguageWriter.WriteSourceNode(sw, sn);
                referencedAssemblies.AddRange(lw.ReferencedAssemblies);
                String sourceCode = sw.ToString();
                sources.Add(sourceCode);
                if (needFilenames)
                {
                    string filename = Path.GetFullPath(GetFilenameForType(GeneratedSourceFolder, td, ".cs"));
                    filenames.Add(filename);
                    if (writeSourceFiles)
                    {
                        if (useExistingFiles && File.Exists(filename))
                        {
                            if (showProgress)
                            {
                                Console.Write("Using existing source file: {0} ", filename);
                            }
                        }
                        else
                        {
                            if (showProgress)
                            {
                                Console.Write("Writing source file: {0} ", filename);
                            }
                            StreamWriter stw = new StreamWriter(filename);
                            stw.Write(sourceCode);
                            stw.Close();
                        }
                    }
                }
            }
            // sometimes we need to reference assemblies that are not directly referenced in the code,
            // as explained at: http://msdn.microsoft.com/en-us/library/yabyz3h4.aspx
            // If you reference an assembly (Assembly A) that references another assembly (Assembly B), you will need to reference Assembly B if:
            //   1. A type you use from Assembly A inherits from a type or implements an interface from Assembly B.
            //   2. You invoke a field, property, event, or method that has a return type or parameter type from Assembly B.
            // Rather than check for all this, we add references to all loaded assemblies referenced by referenced assemblies.
            Set <AssemblyName> loadedAssemblies = new Set <AssemblyName>(new AssemblyNameComparer());

            loadedAssemblies.AddRange(AppDomain.CurrentDomain.GetAssemblies().ListSelect(assembly => assembly.GetName()));
            Stack <Assembly> assemblyStack = new Stack <Assembly>();

            foreach (Assembly assembly in referencedAssemblies)
            {
                assemblyStack.Push(assembly);
            }
            while (assemblyStack.Count != 0)
            {
                Assembly assembly = assemblyStack.Pop();
                foreach (AssemblyName name in assembly.GetReferencedAssemblies())
                {
                    if (loadedAssemblies.Contains(name))
                    {
                        Assembly referenced = Assembly.Load(name);
                        if (!referencedAssemblies.Contains(referenced))
                        {
                            referencedAssemblies.Add(referenced);
                            assemblyStack.Push(referenced);
                        }
                    }
                }
            }
            if (showProgress)
            {
                watch.Stop();
                Console.WriteLine("({0}ms)", watch.ElapsedMilliseconds);
            }
            return(sources);
        }
Example #5
0
        public List <ITypeDeclaration> TransformToDeclaration(ITypeDeclaration itd, AttributeRegistry <object, ICompilerAttribute> inputAttributes, bool trackTransform, bool showProgress,
                                                              out List <TransformError> warnings, bool catchExceptions = false, bool treatWarningsAsErrors = false)
        {
            List <ITypeDeclaration> res = new List <ITypeDeclaration>();

            res.Add(itd);
            AttributeRegistry <object, ICompilerAttribute> attributes = inputAttributes;

            warnings = new List <TransformError>();
            foreach (CodeTransformer ct in transformers)
            {
                string    name  = ct.Transform.Name;
                Stopwatch watch = null;
                if (showProgress)
                {
                    Console.Write(name + " ");
                    watch = Stopwatch.StartNew();
                }
                ct.Transform.Context.InputAttributes = attributes;
                ct.TrackTransform = trackTransform;
                if (catchExceptions)
                {
                    try
                    {
                        res = ct.TransformToDeclaration(res[0]);
                    }
                    catch (Exception ex)
                    {
                        ((BasicTransformContext)ct.Transform.Context).Error("Uncaught exception in transform", ex);
                    }
                }
                else
                {
                    res = ct.TransformToDeclaration(res[0]);
                }
                if (showProgress)
                {
                    watch.Stop();
                    Console.WriteLine("({0}ms)", watch.ElapsedMilliseconds);
                }
#if TestLanguageWriter
                try
                {
                    ILanguageWriter lw = new CSharpWriter() as ILanguageWriter;
                    lw.GenerateSource(res[0]);
                }
                catch
                {
                    Console.WriteLine("Language writer error for " + res[0].Name);
                }
#endif
                TransformResults tr = ct.Transform.Context.Results;
                tr.ThrowIfErrors(name + " failed", treatWarningsAsErrors);
                if (tr.WarningCount > 0)
                {
                    foreach (TransformError te in tr.errorsAndWarnings)
                    {
                        if (te.IsWarning)
                        {
                            warnings.Add(te);
                        }
                    }
                }
                attributes = ct.Transform.Context.OutputAttributes;
            }
            return(res);
        }