public void Should_Return_Collection_of_Output_Lines()
        {
            var outputFormatter = new OutputFormatter();

            var formattedOutput = outputFormatter.Format(_generatedPrimes);

            Assert.That(formattedOutput, Is.Not.Empty);
        }
        public void Should_Contains_Count_For_Every_Tenth_Line()
        {
            var generatedPrimes = new PrimeGenerator(new PrimeEvaluationEngine()).GeneratePrimesUpTo(2000);

            var outputFormatter = new OutputFormatter();

            var formattedOutput = outputFormatter.Format(generatedPrimes);

            for (var i = 10; i < formattedOutput.Count; i += 11)
            {
                Assert.That(formattedOutput[i].Contains("Count:"));
            }
        }
        public void Should_Have_No_More_Than_Five_Items_For_Each_Output_Line()
        {
            var outputFormatter = new OutputFormatter();

            var formattedOutput = outputFormatter.Format(_generatedPrimes);

            string[] splitPrimes;

            foreach (var item in formattedOutput)
            {
                splitPrimes = item.Split(",".ToCharArray());

                Assert.That(splitPrimes.Length, Is.LessThanOrEqualTo(5));
            }
        }
        public bool Compile(CompilerOptions options)
        {
            string intermediateAssemblyFile = Path.GetTempFileName(), intermediateDocFile = Path.GetTempFileName();
            var    actualOut = Console.Out;
            var    er = new ErrorReporterWrapper(_errorReporter, actualOut);

            try {
                Console.SetOut(new StringWriter());                     // I don't trust the third-party libs to not generate spurious random messages, so make sure that any of those messages are suppressed.

                // Compile the assembly
                var settings = MapSettings(options, intermediateAssemblyFile, intermediateDocFile, er);
                if (er.HasErrors)
                {
                    return(false);
                }

                if (!options.AlreadyCompiled)
                {
                    // Compile the assembly
                    var ctx = new CompilerContext(settings, new ConvertingReportPrinter(er));
                    var d   = new Mono.CSharp.Driver(ctx);
                    d.Compile();
                    if (er.HasErrors)
                    {
                        return(false);
                    }
                }

                var references = LoadReferences(settings.AssemblyReferences, er);
                if (references == null)
                {
                    return(false);
                }

                PreparedCompilation compilation = PreparedCompilation.CreateCompilation(options.SourceFiles.Select(f => new SimpleSourceFile(f, settings.Encoding)), references.Select(r => r.Item1), options.DefineConstants);

                IMethod entryPoint = FindEntryPoint(options, er, compilation);

                var container = new WindsorContainer();
                foreach (var plugin in TopologicalSortPlugins(references).Reverse())
                {
                    RegisterPlugin(container, plugin);
                }

                // Compile the script
                container.Register(Component.For <IErrorReporter>().Instance(er),
                                   Component.For <CompilerOptions>().Instance(options),
                                   Component.For <ICompilation>().Instance(compilation.Compilation),
                                   Component.For <ICompiler>().ImplementedBy <Compiler.Compiler>()
                                   );

                container.Resolve <IMetadataImporter>().Prepare(compilation.Compilation.GetAllTypeDefinitions());

                var compiledTypes = container.Resolve <ICompiler>().Compile(compilation);

                foreach (var rewriter in container.ResolveAll <IJSTypeSystemRewriter>())
                {
                    compiledTypes = rewriter.Rewrite(compiledTypes);
                }

                var js = container.Resolve <IOOPEmulator>().Process(compiledTypes, entryPoint);
                js = container.Resolve <ILinker>().Process(js);

                if (er.HasErrors)
                {
                    return(false);
                }

                string outputAssemblyPath = !string.IsNullOrEmpty(options.OutputAssemblyPath) ? options.OutputAssemblyPath : Path.ChangeExtension(options.SourceFiles[0], ".dll");
                string outputScriptPath   = !string.IsNullOrEmpty(options.OutputScriptPath)   ? options.OutputScriptPath   : Path.ChangeExtension(options.SourceFiles[0], ".js");

                if (!options.AlreadyCompiled)
                {
                    try {
                        File.Copy(intermediateAssemblyFile, outputAssemblyPath, true);
                    }
                    catch (IOException ex) {
                        er.Region = DomRegion.Empty;
                        er.Message(Messages._7950, ex.Message);
                        return(false);
                    }
                    if (!string.IsNullOrEmpty(options.DocumentationFile))
                    {
                        try {
                            File.Copy(intermediateDocFile, options.DocumentationFile, true);
                        }
                        catch (IOException ex) {
                            er.Region = DomRegion.Empty;
                            er.Message(Messages._7952, ex.Message);
                            return(false);
                        }
                    }
                }

                if (options.MinimizeScript)
                {
                    js = ((JsBlockStatement)Minifier.Process(JsStatement.Block(js))).Statements;
                }

                string script = string.Join("", js.Select(s => options.MinimizeScript ? OutputFormatter.FormatMinified(s) : OutputFormatter.Format(s)));
                try {
                    File.WriteAllText(outputScriptPath, script, settings.Encoding);
                }
                catch (IOException ex) {
                    er.Region = DomRegion.Empty;
                    er.Message(Messages._7951, ex.Message);
                    return(false);
                }
                return(true);
            }
            catch (Exception ex) {
                er.Region = DomRegion.Empty;
                er.InternalError(ex.ToString());
                return(false);
            }
            finally {
                if (!options.AlreadyCompiled)
                {
                    try { File.Delete(intermediateAssemblyFile); } catch {}
                    try { File.Delete(intermediateDocFile); } catch {}
                }
                if (actualOut != null)
                {
                    Console.SetOut(actualOut);
                }
            }
        }
Example #5
0
        private void AssertCorrect(JsStatement stmt, string expected)
        {
            var actual = OutputFormatter.Format(stmt);

            Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n")));
        }
Example #6
0
        private void AssertCorrect(JsExpression expr, string expected)
        {
            var actual = OutputFormatter.Format(expr);

            Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n")));
        }
        public void YieldReturnStatement()
        {
            var stmt = ParseStatement <JsYieldStatement>("yield return a;");

            Assert.That(OutputFormatter.Format(stmt.Value), Is.EqualTo("a"));
        }
        public void ThrowStatement()
        {
            var stmt = ParseStatement <JsThrowStatement>("throw x;");

            Assert.That(OutputFormatter.Format(stmt.Expression), Is.EqualTo("x"));
        }
        private void RoundtripStatement(string source, string expected = null)
        {
            var stmt = JavaScriptParser.Parser.ParseStatement(source);

            Assert.That(OutputFormatter.Format(stmt).Replace("\r\n", "\n"), Is.EqualTo((expected ?? source).Replace("\r\n", "\n")));
        }
Example #10
0
 public string DebugToString()
 {
     return(new Regex("\\s+").Replace(OutputFormatter.Format(this, true), " "));
 }
        public JsExpression Lift(JsExpression expression)
        {
            if (expression is JsInvocationExpression)
            {
                var ie = (JsInvocationExpression)expression;
                if (ie.Method is JsMemberAccessExpression)
                {
                    var mae = (JsMemberAccessExpression)ie.Method;
                    if (mae.Target is JsTypeReferenceExpression)
                    {
                        var  t             = ((JsTypeReferenceExpression)mae.Target).Type;
                        bool isIntegerType = t.IsKnownType(KnownTypeCode.Byte) || t.IsKnownType(KnownTypeCode.SByte) || t.IsKnownType(KnownTypeCode.Int16) || t.IsKnownType(KnownTypeCode.UInt16) || t.IsKnownType(KnownTypeCode.Char) || t.IsKnownType(KnownTypeCode.Int32) || t.IsKnownType(KnownTypeCode.UInt32) || t.IsKnownType(KnownTypeCode.Int64) || t.IsKnownType(KnownTypeCode.UInt64);
                        if (isIntegerType)
                        {
                            if (mae.MemberName == "div" || mae.MemberName == "trunc")
                            {
                                return(expression);
                            }
                        }
                    }
                }
            }
            if (expression is JsUnaryExpression)
            {
                string methodName = null;
                switch (expression.NodeType)
                {
                case ExpressionNodeType.LogicalNot: methodName = "not"; goto default;

                case ExpressionNodeType.Negate:     methodName = "neg"; goto default;

                case ExpressionNodeType.Positive:   methodName = "pos"; goto default;

                case ExpressionNodeType.BitwiseNot: methodName = "cpl"; goto default;

                default:
                    if (methodName != null)
                    {
                        return(JsExpression.Invocation(JsExpression.Member(_createTypeReferenceExpression(KnownTypeReference.NullableOfT), methodName), ((JsUnaryExpression)expression).Operand));
                    }
                    break;
                }
            }
            else if (expression is JsBinaryExpression)
            {
                string methodName = null;
                switch (expression.NodeType)
                {
                case ExpressionNodeType.Equal:
                case ExpressionNodeType.Same:
                    methodName = "eq";
                    goto default;

                case ExpressionNodeType.NotEqual:
                case ExpressionNodeType.NotSame:
                    methodName = "ne";
                    goto default;

                case ExpressionNodeType.LesserOrEqual:      methodName = "le";   goto default;

                case ExpressionNodeType.GreaterOrEqual:     methodName = "ge";   goto default;

                case ExpressionNodeType.Lesser:             methodName = "lt";   goto default;

                case ExpressionNodeType.Greater:            methodName = "gt";   goto default;

                case ExpressionNodeType.Subtract:           methodName = "sub";  goto default;

                case ExpressionNodeType.Add:                methodName = "add";  goto default;

                case ExpressionNodeType.Modulo:             methodName = "mod";  goto default;

                case ExpressionNodeType.Divide:             methodName = "div";  goto default;

                case ExpressionNodeType.Multiply:           methodName = "mul";  goto default;

                case ExpressionNodeType.BitwiseAnd:         methodName = "band"; goto default;

                case ExpressionNodeType.BitwiseOr:          methodName = "bor";  goto default;

                case ExpressionNodeType.BitwiseXor:         methodName = "xor";  goto default;

                case ExpressionNodeType.LeftShift:          methodName = "shl";  goto default;

                case ExpressionNodeType.RightShiftSigned:   methodName = "srs";  goto default;

                case ExpressionNodeType.RightShiftUnsigned: methodName = "sru";  goto default;

                default:
                    if (methodName != null)
                    {
                        return(JsExpression.Invocation(JsExpression.Member(_createTypeReferenceExpression(KnownTypeReference.NullableOfT), methodName), ((JsBinaryExpression)expression).Left, ((JsBinaryExpression)expression).Right));
                    }
                    break;
                }
            }

            throw new ArgumentException("Cannot lift expression " + OutputFormatter.Format(expression, true));
        }
Example #12
0
            public bool Compile(CompilerOptions options, ErrorReporterWrapper er)
            {
                string intermediateAssemblyFile = Path.GetTempFileName(), intermediateDocFile = Path.GetTempFileName();

                try {
                    // Compile the assembly
                    var settings = MapSettings(options, intermediateAssemblyFile, intermediateDocFile, er);
                    if (er.HasErrors)
                    {
                        return(false);
                    }

                    if (!options.AlreadyCompiled)
                    {
                        // Compile the assembly
                        var ctx = new CompilerContext(settings, new ConvertingReportPrinter(er));
                        var d   = new Mono.CSharp.Driver(ctx);
                        d.Compile();
                        if (er.HasErrors)
                        {
                            return(false);
                        }
                    }

                    // Compile the script
                    var md = new MetadataImporter.ScriptSharpMetadataImporter(options.MinimizeScript);
                    var n  = new DefaultNamer();
                    PreparedCompilation compilation = null;
                    var rtl      = new ScriptSharpRuntimeLibrary(md, er, n.GetTypeParameterName, tr => new JsTypeReferenceExpression(tr.Resolve(compilation.Compilation).GetDefinition()));
                    var compiler = new Compiler.Compiler(md, n, rtl, er, allowUserDefinedStructs: options.References.Count == 0 /* We allow user-defined structs in mscorlib only, which can be identified by the fact that it has no references*/);

                    var references = LoadReferences(settings.AssemblyReferences, er);
                    if (references == null)
                    {
                        return(false);
                    }

                    compilation = compiler.CreateCompilation(options.SourceFiles.Select(f => new SimpleSourceFile(f, settings.Encoding)), references, options.DefineConstants);
                    var compiledTypes = compiler.Compile(compilation);

                    IMethod entryPoint = null;
                    if (options.HasEntryPoint)
                    {
                        List <IMethod> candidates;
                        if (!string.IsNullOrEmpty(options.EntryPointClass))
                        {
                            var t = compilation.Compilation.MainAssembly.GetTypeDefinition(new FullTypeName(options.EntryPointClass));
                            if (t == null)
                            {
                                er.Region = DomRegion.Empty;
                                er.Message(7950, "Could not find the entry point class " + options.EntryPointClass + ".");
                                return(false);
                            }
                            candidates = t.Methods.Where(IsEntryPointCandidate).ToList();
                        }
                        else
                        {
                            candidates = compilation.Compilation.MainAssembly.GetAllTypeDefinitions().SelectMany(t => t.Methods).Where(IsEntryPointCandidate).ToList();
                        }
                        if (candidates.Count != 1)
                        {
                            er.Region = DomRegion.Empty;
                            er.Message(7950, "Could not find a unique entry point.");
                            return(false);
                        }
                        entryPoint = candidates[0];
                    }

                    var js = new ScriptSharpOOPEmulator(compilation.Compilation, md, rtl, n, er).Process(compiledTypes, compilation.Compilation, entryPoint);
                    js = new DefaultLinker(md, n).Process(js, compilation.Compilation.MainAssembly);

                    if (er.HasErrors)
                    {
                        return(false);
                    }

                    string outputAssemblyPath = !string.IsNullOrEmpty(options.OutputAssemblyPath) ? options.OutputAssemblyPath : Path.ChangeExtension(options.SourceFiles[0], ".dll");
                    string outputScriptPath   = !string.IsNullOrEmpty(options.OutputScriptPath)   ? options.OutputScriptPath   : Path.ChangeExtension(options.SourceFiles[0], ".js");

                    if (!options.AlreadyCompiled)
                    {
                        try {
                            File.Copy(intermediateAssemblyFile, outputAssemblyPath, true);
                        }
                        catch (IOException ex) {
                            er.Region = DomRegion.Empty;
                            er.Message(7950, ex.Message);
                            return(false);
                        }
                        if (!string.IsNullOrEmpty(options.DocumentationFile))
                        {
                            try {
                                File.Copy(intermediateDocFile, options.DocumentationFile, true);
                            }
                            catch (IOException ex) {
                                er.Region = DomRegion.Empty;
                                er.Message(7952, ex.Message);
                                return(false);
                            }
                        }
                    }

                    if (options.MinimizeScript)
                    {
                        js = ((JsBlockStatement)Minifier.Process(new JsBlockStatement(js))).Statements;
                    }

                    string script = string.Join("", js.Select(s => options.MinimizeScript ? OutputFormatter.FormatMinified(s) : OutputFormatter.Format(s)));
                    try {
                        File.WriteAllText(outputScriptPath, script, settings.Encoding);
                    }
                    catch (IOException ex) {
                        er.Region = DomRegion.Empty;
                        er.Message(7951, ex.Message);
                        return(false);
                    }
                    return(true);
                }
                catch (Exception ex) {
                    er.Region = DomRegion.Empty;
                    er.InternalError(ex.ToString());
                    return(false);
                }
                finally {
                    if (!options.AlreadyCompiled)
                    {
                        try { File.Delete(intermediateAssemblyFile); } catch {}
                        try { File.Delete(intermediateDocFile); } catch {}
                    }
                }
            }
 private string DebugToString()
 {
     return(OutputFormatter.Format(this, allowIntermediates: true));
 }
        protected void AssertCorrect(JsExpression expr, string expected)
        {
            var actual = OutputFormatter.Format(expr, allowIntermediates: true);

            Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n")));
        }
        private void RoundtripExpression(string source, string expected = null)
        {
            var expr = JavaScriptParser.Parser.ParseExpression(source);

            Assert.That(OutputFormatter.Format(expr).Replace("\r\n", "\n"), Is.EqualTo((expected ?? source).Replace("\r\n", "\n")));
        }
 protected string Stringify(JsExpression expression)
 {
     return(OutputFormatter.Format(expression, allowIntermediates: true));
 }
            public bool Compile(CompilerOptions options, ErrorReporterWrapper er)
            {
                string intermediateAssemblyFile = Path.GetTempFileName(), intermediateDocFile = Path.GetTempFileName();

                try {
                    // Compile the assembly
                    var settings = MapSettings(options, intermediateAssemblyFile, intermediateDocFile, er);
                    if (er.HasErrors)
                    {
                        return(false);
                    }

                    if (!options.AlreadyCompiled)
                    {
                        // Compile the assembly
                        var ctx = new CompilerContext(settings, new ConvertingReportPrinter(er));
                        var d   = new Mono.CSharp.Driver(ctx);
                        d.Compile();
                        if (er.HasErrors)
                        {
                            return(false);
                        }
                    }

                    // Compile the script
                    var md = new MetadataImporter.ScriptSharpMetadataImporter(options.MinimizeScript);
                    var n  = new DefaultNamer();
                    PreparedCompilation compilation = null;
                    var rtl      = new ScriptSharpRuntimeLibrary(md, er, n.GetTypeParameterName, tr => { var t = tr.Resolve(compilation.Compilation).GetDefinition(); return(new JsTypeReferenceExpression(t.ParentAssembly, md.GetTypeSemantics(t).Name)); });
                    var compiler = new Compiler.Compiler(md, n, rtl, er, allowUserDefinedStructs: options.References.Count == 0 /* We allow user-defined structs in mscorlib only, which can be identified by the fact that it has no references*/);

                    var references = LoadReferences(settings.AssemblyReferences, er);
                    if (references == null)
                    {
                        return(false);
                    }

                    compilation = compiler.CreateCompilation(options.SourceFiles.Select(f => new SimpleSourceFile(f, settings.Encoding)), references, options.DefineConstants);
                    var compiledTypes = compiler.Compile(compilation);

                    var js = new ScriptSharpOOPEmulator(compilation.Compilation, md, rtl, er).Rewrite(compiledTypes, compilation.Compilation);
                    js = new GlobalNamespaceReferenceImporter().ImportReferences(js);

                    if (er.HasErrors)
                    {
                        return(false);
                    }

                    string outputAssemblyPath = !string.IsNullOrEmpty(options.OutputAssemblyPath) ? options.OutputAssemblyPath : Path.ChangeExtension(options.SourceFiles[0], ".dll");
                    string outputScriptPath   = !string.IsNullOrEmpty(options.OutputScriptPath)   ? options.OutputScriptPath   : Path.ChangeExtension(options.SourceFiles[0], ".js");

                    if (!options.AlreadyCompiled)
                    {
                        try {
                            File.Copy(intermediateAssemblyFile, outputAssemblyPath, true);
                        }
                        catch (IOException ex) {
                            er.Region = DomRegion.Empty;
                            er.Message(7950, ex.Message);
                            return(false);
                        }
                        if (!string.IsNullOrEmpty(options.DocumentationFile))
                        {
                            try {
                                File.Copy(intermediateDocFile, options.DocumentationFile, true);
                            }
                            catch (IOException ex) {
                                er.Region = DomRegion.Empty;
                                er.Message(7952, ex.Message);
                                return(false);
                            }
                        }
                    }

                    string script = string.Join("", js.Select(s => options.MinimizeScript ? OutputFormatter.FormatMinified(Minifier.Process(s)) : OutputFormatter.Format(s)));
                    try {
                        File.WriteAllText(outputScriptPath, script, settings.Encoding);
                    }
                    catch (IOException ex) {
                        er.Region = DomRegion.Empty;
                        er.Message(7951, ex.Message);
                        return(false);
                    }
                    return(true);
                }
                catch (Exception ex) {
                    er.Region = DomRegion.Empty;
                    er.InternalError(ex.ToString());
                    return(false);
                }
                finally {
                    if (!options.AlreadyCompiled)
                    {
                        try { File.Delete(intermediateAssemblyFile); } catch {}
                        try { File.Delete(intermediateDocFile); } catch {}
                    }
                }
            }