Exemplo n.º 1
0
        public HxlCompilerResults Compile(HxlCompilerSettings settings,
                                          IEnumerable <HxlTemplate> templates)
        {
            using (CSharpCodeProvider provider = new CSharpCodeProvider()) {
                CompilerParameters options = new CompilerParameters();

                var      session     = new HxlCompilerSession(settings);
                string[] sourceFiles = templates.Select(t => GenerateSourceTempFile(session, t)).ToArray();

                // TODO Support generation of version in the output asm more easily
                // TODO Support private key signing in the output asm more easily
                if (string.IsNullOrEmpty(options.OutputAssembly))
                {
                    options.OutputAssembly = session.SessionID;
                }

                // TODO Previously, we indirectly supported other CodeDOM compiler parameters
                //   (embedded resources, etc.)
                settings.ImplicitAssemblyReferencePolicy.AddAssemblies(session.ImplicitAssemblyReferences);

                // TODO Only local paths are allowed
                options.ReferencedAssemblies.AddRange(settings.Assemblies.Select(t => t.Source.LocalPath).ToArray());
                options.IncludeDebugInformation = settings.Debug;

                var results = provider.CompileAssemblyFromFile(options, sourceFiles);
                return(new HxlCompilerResults(new HxlCompilerResultsAdapter(results)));
            }
        }
Exemplo n.º 2
0
        private int RunCore()
        {
            // TODO Validate options

            var collectedReferences = LoadReferences();
            var settings            = new HxlCompilerSettings();

            foreach (var reference in collectedReferences)
            {
                settings.Assemblies.AddNew(reference.Key, new Uri(reference.Value, UriKind.RelativeOrAbsolute));
            }
            // TODO Support output assembly name
            //   Path.GetFileNameWithoutExtension(Options.OutputFile);
            foreach (var kvp in Options.Namespaces)
            {
                settings.Namespaces.AddNew(kvp.Key, new Uri(kvp.Value));
            }

            var compiler  = HxlCompiler.Create(settings);
            var templates = new List <HxlTemplate>();

            foreach (var item in Options.Inputs.EnumerateFiles())
            {
                string file = item.File;
                _logger.ParsingTemplate(file);

                // TODO Get access to template builder another way
                var template = compiler.LoadTemplate(file);
                var builder  = (IHxlTemplateBuilder)template;

                var viewType = Options.BaseType
                               ?? TypeReference.Parse("Carbonfrost.Commons.Hxl.HxlViewTemplate");

                // TODO Drop this- should be using the type selector
                // TODO Allow type selector to be configurable
                builder.BaseClass = viewType;
                if (builder.ModelType == null)
                {
                    builder.BaseClass = viewType;
                }
                else
                {
                    string text = viewType.OriginalString + "<" + builder.ModelType + ">";
                    builder.BaseClass = TypeReference.Parse(text);
                }

                builder.TemplateName = PathHelper.UnixPath(PathHelper.MakeRelative(item.OriginalGlob, file));
                builder.ClassName    = CodeUtility.Slug(builder.TemplateName);
                templates.Add(template);
            }
            if (templates.Count == 0)
            {
                _logger.NoSourceFilesSpecified();
                return(1);
            }

            if (Options.NoCompile)
            {
                return(GenerateSource(compiler, templates));
            }
            else
            {
                return(CompileSource(compiler, templates));
            }
        }
Exemplo n.º 3
0
        protected void Load(string fixture)
        {
            var fixtureFileName = string.Format("Hxl/{0}.fixture", fixture);
            var myFixture       = TestContext.LoadFixture(fixtureFileName).Items[0];

            errors.Clear();

            this.FixtureName = GetType().Name + "-" + fixture;
            this.Source      = myFixture["input.hxl"];

            this.InputHtml = ParseHtml(Source);
            HxlCompilerSettings settings = new HxlCompilerSettings();

            settings.Namespaces.AddNew("test", new Uri("http://example.com/"));

            HxlCompiler c    = HxlCompiler.Create(settings);
            HxlTemplate temp = c.ParseTemplate(this.Source);

            // UNDONE Currently, f-spec is using the stream context API from shared instead of f-core,
            // so we have to copy the data over and hack the generated template names to support the
            // proper fixture data names.
            var templates = myFixture.Where(t => t.Key.EndsWith(".hxl", StringComparison.Ordinal))
                            .Select(t => {
                var tpl          = (ParsedTemplate)c.ParseTemplate(myFixture.GetStreamContext(t.Key).ReadAllText());
                string name      = WorkaroundTemplateName(fixtureFileName, t.Key);
                tpl.TemplateName = name;
                tpl.ClassName    = name;
                return(tpl);
            });
            var results = c.Compile(templates);

            this.Data = new Properties();
            if (myFixture["data.properties"] != null)
            {
                var props = Properties.FromStream(myFixture.GetStreamContext("data.properties").OpenRead());

                // So that we get some iterable content:
                // Use array syntax [a,b,c]
                foreach (var kvp in props)
                {
                    string parsedValue = Convert.ToString(kvp.Value);

                    if (parsedValue.Length > 0 && parsedValue[0] == '[')
                    {
                        var array = parsedValue.Substring(1, parsedValue.Length - 2).Split(',');
                        this.Data.SetProperty(kvp.Key, array);
                    }
                    else
                    {
                        this.Data.SetProperty(kvp.Key, parsedValue);
                    }
                }
            }

            var es = myFixture["output.cs"];

            if (es == null)
            {
                _expectedSource = null;
            }
            else
            {
                var    reader = new StringReader(es);
                var    lines  = new List <string>();
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    lines.Add(line);
                }
                _expectedSource = lines;
            }

            GeneratedSource       = c.GenerateSource(temp);
            OtherGeneratedSources = templates.Except(temp).ToDictionary(t => ((IHxlTemplateBuilder)t).TemplateName, t => c.GenerateSource(t));

            var allErrors = results.Errors.Where(t => !t.IsWarning);

            if (allErrors.Any())
            {
                WriteCompilerOutput(string.Empty, string.Empty);
                Assert.Fail("One or more compiler errors: {0}", allErrors.First());
            }

            Assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(
                results.PathToAssembly
                );

            ExpectedHtml   = myFixture["generated.html"];
            CompilerErrors = results.Errors;
        }
Exemplo n.º 4
0
 public AllowAllImpl(HxlCompilerSettings settings)
 {
     _settings = settings;
 }
Exemplo n.º 5
0
 public static IImplicitAssemblyReferencePolicy AllowAll(HxlCompilerSettings settings)
 {
     return(new AllowAllImpl(settings));
 }
Exemplo n.º 6
0
        public HxlCompilerResults Compile(HxlCompilerSettings settings,
                                          IEnumerable <HxlTemplate> templates)
        {
            var parseOptions = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp5);

            var session = new HxlCompilerSession(settings);

            string[] sourceFiles = templates.Select(t => GenerateSourceTempFile(session, t)).ToArray();

            // TODO Support generation of version in the output asm more easily
            // TODO Support private key signing in the output asm more easily
            string moduleName = "Hxl-" + session.SessionID;

            var emitOptions = new EmitOptions();

            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                moduleName,
                null,
                null,
                Empty <string> .List,
                settings.Debug ? OptimizationLevel.Debug : OptimizationLevel.Release,
                true,
                false,
                null,
                null,
                ImmutableArray <byte> .Empty,
                null,
                Platform.AnyCpu,
                ReportDiagnostic.Default,
                1,
                null,
                false,
                null,
                null,
                null,
                null,
                null
                );

            // TODO Previously, we indirectly supported other CodeDOM compiler parameters
            //   (embedded resources, etc.)
            settings.ImplicitAssemblyReferencePolicy.AddAssemblies(session.ImplicitAssemblyReferences);

            // TODO Only local paths are allowed
            var references = new List <MetadataReference>();

            references.AddRange(settings.Assemblies.Select(
                                    t => MetadataReference.CreateFromFile(t.Source.LocalPath,
                                                                          MetadataReferenceProperties.Assembly,
                                                                          null)).ToArray());

            var compilation = CSharpCompilation.Create(
                moduleName,
                GetParseTrees(parseOptions, sourceFiles),
                references,
                compilationOptions);
            var outputPath   = session.GetFileName(moduleName + ".dll");
            var outputStream = File.OpenWrite(outputPath);

            var results = compilation.Emit(outputStream,
                                           null,
                                           null,
                                           null,
                                           Empty <ResourceDescription> .List,
                                           emitOptions,
                                           CancellationToken.None);

            outputStream.Flush();
            outputStream.Dispose();

            return(new HxlCompilerResults(new HxlCompilerResultsAdapter(outputPath, results)));
        }