Ejemplo n.º 1
0
        CompileResult CompileImpl(string lessSource, IFile file)
        {
            currentFiles.Push(file);

            var parser = (ObjectInstance)ScriptEngine.Evaluate("(new window.less.Parser)");
            var callback = new CompileResult(ScriptEngine);
            try
            {
                parser.CallMemberFunction("parse", lessSource, callback);
            }
            catch (JavaScriptException ex)
            {
                var message = ((ObjectInstance)ex.ErrorObject).GetPropertyValue("message").ToString();
                throw new LessCompileException(
                    string.Format(
                        "Less compile error in {0}:\r\n{1}",
                        file.FullPath,
                        message
                    )
                );
            }
            catch (InvalidOperationException ex)
            {
                throw new LessCompileException(
                    string.Format("Less compile error in {0}.", file.FullPath),
                    ex
                );
            }

            currentFiles.Pop();
            return callback;
        }
Ejemplo n.º 2
0
 void AddRawFileReferenceForEachImportedFile(IAsset asset, CompileResult compileResult)
 {
     foreach (var importedFilePath in compileResult.ImportedFilePaths)
     {
         asset.AddRawFileReference(importedFilePath);
     }
 }
Ejemplo n.º 3
0
        internal static CompileResult Compile(RenderStream stream)
        {
            CompileResult rs = new CompileResult();
            rs.Success = true;

            return rs;
        }
Ejemplo n.º 4
0
        private CompileResult CompileExpr(Expression expr, List <object> queryArgs)
        {
            if (expr == null)
            {
                throw new NotSupportedException("Expression is NULL");
            }

            if (expr is BinaryExpression)
            {
                var bin = (BinaryExpression)expr;

                CompileResult leftr  = CompileExpr(bin.Left, queryArgs);
                CompileResult rightr = CompileExpr(bin.Right, queryArgs);

                //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null")
                string text;
                if (leftr.CommandText == "?" && leftr.Value == null)
                {
                    text = CompileNullBinaryExpression(bin, rightr);
                }
                else if (rightr.CommandText == "?" && rightr.Value == null)
                {
                    text = CompileNullBinaryExpression(bin, leftr);
                }
                else
                {
                    text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")";
                }
                return(new CompileResult {
                    CommandText = text
                });
            }
            else if (expr.NodeType == ExpressionType.Call)
            {
                var call = (MethodCallExpression)expr;
                var args = new CompileResult[call.Arguments.Count];
                var obj  = call.Object != null?CompileExpr(call.Object, queryArgs) : null;

                string methodName = call.Method.Name;
                string sqlCall    = string.Empty;

                for (int i = 0; i < args.Length; i++)
                {
                    args[i] = CompileExpr(call.Arguments[i], queryArgs);
                }

                if (methodName == "Contains")
                {
                    if (args.Length == 1)
                    {
                        // string.Contains("xxx") or list.Contains(x)
                        if (call.Object != null && call.Object.Type == typeof(string))
                        {
                            sqlCall = "({0} like ('%' || {1} || '%'))";
                        }
                        else
                        {
                            sqlCall = "({1} in {0})";
                        }

                        sqlCall = string.Format(sqlCall, obj.CommandText, args[0].CommandText);
                    }
                    else if (args.Length == 2)
                    {
                        sqlCall = string.Format("({0} in {1})", args[1].CommandText, args[0].CommandText);
                    }
                }
                else if (methodName == "StartsWith" || methodName == "EndsWith")
                {
                    if (args.Length == 1)
                    {
                        if (methodName == "StartsWith")
                        {
                            sqlCall = "({0} like ({1} || '%'))";
                        }
                        else if (methodName == "EndsWith")
                        {
                            sqlCall = "({0} like ('%' || {1}))";
                        }

                        sqlCall = string.Format(sqlCall, obj.CommandText, args[0].CommandText);
                    }
                }
                else if (methodName == "Matches" && args.Length == 2)
                {
                    sqlCall = "({0} match {1})";
                    sqlCall = string.Format(sqlCall, args[0].CommandText, args[1].CommandText);
                }
                else if (call.Method.Name == "Equals" && args.Length == 1)
                {
                    sqlCall = "({0} = ({1}))";
                    sqlCall = string.Format(sqlCall, obj.CommandText, args[0].CommandText);
                }
                else
                {
                    var arguments = string.Join(",", args.Select(a => a.CommandText).ToArray());
                    sqlCall = string.Format("{0}({1})", methodName.ToLower(), arguments);
                }

                return(new CompileResult {
                    CommandText = sqlCall
                });
            }
            else if (expr.NodeType == ExpressionType.Constant)
            {
                var c = (ConstantExpression)expr;
                queryArgs.Add(c.Value);
                return(new CompileResult
                {
                    CommandText = "?",
                    Value = c.Value
                });
            }
            else if (expr.NodeType == ExpressionType.Convert)
            {
                var           u    = (UnaryExpression)expr;
                Type          ty   = u.Type;
                CompileResult valr = CompileExpr(u.Operand, queryArgs);

                var underlyingType = Nullable.GetUnderlyingType(ty);
                if (underlyingType != null)
                {
                    ty = underlyingType;
                }

                return(new CompileResult
                {
                    CommandText = valr.CommandText,
                    Value = valr.Value != null?Convert.ChangeType(valr.Value, ty, null) : null
                });
            }
            else if (expr.NodeType == ExpressionType.MemberAccess)
            {
                var mem = (MemberExpression)expr;

                if (mem.Expression.NodeType == ExpressionType.Parameter)
                {
                    //
                    // This is a column of our table, output just the column name
                    //
                    return(new CompileResult {
                        CommandText = "\"" + OrmHelper.GetColumnName(mem.Member) + "\""
                    });
                }
                else
                {
                    object obj = null;
                    if (mem.Expression != null)
                    {
                        CompileResult r = CompileExpr(mem.Expression, queryArgs);
                        if (r.Value == null)
                        {
                            throw new NotSupportedException("Member access failed to compile expression");
                        }
                        if (r.CommandText == "?")
                        {
                            queryArgs.RemoveAt(queryArgs.Count - 1);
                        }
                        obj = r.Value;
                    }

                    var val = this.Session.GetExpressionMemberValue(expr, mem, obj);

                    //
                    // Work special magic for enumerables
                    //
                    if (val != null && val is IEnumerable && !(val is string))
                    {
                        var sb = new StringBuilder();
                        sb.Append("(");
                        string head = "";
                        foreach (object a in (IEnumerable)val)
                        {
                            queryArgs.Add(a);
                            sb.Append(head);
                            sb.Append("?");
                            head = ",";
                        }
                        sb.Append(")");
                        return(new CompileResult
                        {
                            CommandText = sb.ToString(),
                            Value = val
                        });
                    }
                    else
                    {
                        queryArgs.Add(val);
                        return(new CompileResult
                        {
                            CommandText = "?",
                            Value = val
                        });
                    }
                }
            }
            throw new NotSupportedException("Cannot compile: " + expr.NodeType.ToString());
        }
Ejemplo n.º 5
0
        public override LinkResult Link(IConsole console, IStandardProject superProject, IStandardProject project,
                                        CompileResult assemblies, string outputPath)
        {
            var settings = GetSettings(superProject);
            var result   = new LinkResult();

            var startInfo = new ProcessStartInfo();

            startInfo.FileName = Path.Combine(BaseDirectory, "arm-none-eabi-gcc" + Platform.ExecutableExtension);

            if (project.Type == ProjectType.StaticLibrary)
            {
                startInfo.FileName = Path.Combine(BaseDirectory, "arm-none-eabi-ar" + Platform.ExecutableExtension);
            }

            startInfo.WorkingDirectory = project.Solution.CurrentDirectory;

            if (!System.IO.File.Exists(startInfo.FileName))
            {
                result.ExitCode = -1;
                console.WriteLine("Unable to find linker executable (" + startInfo.FileName + ") Check project compiler settings.");
                return(result);
            }

            var objectArguments = string.Empty;

            foreach (var obj in assemblies.ObjectLocations)
            {
                objectArguments += obj + " ";
            }

            var libs = string.Empty;

            foreach (var lib in assemblies.LibraryLocations)
            {
                libs += lib + " ";
            }

            var outputDir = Path.GetDirectoryName(outputPath);

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

            var outputName = Path.GetFileNameWithoutExtension(outputPath) + ExecutableExtension;

            if (project.Type == ProjectType.StaticLibrary)
            {
                outputName = Path.GetFileNameWithoutExtension(outputPath) + StaticLibraryExtension;
            }
            else
            {
                GenerateLinkerScript(superProject);
            }

            var executable = Path.Combine(outputDir, outputName);

            var linkedLibraries = string.Empty;

            foreach (var libraryPath in project.StaticLibraries)
            {
                var relativePath = Path.GetDirectoryName(libraryPath);

                var libName = Path.GetFileNameWithoutExtension(libraryPath).Substring(3);

                linkedLibraries += string.Format("-L\"{0}\" -l{1} ", relativePath, libName);
            }

            foreach (var lib in project.BuiltinLibraries)
            {
                linkedLibraries += string.Format("-l{0} ", lib);
            }


            // TODO linked libraries won't make it in on nano... Please fix -L directory placement in compile string.
            switch (settings.LinkSettings.Library)
            {
            case LibraryType.NanoCLib:
                linkedLibraries += "-lm -lc_nano -lsupc++_nano -lstdc++_nano ";
                break;

            case LibraryType.BaseCLib:
                linkedLibraries += "-lm -lc -lstdc++ -lsupc++ ";
                break;

            case LibraryType.SemiHosting:
                linkedLibraries += "-lm -lgcc -lc -lrdimon ";
                break;

            case LibraryType.Retarget:
                linkedLibraries += "-lm -lc -lnosys -lstdc++ -lsupc++ ";
                break;
            }

            // Hide console window
            startInfo.UseShellExecute        = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError  = true;
            startInfo.RedirectStandardInput  = true;
            startInfo.CreateNoWindow         = true;

            if (project.Type == ProjectType.StaticLibrary)
            {
                startInfo.Arguments = string.Format("rvs {0} {1}", executable, objectArguments);
            }
            else
            {
                startInfo.Arguments = string.Format("{0} -o{1} {2} -Wl,--start-group {3} {4} -Wl,--end-group",
                                                    GetLinkerArguments(project), executable, objectArguments, linkedLibraries, libs);
            }

            //console.WriteLine(Path.GetFileNameWithoutExtension(startInfo.FileName) + " " + startInfo.Arguments);
            //console.WriteLine ("[LL] - " + startInfo.Arguments);

            using (var process = Process.Start(startInfo))
            {
                process.OutputDataReceived += (sender, e) =>
                {
                    //console.WriteLine(e.Data);
                };

                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data != null && !e.Data.Contains("creating"))
                    {
                        console.WriteLine(e.Data);
                    }
                };

                process.BeginOutputReadLine();

                process.BeginErrorReadLine();

                process.WaitForExit();

                result.ExitCode = process.ExitCode;

                if (result.ExitCode == 0)
                {
                    result.Executable = executable;
                }
            }

            return(result);
        }
Ejemplo n.º 6
0
        internal static CompileResult Compile(Project project, string logFile)
        {
            ProjectCollection.GlobalProjectCollection.UnregisterAllLoggers();
            ProjectCollection.GlobalProjectCollection.UnloadAllProjects();

            Configuration = Settings.Instance.DeveloperMode ? "Debug" : "Release";
            OutputPath    = "bin\\" + Configuration;

            project.SetProperty("Configuration", Configuration);
            project.SetProperty("PlatformTarget", PlatformTarget);
            project.SetProperty("OutputPath", OutputPath);

            //C# 6.0 support
            SetLatestBuildTools(project);

            foreach (var item in project.GetItems("Reference"))
            {
                if (item == null)
                {
                    continue;
                }

                var path = item.GetMetadata("HintPath");

                if (path != null && !string.IsNullOrWhiteSpace(path.EvaluatedValue))
                {
                    var fileName = Path.GetFileName(path.EvaluatedValue);

                    if (fileName.EndsWith(".dll"))
                    {
                        if (CrackedAddonsList.Any(name => fileName.IndexOf(name, StringComparison.CurrentCultureIgnoreCase) > -1))
                        {
                            return(Compile(project, logFile));
                        }
                        var files   = Directory.GetFiles(ReferencesDirectory, "*", SearchOption.AllDirectories);
                        var refPath =
                            Path.GetDirectoryName(
                                files.FirstOrDefault(
                                    f => string.Equals(Path.GetFileName(f), fileName, StringComparison.CurrentCultureIgnoreCase)) ??
                                ReferencesDirectory);

                        item.SetMetadataValue("HintPath", Path.Combine(refPath, fileName));
                    }
                }
            }

            var targetFramework = project.GetProperty("TargetFrameworkVersion").EvaluatedValue;

            switch (targetFramework)
            {
            case "v4.5.1":
                project.SetProperty("TargetFrameworkVersion", "v4.5");
                break;

            case "v4.5.2":
                project.SetProperty("TargetFrameworkVersion", "v4.5");
                break;

            case "v4.6":
                break;
            }

            project.SetGlobalProperty("PreBuildEvent", string.Empty);
            project.SetGlobalProperty("PostBuildEvent", string.Empty);
            project.SetGlobalProperty("PreLinkEvent", string.Empty);

            var fileLogger = new FileLogger {
                Parameters = @"logfile=" + logFile, ShowSummary = true
            };

            ProjectCollection.GlobalProjectCollection.RegisterLogger(fileLogger);
            ProjectCollection.GlobalProjectCollection.LoadedProjects.Add(project);

            var result = project.Build();

            ProjectCollection.GlobalProjectCollection.UnregisterAllLoggers();
            var compileResult = new CompileResult(project, result, logFile);

            ProjectCollection.GlobalProjectCollection.UnloadAllProjects();

            return(compileResult);
        }
Ejemplo n.º 7
0
		CompileResult Compile(string output, string code, out Assembly generatedAssembly)
		{
			var inMemory = string.IsNullOrEmpty(output);
			var parameters = new CompilerParameters
			{
				GenerateInMemory = inMemory,
				TreatWarningsAsErrors = false,
				GenerateExecutable = false,
				OutputAssembly = inMemory ? null : output
			};

			if (EtoEnvironment.Platform.IsMac)
			{
				// hack for OS X el capitan. mcs moved from /usr/bin to /usr/local/bin and is not on the path when XS is running
				// this should be removed when mono/XS is fixed.
				var path = Environment.GetEnvironmentVariable("PATH");
				var paths = path.Split(':');
				if (!paths.Contains("/usr/local/bin", StringComparer.Ordinal))
				{
					path += ":/usr/local/bin";
					Environment.SetEnvironmentVariable("PATH", path);
				}
			}

			SetParameters(parameters);

			var codeProvider = CreateCodeProvider();
			var results = codeProvider.CompileAssemblyFromSource(parameters, code);

			var errors = results.Errors.Cast<CompilerError>().ToList();
			var result = new CompileResult { Errors = errors };
			if (errors.Count == 0 || errors.All(r => r.IsWarning))
			{
				if (inMemory)
					generatedAssembly = results.CompiledAssembly;
				else
					generatedAssembly = null;
				result.Success = true;
			}
			else
			{
				generatedAssembly = null;
				errors.ForEach(msg => Debug.WriteLine(msg.ToString()));
			}
			return result;
		}
Ejemplo n.º 8
0
        private CompileResult CompileExpr(Expression expr, List <object> queryArgs)
        {
            if (expr == null)
            {
                throw new NotSupportedException("Expression is NULL");
            }
            else if (expr is BinaryExpression)
            {
                var bin = (BinaryExpression)expr;

                // VB turns 'x=="foo"' into 'CompareString(x,"foo",true/false)==0', so we need to unwrap it
                // http://blogs.msdn.com/b/vbteam/archive/2007/09/18/vb-expression-trees-string-comparisons.aspx
                if (bin.Left.NodeType == ExpressionType.Call)
                {
                    var call = (MethodCallExpression)bin.Left;
                    if (call.Method.DeclaringType.FullName == "Microsoft.VisualBasic.CompilerServices.Operators" &&
                        call.Method.Name == "CompareString")
                    {
                        bin = Expression.MakeBinary(bin.NodeType, call.Arguments[0], call.Arguments[1]);
                    }
                }


                var leftr  = CompileExpr(bin.Left, queryArgs);
                var rightr = CompileExpr(bin.Right, queryArgs);

                //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null")
                string text;
                if (leftr.CommandText == "?" && leftr.Value == null)
                {
                    text = CompileNullBinaryExpression(bin, rightr);
                }
                else if (rightr.CommandText == "?" && rightr.Value == null)
                {
                    text = CompileNullBinaryExpression(bin, leftr);
                }
                else
                {
                    text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")";
                }
                return(new CompileResult {
                    CommandText = text
                });
            }
            else if (expr.NodeType == ExpressionType.Not)
            {
                var    operandExpr = ((UnaryExpression)expr).Operand;
                var    opr         = CompileExpr(operandExpr, queryArgs);
                object val         = opr.Value;
                if (val is bool)
                {
                    val = !((bool)val);
                }
                return(new CompileResult {
                    CommandText = "NOT(" + opr.CommandText + ")",
                    Value = val
                });
            }
            else if (expr.NodeType == ExpressionType.Call)
            {
                var call = (MethodCallExpression)expr;
                var args = new CompileResult[call.Arguments.Count];
                var obj  = call.Object != null?CompileExpr(call.Object, queryArgs) : null;

                for (var i = 0; i < args.Length; i++)
                {
                    args[i] = CompileExpr(call.Arguments[i], queryArgs);
                }

                var sqlCall = "";

                if (call.Method.Name == "Like" && args.Length == 2)
                {
                    sqlCall = "(" + args[0].CommandText + " like " + args[1].CommandText + ")";
                }
                else if (call.Method.Name == "Contains" && args.Length == 2)
                {
                    sqlCall = "(" + args[1].CommandText + " in " + args[0].CommandText + ")";
                }
                else if (call.Method.Name == "Contains" && args.Length == 1)
                {
                    if (call.Object != null && call.Object.Type == typeof(string))
                    {
                        sqlCall = "( instr(" + obj.CommandText + "," + args[0].CommandText + ") >0 )";
                    }
                    else
                    {
                        sqlCall = "(" + args[0].CommandText + " in " + obj.CommandText + ")";
                    }
                }
                else if (call.Method.Name == "StartsWith" && args.Length >= 1)
                {
                    var startsWithCmpOp = StringComparison.CurrentCulture;
                    if (args.Length == 2)
                    {
                        startsWithCmpOp = (StringComparison)args[1].Value;
                    }
                    switch (startsWithCmpOp)
                    {
                    case StringComparison.Ordinal:
                    case StringComparison.CurrentCulture:
                        sqlCall = "( substr(" + obj.CommandText + ", 1, " + args[0].Value.ToString().Length + ") =  " + args[0].CommandText + ")";
                        break;

                    case StringComparison.OrdinalIgnoreCase:
                    case StringComparison.CurrentCultureIgnoreCase:
                        sqlCall = "(" + obj.CommandText + " like (" + args[0].CommandText + " || '%'))";
                        break;
                    }
                }
                else if (call.Method.Name == "EndsWith" && args.Length >= 1)
                {
                    var endsWithCmpOp = StringComparison.CurrentCulture;
                    if (args.Length == 2)
                    {
                        endsWithCmpOp = (StringComparison)args[1].Value;
                    }
                    switch (endsWithCmpOp)
                    {
                    case StringComparison.Ordinal:
                    case StringComparison.CurrentCulture:
                        sqlCall = "( substr(" + obj.CommandText + ", length(" + obj.CommandText + ") - " + args[0].Value.ToString().Length + "+1, " + args[0].Value.ToString().Length + ") =  " + args[0].CommandText + ")";
                        break;

                    case StringComparison.OrdinalIgnoreCase:
                    case StringComparison.CurrentCultureIgnoreCase:
                        sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + "))";
                        break;
                    }
                }
                else if (call.Method.Name == "Equals" && args.Length == 1)
                {
                    sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))";
                }
                else if (call.Method.Name == "ToLower")
                {
                    sqlCall = "(lower(" + obj.CommandText + "))";
                }
                else if (call.Method.Name == "ToUpper")
                {
                    sqlCall = "(upper(" + obj.CommandText + "))";
                }
                else if (call.Method.Name == "Replace" && args.Length == 2)
                {
                    sqlCall = "(replace(" + obj.CommandText + "," + args[0].CommandText + "," + args[1].CommandText + "))";
                }
                else
                {
                    sqlCall = call.Method.Name.ToLower() + "(" + string.Join(",", args.Select(a => a.CommandText).ToArray()) + ")";
                }
                return(new CompileResult {
                    CommandText = sqlCall
                });
            }
            else if (expr.NodeType == ExpressionType.Constant)
            {
                var c = (ConstantExpression)expr;
                queryArgs.Add(c.Value);
                return(new CompileResult {
                    CommandText = "?",
                    Value = c.Value
                });
            }
            else if (expr.NodeType == ExpressionType.Convert)
            {
                var u    = (UnaryExpression)expr;
                var ty   = u.Type;
                var valr = CompileExpr(u.Operand, queryArgs);
                return(new CompileResult {
                    CommandText = valr.CommandText,
                    Value = valr.Value != null?ConvertTo(valr.Value, ty) : null
                });
            }
            else if (expr.NodeType == ExpressionType.MemberAccess)
            {
                var mem = (MemberExpression)expr;

                var paramExpr = mem.Expression as ParameterExpression;
                if (paramExpr == null)
                {
                    var convert = mem.Expression as UnaryExpression;
                    if (convert != null && convert.NodeType == ExpressionType.Convert)
                    {
                        paramExpr = convert.Operand as ParameterExpression;
                    }
                }

                if (paramExpr != null)
                {
                    //
                    // This is a column of our table, output just the column name
                    // Need to translate it if that column name is mapped
                    //
                    var columnName = Table.FindColumnWithPropertyName(mem.Member.Name).Name;
                    return(new CompileResult {
                        CommandText = "\"" + columnName + "\""
                    });
                }
                else
                {
                    object obj = null;
                    if (mem.Expression != null)
                    {
                        var r = CompileExpr(mem.Expression, queryArgs);
                        if (r.Value == null)
                        {
                            throw new NotSupportedException("Member access failed to compile expression");
                        }
                        if (r.CommandText == "?")
                        {
                            queryArgs.RemoveAt(queryArgs.Count - 1);
                        }
                        obj = r.Value;
                    }

                    //
                    // Get the member value
                    //
                    object val = null;

                    if (mem.Member is PropertyInfo)
                    {
                        var m = (PropertyInfo)mem.Member;
                        val = m.GetValue(obj, null);
                    }
                    else if (mem.Member is FieldInfo)
                    {
                        var m = (FieldInfo)mem.Member;
                        val = m.GetValue(obj);
                    }
                    else
                    {
                        throw new NotSupportedException("MemberExpr: " + mem.Member.GetType());
                    }

                    //
                    // Work special magic for enumerables
                    //
                    if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable <byte>))
                    {
                        var sb = new System.Text.StringBuilder();
                        sb.Append("(");
                        var head = "";
                        foreach (var a in (System.Collections.IEnumerable)val)
                        {
                            queryArgs.Add(a);
                            sb.Append(head);
                            sb.Append("?");
                            head = ",";
                        }
                        sb.Append(")");
                        return(new CompileResult {
                            CommandText = sb.ToString(),
                            Value = val
                        });
                    }
                    else
                    {
                        queryArgs.Add(val);
                        return(new CompileResult {
                            CommandText = "?",
                            Value = val
                        });
                    }
                }
            }
            throw new NotSupportedException("Cannot compile: " + expr.NodeType.ToString());
        }
Ejemplo n.º 9
0
        public override CompileResult Compile(IConsole console, IStandardProject superProject, IStandardProject project,
                                              ISourceFile file, string outputFile)
        {
            var result = new CompileResult();

            if (Path.GetExtension(file.FilePath) == ".cs")
            {
                CompileCS(console, superProject, project, file, outputFile);

                TransformMSIL(console, superProject, project, file, outputFile);

                CompileLLVMIR(console, superProject, project, file, outputFile + ".bc", outputFile);
            }
            else if (Path.GetExtension(file.FilePath) == ".cpp" || Path.GetExtension(file.FilePath) == ".c")
            {
                var startInfo = new ProcessStartInfo();

                if (file.Extension == ".cpp")
                {
                    startInfo.FileName = Path.Combine(BaseDirectory, "GCC\\bin", "arm-none-eabi-g++.exe");
                }
                else
                {
                    startInfo.FileName = Path.Combine(BaseDirectory, "GCC\\bin", "arm-none-eabi-gcc.exe");
                }


                startInfo.WorkingDirectory = project.Solution.CurrentDirectory;

                if (!System.IO.File.Exists(startInfo.FileName))
                {
                    result.ExitCode = -1;
                    console.WriteLine("Unable to find compiler (" + startInfo.FileName + ") Please check project compiler settings.");
                }
                else
                {
                    var fileArguments = string.Empty;

                    if (file.Extension == ".cpp")
                    {
                        fileArguments = "-x c++ -std=c++14 -fno-use-cxa-atexit";
                    }

                    startInfo.Arguments = string.Format("{0} {1} {2} -o{3} -MMD -MP", GetCompilerArguments(superProject, project, file),
                                                        fileArguments, file.Location, outputFile);

                    // Hide console window
                    startInfo.UseShellExecute        = false;
                    startInfo.RedirectStandardOutput = true;
                    startInfo.RedirectStandardError  = true;
                    startInfo.CreateNoWindow         = true;

                    //console.WriteLine (Path.GetFileNameWithoutExtension(startInfo.FileName) + " " + startInfo.Arguments);

                    using (var process = Process.Start(startInfo))
                    {
                        process.OutputDataReceived += (sender, e) => { console.WriteLine(e.Data); };

                        process.ErrorDataReceived += (sender, e) =>
                        {
                            if (e.Data != null)
                            {
                                console.WriteLine();
                                console.WriteLine(e.Data);
                            }
                        };

                        process.BeginOutputReadLine();

                        process.BeginErrorReadLine();

                        process.WaitForExit();

                        result.ExitCode = process.ExitCode;
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 10
0
        private CompileResult CompileExpr(Expression expr, List <object> queryArgs)
        {
            if (expr == null)
            {
                throw new NotSupportedException("Expression is NULL");
            }
            else if (expr is BinaryExpression)
            {
                var bin = (BinaryExpression)expr;

                CompileResult leftr  = CompileExpr(bin.Left, queryArgs);
                CompileResult rightr = CompileExpr(bin.Right, queryArgs);

                //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null")
                string text;
                if (leftr.CommandText == "?" && leftr.Value == null)
                {
                    text = CompileNullBinaryExpression(bin, rightr);
                }
                else if (rightr.CommandText == "?" && rightr.Value == null)
                {
                    text = CompileNullBinaryExpression(bin, leftr);
                }
                else
                {
                    text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")";
                }
                return(new CompileResult
                {
                    CommandText = text
                });
            }
            else if (expr.NodeType == ExpressionType.Call)
            {
                var           call = (MethodCallExpression)expr;
                var           args = new CompileResult[call.Arguments.Count];
                CompileResult obj  = call.Object != null?CompileExpr(call.Object, queryArgs) : null;

                for (int i = 0; i < args.Length; i++)
                {
                    args[i] = CompileExpr(call.Arguments[i], queryArgs);
                }

                string sqlCall = "";

                if (call.Method.Name == "Like" && args.Length == 2)
                {
                    sqlCall = "(" + args[0].CommandText + " like " + args[1].CommandText + ")";
                }
                else if (call.Method.Name == "Contains" && args.Length == 2)
                {
                    sqlCall = "(" + args[1].CommandText + " in " + args[0].CommandText + ")";
                }
                else if (call.Method.Name == "Contains" && args.Length == 1)
                {
                    if (call.Object != null && call.Object.Type == typeof(string))
                    {
                        sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + " || '%'))";
                    }
                    else
                    {
                        sqlCall = "(" + args[0].CommandText + " in " + obj.CommandText + ")";
                    }
                }
                else if (call.Method.Name == "StartsWith" && args.Length == 1)
                {
                    sqlCall = "(" + obj.CommandText + " like (" + args[0].CommandText + " || '%'))";
                }
                else if (call.Method.Name == "EndsWith" && args.Length == 1)
                {
                    sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + "))";
                }
                else if (call.Method.Name == "Equals" && args.Length == 1)
                {
                    sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))";
                }
                else if (call.Method.Name == "ToLower")
                {
                    sqlCall = "(lower(" + obj.CommandText + "))";
                }
                else if (call.Method.Name == "ToUpper")
                {
                    sqlCall = "(upper(" + obj.CommandText + "))";
                }
                else
                {
                    sqlCall = call.Method.Name.ToLower() + "(" +
                              string.Join(",", args.Select(a => a.CommandText).ToArray()) + ")";
                }
                return(new CompileResult
                {
                    CommandText = sqlCall
                });
            }
            else if (expr.NodeType == ExpressionType.Constant)
            {
                var c = (ConstantExpression)expr;
                queryArgs.Add(c.Value);
                return(new CompileResult
                {
                    CommandText = "?",
                    Value = c.Value
                });
            }
            else if (expr.NodeType == ExpressionType.Convert)
            {
                var           u    = (UnaryExpression)expr;
                Type          ty   = u.Type;
                CompileResult valr = CompileExpr(u.Operand, queryArgs);
                return(new CompileResult
                {
                    CommandText = valr.CommandText,
                    Value = valr.Value != null?ConvertTo(valr.Value, ty) : null
                });
            }
            else if (expr.NodeType == ExpressionType.MemberAccess)
            {
                var mem = (MemberExpression)expr;

                if (mem.Expression != null && mem.Expression.NodeType == ExpressionType.Parameter)
                {
                    //
                    // This is a column of our table, output just the column name
                    // Need to translate it if that column name is mapped
                    //
                    string columnName = Table.FindColumnWithPropertyName(mem.Member.Name).Name;
                    return(new CompileResult
                    {
                        CommandText = "\"" + columnName + "\""
                    });
                }
                else
                {
                    object obj = null;
                    if (mem.Expression != null)
                    {
                        CompileResult r = CompileExpr(mem.Expression, queryArgs);
                        if (r.Value == null)
                        {
                            throw new NotSupportedException("Member access failed to compile expression");
                        }
                        if (r.CommandText == "?")
                        {
                            queryArgs.RemoveAt(queryArgs.Count - 1);
                        }
                        obj = r.Value;
                    }

                    //
                    // Get the member value
                    //
                    object val = _sqlitePlatform.ReflectionService.GetMemberValue(obj, expr, mem.Member);

                    //
                    // Work special magic for enumerables
                    //
                    if (val != null && val is IEnumerable && !(val is string))
                    {
                        var sb = new StringBuilder();
                        sb.Append("(");
                        string head = "";
                        foreach (object a in (IEnumerable)val)
                        {
                            queryArgs.Add(a);
                            sb.Append(head);
                            sb.Append("?");
                            head = ",";
                        }
                        sb.Append(")");
                        return(new CompileResult
                        {
                            CommandText = sb.ToString(),
                            Value = val
                        });
                    }
                    else
                    {
                        queryArgs.Add(val);
                        return(new CompileResult
                        {
                            CommandText = "?",
                            Value = val
                        });
                    }
                }
            }
            throw new NotSupportedException("Cannot compile: " + expr.NodeType.ToString());
        }
 public CompilationResponse(CompileResult compileResult, ITextSnapshot snapshot)
 {
     CompileResult = compileResult;
     Snapshot      = snapshot;
 }
Ejemplo n.º 12
0
 public static void ValidateIncorrectCompilationResult(CompileResult result)
 {
     Assert.AreEqual(result.Compiled, false);
     Assert.AreNotEqual(result.StandartOutput, "");
 }
Ejemplo n.º 13
0
 public static void ValidateCorrectCompilationResult(CompileResult result)
 {
     Assert.AreEqual(result.Compiled, true);
 }
Ejemplo n.º 14
0
 private static void VerifyCustomTypeInfo(CompileResult compileResult, params byte[] expectedBytes)
 {
     VerifyCustomTypeInfo(compileResult.GetCustomTypeInfo(), expectedBytes);
 }
Ejemplo n.º 15
0
        public void CompileExecutable(string csPath, string dllPath, string outFileName, string outFilePath)
        {
            //var uid = csPath.GetHashCode() ^ dllPath.GetHashCode();

            List <string> csFiles     = new FileHelper(csPath, "*.cs").GetAllFiles();
            List <string> csFileNames = new FileHelper(csPath, "*.cs").GetAllFileNames();
            List <string> dllFiles    = new FileHelper(dllPath, "*.dll").GetAllFiles();


            provider = CodeDomProvider.CreateProvider("CSharp");
            if (provider != null)
            {
                CompilerParameters cp =
                    new CompilerParameters()
                {
                    CompilerOptions         = "/optimize",
                    GenerateExecutable      = false,
                    GenerateInMemory        = true,
                    IncludeDebugInformation = false,
                    TreatWarningsAsErrors   = false,
                    OutputAssembly          = Path.Combine(outFilePath, outFileName),
                    WarningLevel            = 4
                };

                var prefix = outFileName.Remove(outFileName.IndexOf('.'), 1);

                var resName = "CSNames";

                string xmlResource = Path.Combine(Logger.ServiceLogPath, prefix + resName);

                SerializeHelper.SerializeToXML
                (
                    Logger.ServiceLogPath,
                    new CSFiles()
                {
                    CSFileNames = csFileNames
                },
                    prefix + resName,
                    false
                );

                if (File.Exists(xmlResource + ".xml"))
                {
                    if (provider.Supports(GeneratorSupport.Resources))
                    {
                        cp.EmbeddedResources.Add(xmlResource + ".xml");
                    }
                }

                cp.ReferencedAssemblies.AddRange(Libraries.CommonFrameworkLibraries);

                dllFiles.ForEach(
                    a =>
                {
                    var name = new FileInfo(a).Name;
                    if (!Libraries.CommonFrameworkLibraries.Contains(name, new CustomStrComparer()))
                    {
                        cp.ReferencedAssemblies.Add(a);
                    }

                    //The follow can do the same thing as above...
                    //if (!Array.Exists(Libraries.CommonFrameworkLibraries,s=>string.Equals(s.ToUpper(),name.ToUpper())))
                    //    cp.ReferencedAssemblies.Add(a);
                });


                CompilerResults cr = provider.CompileAssemblyFromFile(cp, csFiles.ToArray());
                CompileResult   results;
                LogModel        model;

                if (cr.Errors.Count > 0)
                {
                    var errorArray = new CompilerError[cr.Errors.Count];
                    cr.Errors.CopyTo(errorArray, 0);

                    var warnings = errorArray.Where(e => e.IsWarning).ToList();
                    var errors   = errorArray.Where(e => !e.IsWarning).ToList();


                    results = new CompileResult()
                    {
                        IsBuildSuccess = errors.Count > 0 ? false : true,

                        Warnings = warnings,

                        Errors = errors
                    };
                }
                else
                {
                    results = new CompileResult()
                    {
                        IsBuildSuccess = true,

                        Warnings = null,

                        Errors = null
                    };
                }

                model = new LogModel()
                {
                    CurrentFolder = csPath,
                    DllPath       = dllPath,
                    CompileTime   = DateTime.Now,
                    CSFileNames   = csFileNames,
                    Results       = results
                };

                SerializeHelper.SerializeToXML(outputFolder, model, prefix, true);
            }
        }
Ejemplo n.º 16
0
        private CompileResult CompileExpr(Expression expr, List <object> queryArgs)
        {
            if (expr == null)
            {
                throw new NotSupportedException("Expression is NULL");
            }
            else if (expr is BinaryExpression)
            {
                var bin = (BinaryExpression)expr;

                var leftr  = CompileExpr(bin.Left, queryArgs);
                var rightr = CompileExpr(bin.Right, queryArgs);

                //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null")
                string text;
                if (leftr.CommandText == "?" && leftr.Value == null)
                {
                    text = CompileNullBinaryExpression(bin, rightr);
                }
                else if (rightr.CommandText == "?" && rightr.Value == null)
                {
                    text = CompileNullBinaryExpression(bin, leftr);
                }
                else
                {
                    text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")";
                }
                return(new CompileResult {
                    CommandText = text
                });
            }
            else if (expr.NodeType == ExpressionType.Not)
            {
                var    operandExpr = ((UnaryExpression)expr).Operand;
                var    opr         = CompileExpr(operandExpr, queryArgs);
                object val         = opr.Value;
                if (val is bool)
                {
                    val = !((bool)val);
                }
                return(new CompileResult
                {
                    CommandText = "NOT(" + opr.CommandText + ")",
                    Value = val
                });
            }
            else if (expr.NodeType == ExpressionType.Call)
            {
                var call = (MethodCallExpression)expr;
                var args = new CompileResult[call.Arguments.Count];
                var obj  = call.Object != null?CompileExpr(call.Object, queryArgs) : null;

                for (var i = 0; i < args.Length; i++)
                {
                    args[i] = CompileExpr(call.Arguments[i], queryArgs);
                }

                var sqlCall = "";

                if (call.Method.Name == "Like" && args.Length == 2)
                {
                    sqlCall = "(" + args[0].CommandText + " like " + args[1].CommandText + ")";
                }
                else if (call.Method.Name == "Contains" && args.Length == 2)
                {
                    sqlCall = "(" + args[1].CommandText + " in " + args[0].CommandText + ")";
                }
                else if (call.Method.Name == "Contains" && args.Length == 1)
                {
                    if (call.Object != null && call.Object.Type == typeof(string))
                    {
                        sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + " || '%'))";
                    }
                    else
                    {
                        sqlCall = "(" + args[0].CommandText + " in " + obj.CommandText + ")";
                    }
                }
                else if (call.Method.Name == "StartsWith" && args.Length == 1)
                {
                    sqlCall = "(" + obj.CommandText + " like (" + args[0].CommandText + " || '%'))";
                }
                else if (call.Method.Name == "EndsWith" && args.Length == 1)
                {
                    sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + "))";
                }
                else if (call.Method.Name == "Equals" && args.Length == 1)
                {
                    sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))";
                }
                else if (call.Method.Name == "ToLower")
                {
                    sqlCall = "(lower(" + obj.CommandText + "))";
                }
                else if (call.Method.Name == "ToUpper")
                {
                    sqlCall = "(upper(" + obj.CommandText + "))";
                }
                else
                {
                    sqlCall = call.Method.Name.ToLower() + "(" + string.Join(",", args.Select(a => a.CommandText).ToArray()) + ")";
                }
                return(new CompileResult {
                    CommandText = sqlCall
                });
            }
            else if (expr.NodeType == ExpressionType.Constant)
            {
                var c = (ConstantExpression)expr;
                queryArgs.Add(c.Value);
                return(new CompileResult
                {
                    CommandText = "?",
                    Value = c.Value
                });
            }
            else if (expr.NodeType == ExpressionType.Convert)
            {
                var u    = (UnaryExpression)expr;
                var ty   = u.Type;
                var valr = CompileExpr(u.Operand, queryArgs);
                return(new CompileResult
                {
                    CommandText = valr.CommandText,
                    Value = valr.Value != null?ConvertTo(valr.Value, ty) : null
                });
            }
            else if (expr.NodeType == ExpressionType.MemberAccess)
            {
                var mem = (MemberExpression)expr;

                if (mem.Expression != null && mem.Expression.NodeType == ExpressionType.Parameter)
                {
                    //
                    // This is a column of our table, output just the column name
                    // Need to translate it if that column name is mapped
                    //
                    var columnName = Table.FindColumnWithTargetName(mem.Member.Name).Name;
                    return(new CompileResult {
                        CommandText = "\"" + columnName + "\""
                    });
                }
                else
                {
                    object obj = null;
                    if (mem.Expression != null)
                    {
                        var r = CompileExpr(mem.Expression, queryArgs);
                        if (r.Value == null)
                        {
                            throw new NotSupportedException("Member access failed to compile expression");
                        }
                        if (r.CommandText == "?")
                        {
                            queryArgs.RemoveAt(queryArgs.Count - 1);
                        }
                        obj = r.Value;
                    }

                    //
                    // Get the member value
                    //
                    object val = null;

#if !USE_NEW_REFLECTION_API
                    if (mem.Member.MemberType == MemberTypes.Property)
                    {
#else
                    if (mem.Member is PropertyInfo)
                    {
#endif
                        var m = (PropertyInfo)mem.Member;
                        val = m.GetValue(obj, null);
#if !USE_NEW_REFLECTION_API
                    }
                    else if (mem.Member.MemberType == MemberTypes.Field)
                    {
#else
                    }
                    else if (mem.Member is FieldInfo)
                    {
#endif
#if SILVERLIGHT
                        val = Expression.Lambda(expr).Compile().DynamicInvoke();
#else
                        var m = (FieldInfo)mem.Member;
                        val = m.GetValue(obj);
#endif
                    }
                    else
                    {
#if !USE_NEW_REFLECTION_API
                        throw new NotSupportedException("MemberExpr: " + mem.Member.MemberType);
#else
                        throw new NotSupportedException("MemberExpr: " + mem.Member.DeclaringType);
#endif
                    }

                    //
                    // Work special magic for enumerables
                    //
                    if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable <byte>))
                    {
                        var sb = new System.Text.StringBuilder();
                        sb.Append("(");
                        var head = "";
                        foreach (var a in (System.Collections.IEnumerable)val)
                        {
                            queryArgs.Add(a);
                            sb.Append(head);
                            sb.Append("?");
                            head = ",";
                        }
                        sb.Append(")");
                        return(new CompileResult
                        {
                            CommandText = sb.ToString(),
                            Value = val
                        });
                    }
                    else
                    {
                        queryArgs.Add(val);
                        return(new CompileResult
                        {
                            CommandText = "?",
                            Value = val
                        });
                    }
                }
            }
            throw new NotSupportedException("Cannot compile: " + expr.NodeType.ToString());
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Scans the specified non-plugged IL block.
        /// </summary>
        /// <param name="TheLibrary">The library currently being compiled.</param>
        /// <param name="theMethodInfo">The method which generated the IL block.</param>
        /// <param name="theILBlock">The IL block to scan.</param>
        /// <returns>CompileResult.OK.</returns>
        private static CompileResult ScanNonpluggedILBlock(ILLibrary TheLibrary, Types.MethodInfo theMethodInfo, ILBlock theILBlock)
        {
            CompileResult result = CompileResult.OK;

            ASM.ASMBlock TheASMBlock = new ASM.ASMBlock()
            {
                OriginMethodInfo = theMethodInfo,
                Priority         = theMethodInfo.Priority
            };

            ILConversionState convState = new ILConversionState()
            {
                TheILLibrary      = TheLibrary,
                CurrentStackFrame = new StackFrame(),
                Input             = theILBlock,
                Result            = TheASMBlock
            };

            foreach (ILOp anOp in theILBlock.ILOps)
            {
                try
                {
                    string commentText = TheASMBlock.GenerateILOpLabel(convState.PositionOf(anOp), "") + "  --  " + anOp.opCode.ToString() + " -- Offset: " + anOp.Offset.ToString("X2");

                    ASM.ASMOp newCommentOp = TargetArchitecture.CreateASMOp(ASM.OpCodes.Comment, commentText);
                    TheASMBlock.ASMOps.Add(newCommentOp);

                    int currCount = TheASMBlock.ASMOps.Count;
                    if (anOp is ILOps.MethodStart)
                    {
                        TargetArchitecture.MethodStartOp.Convert(convState, anOp);
                    }
                    else if (anOp is ILOps.MethodEnd)
                    {
                        TargetArchitecture.MethodEndOp.Convert(convState, anOp);
                    }
                    else if (anOp is ILOps.StackSwitch)
                    {
                        TargetArchitecture.StackSwitchOp.Convert(convState, anOp);
                    }
                    else
                    {
                        ILOp ConverterOp = TargetArchitecture.TargetILOps[(ILOp.OpCodes)anOp.opCode.Value];
                        ConverterOp.Convert(convState, anOp);
                    }

                    if (anOp.LabelRequired)
                    {
                        if (currCount < TheASMBlock.ASMOps.Count)
                        {
                            TheASMBlock.ASMOps[currCount].ILLabelPosition = convState.PositionOf(anOp);
                            TheASMBlock.ASMOps[currCount].RequiresILLabel = true;
                        }
                    }
                }
                catch (KeyNotFoundException)
                {
                    result = CompileResult.PartialFailure;

                    Logger.LogError(Errors.ILCompiler_ScanILOpFailure_ErrorCode, theMethodInfo.ToString(), anOp.Offset,
                                    string.Format(Errors.ErrorMessages[Errors.ILCompiler_ScanILOpFailure_ErrorCode], Enum.GetName(typeof(ILOp.OpCodes), anOp.opCode.Value), "Conversion for IL op not found."));
                }
                catch (InvalidOperationException ex)
                {
                    result = CompileResult.PartialFailure;

                    Logger.LogError(Errors.ILCompiler_ScanILOpFailure_ErrorCode, theMethodInfo.ToString(), anOp.Offset,
                                    string.Format(Errors.ErrorMessages[Errors.ILCompiler_ScanILOpFailure_ErrorCode], Enum.GetName(typeof(ILOp.OpCodes), anOp.opCode.Value), ex.Message));
                }
                catch (NotSupportedException ex)
                {
                    result = CompileResult.PartialFailure;

                    Logger.LogError(Errors.ILCompiler_ScanILOpFailure_ErrorCode, theMethodInfo.ToString(), anOp.Offset,
                                    string.Format(Errors.ErrorMessages[Errors.ILCompiler_ScanILOpFailure_ErrorCode], Enum.GetName(typeof(ILOp.OpCodes), anOp.opCode.Value), "An IL op reported something as not supported : " + ex.Message));
                }
                catch (Exception ex)
                {
                    result = CompileResult.Fail;

                    Logger.LogError(Errors.ILCompiler_ScanILOpFailure_ErrorCode, theMethodInfo.ToString(), anOp.Offset,
                                    string.Format(Errors.ErrorMessages[Errors.ILCompiler_ScanILOpFailure_ErrorCode], Enum.GetName(typeof(ILOp.OpCodes), anOp.opCode.Value), ex.Message));
                }
            }

            TheLibrary.TheASMLibrary.ASMBlocks.Add(TheASMBlock);

            return(result);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Scans the specified library and any dependencies.
        /// </summary>
        /// <param name="TheLibrary">The library to scan.</param>
        /// <returns>
        /// CompileResult.OK if completed successfully.
        /// Otherwise CompileResult.PartialFail or CompileResult.Error depending on
        /// the extent of the problem.
        /// </returns>
        public static CompileResult Scan(ILLibrary TheLibrary)
        {
            CompileResult result = CompileResult.OK;

            if (TheLibrary.ILScanned)
            {
                return(result);
            }
            TheLibrary.ILScanned = true;

            foreach (ILLibrary depLib in TheLibrary.Dependencies)
            {
                Scan(depLib);
            }

            // Create / Add Static Fields ASM Block
            ASM.ASMBlock StaticFieldsBlock = new ASM.ASMBlock()
            {
                Priority = (long.MinValue / 2) - 9
            };
            TheLibrary.TheASMLibrary.ASMBlocks.Add(StaticFieldsBlock);

            // Create / Add Types Table ASM Block
            ASM.ASMBlock TypesTableBlock = new ASM.ASMBlock()
            {
                Priority = (long.MinValue / 2) - 8
            };
            TheLibrary.TheASMLibrary.ASMBlocks.Add(TypesTableBlock);

            // Create / Add Method Tables ASM Block
            ASM.ASMBlock MethodTablesBlock = new ASM.ASMBlock()
            {
                Priority = (long.MinValue / 2) + 0
            };
            TheLibrary.TheASMLibrary.ASMBlocks.Add(MethodTablesBlock);

            // Create / Add Field Tables ASM Block
            ASM.ASMBlock FieldTablesBlock = new ASM.ASMBlock()
            {
                Priority = (long.MinValue / 2) + 1
            };
            TheLibrary.TheASMLibrary.ASMBlocks.Add(FieldTablesBlock);

            // Don't use foreach or you get collection modified exceptions
            for (int i = 0; i < TheLibrary.TypeInfos.Count; i++)
            {
                Types.TypeInfo aTypeInfo = TheLibrary.TypeInfos[i];
                if (!ScannedTypes.ContainsKey(aTypeInfo.ID))
                {
                    ScannedTypes.Add(aTypeInfo.ID, TheLibrary);
                    ScanStaticFields(TheLibrary, aTypeInfo, StaticFieldsBlock);
                    ScanType(TheLibrary, aTypeInfo, TypesTableBlock);
                    ScanMethods(TheLibrary, aTypeInfo, MethodTablesBlock);
                    ScanFields(TheLibrary, aTypeInfo, FieldTablesBlock);
                }
            }

            foreach (Types.MethodInfo aMethodInfo in TheLibrary.ILBlocks.Keys)
            {
                ILBlock       anILBlock    = TheLibrary.ILBlocks[aMethodInfo];
                CompileResult singleResult = CompileResult.OK;

                if (anILBlock.Plugged)
                {
                    singleResult = ScanPluggedILBlock(TheLibrary, aMethodInfo, anILBlock);
                }
                else
                {
                    singleResult = ScanNonpluggedILBlock(TheLibrary, aMethodInfo, anILBlock);
                }

                if (result != CompileResult.OK)
                {
                    result = singleResult;
                }
            }

            // Create / Add String Literals ASM Block
            #region String Literals Block

            ASM.ASMBlock StringLiteralsBlock = new ASM.ASMBlock()
            {
                Priority = (long.MinValue / 2) - 10
            };
            TheLibrary.TheASMLibrary.ASMBlocks.Add(StringLiteralsBlock);

            string StringTypeId = ILLibrary.SpecialClasses[typeof(Attributes.StringClassAttribute)].First().ID;
            StringLiteralsBlock.AddExternalLabel(StringTypeId);
            foreach (KeyValuePair <string, string> aStringLiteral in TheLibrary.StringLiterals)
            {
                string value       = aStringLiteral.Value;
                byte[] lengthBytes = BitConverter.GetBytes(value.Length);

                ASM.ASMOp newLiteralOp = TargetArchitecture.CreateASMOp(ASM.OpCodes.StringLiteral,
                                                                        aStringLiteral.Key, StringTypeId, lengthBytes, value.ToCharArray());

                StringLiteralsBlock.Append(newLiteralOp);
            }

            #endregion

            return(result);
        }
Ejemplo n.º 19
0
        public CompilationUnitSyntax Reduce()
        {
            CompileResult debug   = Compiler.Compile(Original, Compiler.DebugOptions);
            CompileResult release = Compiler.Compile(Original, Compiler.ReleaseOptions);

            if (debug.CompileDiagnostics.Length > 0 || release.CompileDiagnostics.Length > 0)
            {
                ImmutableArray <Diagnostic> diags =
                    debug.CompileDiagnostics.Length > 0 ? debug.CompileDiagnostics : release.CompileDiagnostics;

                IEnumerable <Diagnostic> errs = diags.Where(d => d.Severity == DiagnosticSeverity.Error);
                string errorString            = string.Join(Environment.NewLine, errs.Select(e => "  " + e));
                throw new InvalidOperationException("Program has compile errors: " + Environment.NewLine + errorString);
            }

            Func <CompilationUnitSyntax, bool> isInteresting;

            if (debug.RoslynException != null || release.RoslynException != null)
            {
                CSharpCompilationOptions opts = debug.RoslynException != null ? Compiler.DebugOptions : Compiler.ReleaseOptions;
                isInteresting = program => Compiler.Compile(program, opts).RoslynException != null;
            }
            else
            {
                var origPair = new ProgramPair(debug.Assembly, release.Assembly);
                ProgramPairResults origResults = ProgramExecutor.RunPair(origPair);
                if (origResults.DebugResult.Checksum == origResults.ReleaseResult.Checksum &&
                    origResults.DebugResult.ExceptionType == origResults.ReleaseResult.ExceptionType)
                {
                    throw new InvalidOperationException("Program has no errors");
                }

                isInteresting = prog =>
                {
                    ProgramPairResults results = CompileAndRun(prog);
                    if (results == null)
                    {
                        return(false);
                    }

                    // Do exceptions first because they will almost always change checksum
                    if (origResults.DebugResult.ExceptionType != origResults.ReleaseResult.ExceptionType)
                    {
                        // Must throw same exceptions in debug and release to be bad.
                        return(results.DebugResult.ExceptionType == origResults.DebugResult.ExceptionType &&
                               results.ReleaseResult.ExceptionType == origResults.ReleaseResult.ExceptionType);
                    }
                    else
                    {
                        if (results.DebugResult.ExceptionType != origResults.DebugResult.ExceptionType ||
                            results.ReleaseResult.ExceptionType != origResults.ReleaseResult.ExceptionType)
                        {
                            return(false);
                        }
                    }

                    return(results.DebugResult.Checksum != results.ReleaseResult.Checksum);
                };
            }

            // Save original comments as simplification may remove it by removing an unnecessary type.
            SyntaxTriviaList originalTrivia = Original.GetLeadingTrivia();

            Reduced = Original.WithLeadingTrivia();

            Reduced = CoarseSimplify(Reduced, isInteresting);
            List <SyntaxNode> simplifiedNodes = new List <SyntaxNode>();
            bool first = true;
            bool any   = true;

            while (any)
            {
                any = false;
                while (true)
                {
                    if (!SimplifyOne("Statements", Reduced.DescendantNodes().Where(n => n is StatementSyntax).ToList()))
                    {
                        break;
                    }
                    any = true;
                }

                while (true)
                {
                    if (!SimplifyOne("Expressions", Reduced.DescendantNodes().Where(n => n is ExpressionSyntax).ToList()))
                    {
                        break;
                    }
                    any = true;
                }

                while (true)
                {
                    List <SyntaxNode> members =
                        Reduced.DescendantNodesAndSelf().Where(n => n is MemberDeclarationSyntax || n is CompilationUnitSyntax).ToList();

                    if (!SimplifyOne("Members", members))
                    {
                        break;
                    }
                    any = true;
                }

                first = false;

                bool SimplifyOne(string name, List <SyntaxNode> list)
                {
                    for (int i = 0; i < 2000; i++)
                    {
                        Console.Title = $"Simplifying {name}. Iter: {i}";

                        SyntaxNode node = list[_rng.Next(list.Count)];
                        // Do not optimize checksum args and call itself.
                        // We still want to remove these statements, however, so we focus on the expression only.
                        InvocationExpressionSyntax invocParent = node.FirstAncestorOrSelf <InvocationExpressionSyntax>();
                        if (invocParent != null && IsChecksumCall(invocParent))
                        {
                            continue;
                        }

                        // If we fail at creating a new bad example, then we want to be able to restore the state
                        // so the reducer will not blow these up unnecessarily.
                        int origVarCounter = _varCounter;

                        simplifiedNodes.Clear();
                        SimplifyNode(node, !first, simplifiedNodes);

                        foreach (SyntaxNode candidateNode in simplifiedNodes)
                        {
                            CompilationUnitSyntax candidate = Reduced.ReplaceNode(node, candidateNode);
                            if (isInteresting(candidate))
                            {
                                Reduced = candidate;
                                return(true);
                            }
                        }

                        _varCounter = origVarCounter;
                    }

                    return(false);
                }
            }

            List <SyntaxTrivia> outputComments = GetOutputComments(debug, release).Select(Comment).ToList();

            SimplifyRuntime();
            double           oldSizeKiB = Original.NormalizeWhitespace().ToString().Length / 1024.0;
            double           newSizeKiB = Reduced.NormalizeWhitespace().ToString().Length / 1024.0;
            SyntaxTriviaList newTrivia  =
                originalTrivia.Add(Comment(FormattableString.Invariant($"// Reduced from {oldSizeKiB:F1} KiB to {newSizeKiB:F1} KiB")))
                .AddRange(outputComments);

            Reduced = Reduced.WithLeadingTrivia(newTrivia);

            return(Reduced);
        }
Ejemplo n.º 20
0
        public override LinkResult Link(IConsole console, IStandardProject superProject, IStandardProject project, CompileResult assemblies, string outputPath)
        {
            var result = new LinkResult();

            string commandName = project.Type == ProjectType.StaticLibrary ? ARExecutable : LDExecutable;

            var objectArguments = string.Empty;

            foreach (var obj in assemblies.ObjectLocations)
            {
                objectArguments += project.Solution.CurrentDirectory.MakeRelativePath(obj).ToPlatformPath() + " ";
            }

            var libs = string.Empty;

            foreach (var lib in assemblies.LibraryLocations)
            {
                libs += lib + " ";
            }

            var outputDir = Path.GetDirectoryName(outputPath);

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

            var outputName = Path.GetFileName(outputPath);

            if (project.Type == ProjectType.StaticLibrary)
            {
                outputName = Path.GetFileName(outputPath);
            }

            var executable = Path.Combine(outputDir, outputName);

            var linkedLibraries = string.Empty;

            foreach (var libraryPath in project.StaticLibraries)
            {
                var relativePath = Path.GetDirectoryName(libraryPath);

                var libName = Path.GetFileNameWithoutExtension(libraryPath).Substring(3);

                linkedLibraries += string.Format("-L\"{0}\" -l{1} ", relativePath, libName);
            }

            string libraryPaths = string.Empty;

            var linkerScripts = string.Empty;

            if (project.Type == ProjectType.Executable)
            {
                var settings = project.GetToolchainSettings <GccToolchainSettings>();

                foreach (var libraryPath in settings.LinkSettings.LinkedLibraries)
                {
                    var path = project.Solution.CurrentDirectory.MakeRelativePath(Path.Combine(project.CurrentDirectory, Path.GetDirectoryName(libraryPath)));
                    libraryPaths += $"-Wl,--library-path={path.ToPlatformPath()} ";

                    var libName = Path.GetFileName(libraryPath);

                    linkedLibraries += string.Format($"-Wl,--library=:{libName} ");
                }

                foreach (var script in settings.LinkSettings.LinkerScripts)
                {
                    linkerScripts += $"-Wl,-T\"{project.Solution.CurrentDirectory.MakeRelativePath(Path.Combine(project.CurrentDirectory, script)).ToPlatformPath()}\" ";
                }

                foreach (var lib in settings.LinkSettings.SystemLibraries)
                {
                    linkedLibraries += $"-l{lib} ";
                }
            }

            foreach (var lib in project.BuiltinLibraries)
            {
                linkedLibraries += $"-l{lib} ";
            }

            linkedLibraries += GetBaseLibraryArguments(superProject);

            string arguments = string.Empty;

            if (project.Type == ProjectType.StaticLibrary)
            {
                arguments = string.Format("rvs {0} {1}", executable, objectArguments);
            }
            else
            {
                var environment = superProject.GetEnvironmentVariables().AppendRange(Platform.EnvironmentVariables);

                if (!string.IsNullOrWhiteSpace(SysRoot))
                {
                    arguments = string.Format("{0} {1} -o{2} {3} {4} -Wl,--start-group {5} {6} -Wl,--end-group --sysroot=\"{7}\"", GetLinkerArguments(superProject, project).ExpandVariables(environment), linkerScripts, executable, objectArguments, libraryPaths, linkedLibraries, libs, SysRoot);
                }
                else
                {
                    arguments = string.Format("{0} {1} -o{2} {3} {4} -Wl,--start-group {5} {6} -Wl,--end-group", GetLinkerArguments(superProject, project).ExpandVariables(environment), linkerScripts, executable, objectArguments, libraryPaths, linkedLibraries, libs);
                }
            }

            result.ExitCode = PlatformSupport.ExecuteShellCommand(commandName, arguments, (s, e) =>
            {
                if (e.Data != null)
                {
                    console.WriteLine(e.Data);
                }
            },
                                                                  (s, e) =>
            {
                if (e.Data != null && !e.Data.Contains("creating"))
                {
                    console.WriteLine(e.Data);
                }
            }, false, project.Solution.CurrentDirectory, false, RunWithSystemPaths, ExtraPaths);

            if (Studio.DebugMode)
            {
                console.WriteLine(Path.GetFileNameWithoutExtension(commandName) + " " + arguments);
            }

            if (result.ExitCode == 0)
            {
                result.Executable = executable;
            }

            return(result);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Logic for Compile button, after WorkflowCompiler has done its work. Separated out for testability.
        /// </summary>
        private void CompileCommandExecutePostCompile(WorkflowItem compiledWorkflow, CompileResult compileResult)
        {
            if (compiledWorkflow == null)
            {
                throw new ArgumentNullException("compiledWorkflow");
            }

            if (compileResult == null)
            {
                throw new ArgumentNullException("compileResult");
            }

            // Import compile result. We signal to the UX that there has been a change, and it should respond by running the
            // import process
            try
            {
                Compiler.AddToCaching(compileResult.FileName);
                MessageBoxService.CompileSuccessed(compiledWorkflow.Name);
            }
            catch (Exception ex)
            {
                throw new UserFacingException(ex.Message);
            }
        }
Ejemplo n.º 22
0
        public override LinkResult Link(IConsole console, IStandardProject superProject, IStandardProject project,
                                        CompileResult assemblies, string outputDirectory)
        {
            var result = new LinkResult();

            var startInfo = new ProcessStartInfo();

            startInfo.FileName = Path.Combine(BaseDirectory, "GCC\\bin", "arm-none-eabi-gcc.exe");

            if (project.Type == ProjectType.StaticLibrary)
            {
                startInfo.FileName = Path.Combine(BaseDirectory, "GCC\\bin", "arm-none-eabi-ar.exe");
            }

            startInfo.WorkingDirectory = project.Solution.CurrentDirectory;

            if (!System.IO.File.Exists(startInfo.FileName))
            {
                result.ExitCode = -1;
                console.WriteLine("Unable to find linker executable (" + startInfo.FileName + ") Check project compiler settings.");
                return(result);
            }

            // GenerateLinkerScript(project);

            var objectArguments = string.Empty;

            foreach (var obj in assemblies.ObjectLocations)
            {
                objectArguments += obj + " ";
            }

            var libs = string.Empty;

            foreach (var lib in assemblies.LibraryLocations)
            {
                libs += lib + " ";
            }

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

            var outputName = Path.GetFileNameWithoutExtension(project.Location) + ".elf";

            if (project.Type == ProjectType.StaticLibrary)
            {
                outputName = "lib" + Path.GetFileNameWithoutExtension(project.Name) + ".a";
            }

            var executable = Path.Combine(outputDirectory, outputName);

            var linkedLibraries = string.Empty;

            foreach (var libraryPath in project.StaticLibraries)
            {
                var relativePath = project.CurrentDirectory;

                var libName = Path.GetFileNameWithoutExtension(libraryPath).Substring(3);

                linkedLibraries += string.Format(" -L\"{0}\" -l{1} ", relativePath, libName);
            }

            foreach (var lib in project.BuiltinLibraries)
            {
                linkedLibraries += string.Format("-l{0} ", lib);
            }


            // Hide console window
            startInfo.UseShellExecute        = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError  = true;
            startInfo.RedirectStandardInput  = true;
            startInfo.CreateNoWindow         = true;

            startInfo.Arguments = string.Format("{0} -o{1} {2} -Wl,--start-group {3} {4} -Wl,--end-group",
                                                GetLinkerArguments(project), executable, objectArguments, linkedLibraries, libs);

            if (project.Type == ProjectType.StaticLibrary)
            {
                startInfo.Arguments = string.Format("rvs {0} {1}", executable, objectArguments);
            }

            //console.WriteLine(Path.GetFileNameWithoutExtension(startInfo.FileName) + " " + startInfo.Arguments);
            //console.WriteLine ("[LL] - " + startInfo.Arguments);

            using (var process = Process.Start(startInfo))
            {
                process.OutputDataReceived += (sender, e) =>
                {
                    //console.WriteLine(e.Data);
                };

                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data != null && !e.Data.Contains("creating"))
                    {
                        console.WriteLine(e.Data);
                    }
                };

                process.BeginOutputReadLine();

                process.BeginErrorReadLine();

                process.WaitForExit();

                result.ExitCode = process.ExitCode;

                if (result.ExitCode == 0)
                {
                    result.Executable = executable;
                }
            }

            return(result);
        }
Ejemplo n.º 23
0
		protected override CompileResult Compile(string outputFile, IEnumerable<string> references, string code, out Assembly generatedAssembly)
		{
			var inMemory = string.IsNullOrEmpty(outputFile);
			var parameters = new CompilerParameters
			{
				GenerateInMemory = inMemory,
				TreatWarningsAsErrors = false,
				GenerateExecutable = false,
				OutputAssembly = inMemory ? null : outputFile
			};

			FixMonoPath();

			SetParameters(parameters);

			if (references != null)
			{
				foreach (var reference in references)
				{
					if (File.Exists(reference))
						parameters.ReferencedAssemblies.Add(reference);
				}
			}

			var codeProvider = CreateCodeProvider();
			var results = codeProvider.CompileAssemblyFromSource(parameters, code);

			var errors = results.Errors.Cast<CompilerError>().ToList();
			var result = new CompileResult { Errors = errors.Select(r => r.ErrorText).ToList() };
			if (errors.Count == 0 || errors.All(r => r.IsWarning))
			{
				if (inMemory)
					generatedAssembly = results.CompiledAssembly;
				else
					generatedAssembly = null;
				result.Success = true;
			}
			else
			{
				generatedAssembly = null;
				errors.ForEach(msg => Debug.WriteLine(msg.ToString()));
			}
			return result;
		}
 internal CompileExpressionResult(CompileResult compileResult, CompilationTestData testData)
 {
     this.CompileResult = compileResult;
     this.TestData      = testData;
 }
Ejemplo n.º 25
0
 protected void BuildFunctionArguments(CompileResult result, List <FunctionArgument> args)
 {
     BuildFunctionArguments(result, result.DataType, args);
 }
Ejemplo n.º 26
0
        public override LinkResult Link(IConsole console, IStandardProject superProject, IStandardProject project, CompileResult assemblies, string outputPath)
        {
            var result = new LinkResult();

            string commandName = project.Type == ProjectType.StaticLibrary ? ARExecutable : LDExecutable;

            var objectArguments = string.Empty;

            foreach (var obj in assemblies.ObjectLocations)
            {
                objectArguments += obj + " ";
            }

            var libs = string.Empty;

            foreach (var lib in assemblies.LibraryLocations)
            {
                libs += lib + " ";
            }

            var outputDir = Path.GetDirectoryName(outputPath);

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

            var outputName = Path.GetFileNameWithoutExtension(outputPath) + ExecutableExtension;

            if (project.Type == ProjectType.StaticLibrary)
            {
                outputName = Path.GetFileNameWithoutExtension(outputPath) + StaticLibraryExtension;
            }

            var executable = Path.Combine(outputDir, outputName);

            var linkedLibraries = string.Empty;

            foreach (var libraryPath in project.StaticLibraries)
            {
                var relativePath = Path.GetDirectoryName(libraryPath);

                var libName = Path.GetFileNameWithoutExtension(libraryPath).Substring(3);

                linkedLibraries += string.Format("-L\"{0}\" -l{1} ", relativePath, libName);
            }

            string libraryPaths = string.Empty;

            var linkerScripts = string.Empty;

            if (project.Type == ProjectType.Executable)
            {
                var settings = GetSettings(project);

                foreach (var libraryPath in settings.LinkSettings.LinkedLibraries)
                {
                    libraryPaths += $"-Wl,--library-path={Path.Combine(project.CurrentDirectory, Path.GetDirectoryName(libraryPath)).ToPlatformPath()} ";

                    var libName = Path.GetFileName(libraryPath);

                    linkedLibraries += string.Format($"-Wl,--library=:{libName} ");
                }

                if (project.Type == ProjectType.Executable)
                {
                    foreach (var script in settings.LinkSettings.LinkerScripts)
                    {
                        linkerScripts += $"-Wl,-T\"{Path.Combine(project.CurrentDirectory, script)}\" ";
                    }
                }
            }

            foreach (var lib in project.BuiltinLibraries)
            {
                linkedLibraries += string.Format("-l{0} ", lib);
            }

            linkedLibraries += GetBaseLibraryArguments(superProject);

            string arguments = string.Empty;

            if (project.Type == ProjectType.StaticLibrary)
            {
                arguments = string.Format("rvs {0} {1}", executable, objectArguments);
            }
            else
            {
                arguments = string.Format("{0} {1} -o{2} {3} {4} -Wl,--start-group {5} {6} -Wl,--end-group", GetLinkerArguments(superProject, project), linkerScripts, executable, objectArguments, libraryPaths, linkedLibraries, libs);
            }

            result.ExitCode = PlatformSupport.ExecuteShellCommand(commandName, arguments, (s, e) => { },
                                                                  (s, e) =>
            {
                if (e.Data != null && !e.Data.Contains("creating"))
                {
                    console.WriteLine(e.Data);
                }
            }, false, project.Solution.CurrentDirectory, false);

            //console.WriteLine(Path.GetFileNameWithoutExtension(commandName) + " " + arguments);

            if (result.ExitCode == 0)
            {
                result.Executable = executable;
            }

            return(result);
        }
Ejemplo n.º 27
0
 private bool TryGetSearchValue(FunctionArgument argument, ParsingContext context, out object searchValue, out CompileResult error)
 {
     searchValue = null;
     error       = null;
     if (argument.Value is ExcelDataProvider.IRangeInfo rangeInfo)
     {
         // If the first argument is a range, we take the value in the range that is perpendicular to the function.
         // If the lookup range and MATCH function are not perpendicular, #NA is returned.
         var rangeInfoValue = argument.ValueAsRangeInfo;
         var addr           = rangeInfoValue?.Address;
         // The lookup range must be one-dimensional.
         if (addr._fromCol != addr._toCol && addr._fromRow != addr._toRow)
         {
             error = new CompileResult(eErrorType.Value);
             return(false);
         }
         var direction        = this.GetLookupDirection(addr);
         var functionLocation = context.Scopes.Current.Address;
         if (direction == LookupDirection.Vertical && addr._fromRow <= functionLocation.FromRow && functionLocation.FromRow <= addr._toRow)
         {
             searchValue = rangeInfoValue.GetValue(functionLocation.FromRow, addr._fromCol);
         }
         else if (direction == LookupDirection.Horizontal && addr._fromCol <= functionLocation.FromCol && functionLocation.FromCol <= addr._toCol)
         {
             searchValue = rangeInfoValue.GetValue(addr._fromRow, functionLocation.FromCol);
         }
         else
         {
             error = new CompileResult(eErrorType.NA);
             return(false);
         }
     }
     else
     {
         searchValue = argument.Value;
     }
     return(true);
 }
Ejemplo n.º 28
0
        public override CompileResult Compile(IConsole console, IStandardProject superProject, IStandardProject project,
                                              ISourceFile file, string outputFile)
        {
            var result = new CompileResult();

            var startInfo = new ProcessStartInfo();

            if (file.Extension == ".cpp")
            {
                startInfo.FileName = Path.Combine(BaseDirectory, "clang++" + Platform.ExecutableExtension);
            }
            else
            {
                startInfo.FileName = Path.Combine(BaseDirectory, "clang" + Platform.ExecutableExtension);
            }


            startInfo.WorkingDirectory = file.CurrentDirectory;

            if (!System.IO.File.Exists(startInfo.FileName))
            {
                result.ExitCode = -1;
                console.WriteLine("Unable to find compiler (" + startInfo.FileName + ") Please check project compiler settings.");
            }
            else
            {
                var fileArguments = string.Empty;

                if (file.Extension == ".cpp")
                {
                    fileArguments = "-x c++ -fno-use-cxa-atexit";
                }

                startInfo.Arguments = string.Format("{0} {1} {2} -o{3} -fshort-enums -MMD -MP", fileArguments,
                                                    GetCompilerArguments(superProject, project, file), file.Location, outputFile);

                // Hide console window
                startInfo.UseShellExecute        = false;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError  = true;
                startInfo.CreateNoWindow         = true;

                //console.WriteLine (Path.GetFileNameWithoutExtension(startInfo.FileName) + " " + startInfo.Arguments);

                using (var process = Process.Start(startInfo))
                {
                    process.OutputDataReceived += (sender, e) => { console.WriteLine(e.Data); };

                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data != null)
                        {
                            console.WriteLine();
                            console.WriteLine(e.Data);
                        }
                    };

                    process.BeginOutputReadLine();

                    process.BeginErrorReadLine();

                    process.WaitForExit();

                    result.ExitCode = process.ExitCode;
                }
            }

            return(result);
        }
Ejemplo n.º 29
0
 private CompileResult CompileExpr(Expression expr, List <object> queryArgs)
 {
     if (expr == null)
     {
         throw new NotSupportedException("Expression is NULL");
     }
     if (expr is BinaryExpression)
     {
         BinaryExpression binaryExpression = (BinaryExpression)expr;
         CompileResult    compileResult    = CompileExpr(binaryExpression.Left, queryArgs);
         CompileResult    compileResult2   = CompileExpr(binaryExpression.Right, queryArgs);
         string           commandText      = (compileResult.CommandText == "?" && compileResult.Value == null) ? CompileNullBinaryExpression(binaryExpression, compileResult2) : ((!(compileResult2.CommandText == "?") || compileResult2.Value != null) ? ("(" + compileResult.CommandText + " " + GetSqlName(binaryExpression) + " " + compileResult2.CommandText + ")") : CompileNullBinaryExpression(binaryExpression, compileResult));
         CompileResult    compileResult3   = new CompileResult();
         compileResult3.CommandText = commandText;
         return(compileResult3);
     }
     if (expr.NodeType == ExpressionType.Call)
     {
         MethodCallExpression methodCallExpression = (MethodCallExpression)expr;
         CompileResult[]      array          = new CompileResult[methodCallExpression.Arguments.Count];
         CompileResult        compileResult4 = (methodCallExpression.Object == null) ? null : CompileExpr(methodCallExpression.Object, queryArgs);
         for (int i = 0; i < array.Length; i++)
         {
             array[i] = CompileExpr(methodCallExpression.Arguments[i], queryArgs);
         }
         string empty = string.Empty;
         empty = ((methodCallExpression.Method.Name == "Like" && array.Length == 2) ? ("(" + array[0].CommandText + " like " + array[1].CommandText + ")") : ((methodCallExpression.Method.Name == "Contains" && array.Length == 2) ? ("(" + array[1].CommandText + " in " + array[0].CommandText + ")") : ((methodCallExpression.Method.Name == "Contains" && array.Length == 1) ? ((methodCallExpression.Object == null || methodCallExpression.Object.Type != typeof(string)) ? ("(" + array[0].CommandText + " in " + compileResult4.CommandText + ")") : ("(" + compileResult4.CommandText + " like ('%' || " + array[0].CommandText + " || '%'))")) : ((methodCallExpression.Method.Name == "StartsWith" && array.Length == 1) ? ("(" + compileResult4.CommandText + " like (" + array[0].CommandText + " || '%'))") : ((methodCallExpression.Method.Name == "EndsWith" && array.Length == 1) ? ("(" + compileResult4.CommandText + " like ('%' || " + array[0].CommandText + "))") : ((methodCallExpression.Method.Name == "Equals" && array.Length == 1) ? ("(" + compileResult4.CommandText + " = (" + array[0].CommandText + "))") : ((methodCallExpression.Method.Name == "ToLower") ? ("(lower(" + compileResult4.CommandText + "))") : ((!(methodCallExpression.Method.Name == "ToUpper")) ? (methodCallExpression.Method.Name.ToLower() + "(" + string.Join(",", (from a in array
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                select a.CommandText).ToArray()) + ")") : ("(upper(" + compileResult4.CommandText + "))")))))))));
         CompileResult compileResult3 = new CompileResult();
         compileResult3.CommandText = empty;
         return(compileResult3);
     }
     if (expr.NodeType == ExpressionType.Constant)
     {
         ConstantExpression constantExpression = (ConstantExpression)expr;
         queryArgs.Add(constantExpression.Value);
         CompileResult compileResult3 = new CompileResult();
         compileResult3.CommandText = "?";
         compileResult3.Value       = constantExpression.Value;
         return(compileResult3);
     }
     if (expr.NodeType == ExpressionType.Convert)
     {
         UnaryExpression unaryExpression = (UnaryExpression)expr;
         Type            type            = unaryExpression.Type;
         CompileResult   compileResult5  = CompileExpr(unaryExpression.Operand, queryArgs);
         CompileResult   compileResult3  = new CompileResult();
         compileResult3.CommandText = compileResult5.CommandText;
         compileResult3.Value       = ((compileResult5.Value == null) ? null : ConvertTo(compileResult5.Value, type));
         return(compileResult3);
     }
     if (expr.NodeType == ExpressionType.Not)
     {
         UnaryExpression unaryExpression2 = (UnaryExpression)expr;
         Type            type2            = unaryExpression2.Type;
         CompileResult   compileResult6   = CompileExpr(unaryExpression2.Operand, queryArgs);
         CompileResult   compileResult3   = new CompileResult();
         compileResult3.CommandText = "NOT " + compileResult6.CommandText;
         compileResult3.Value       = ((compileResult6.Value == null) ? null : compileResult6.Value);
         return(compileResult3);
     }
     if (expr.NodeType == ExpressionType.MemberAccess)
     {
         MemberExpression memberExpression = (MemberExpression)expr;
         CompileResult    compileResult3;
         if (memberExpression.Expression != null && memberExpression.Expression.NodeType == ExpressionType.Parameter)
         {
             string name = Table.FindColumnWithPropertyName(memberExpression.Member.Name).Name;
             compileResult3             = new CompileResult();
             compileResult3.CommandText = "\"" + name + "\"";
             return(compileResult3);
         }
         object obj = null;
         if (memberExpression.Expression != null)
         {
             CompileResult compileResult7 = CompileExpr(memberExpression.Expression, queryArgs);
             if (compileResult7.Value == null)
             {
                 throw new NotSupportedException("Member access failed to compile expression");
             }
             if (compileResult7.CommandText == "?")
             {
                 queryArgs.RemoveAt(queryArgs.Count - 1);
             }
             obj = compileResult7.Value;
         }
         object obj2 = null;
         if (memberExpression.Member.MemberType == MemberTypes.Property)
         {
             PropertyInfo propertyInfo = (PropertyInfo)memberExpression.Member;
             obj2 = propertyInfo.GetGetMethod().Invoke(obj, null);
         }
         else
         {
             if (memberExpression.Member.MemberType != MemberTypes.Field)
             {
                 throw new NotSupportedException("MemberExpr: " + memberExpression.Member.MemberType);
             }
             FieldInfo fieldInfo = (FieldInfo)memberExpression.Member;
             obj2 = fieldInfo.GetValue(obj);
         }
         if (obj2 != null && obj2 is IEnumerable && !(obj2 is string) && !(obj2 is IEnumerable <byte>))
         {
             StringBuilder stringBuilder = new StringBuilder();
             stringBuilder.Append("(");
             string value = string.Empty;
             foreach (object item in (IEnumerable)obj2)
             {
                 queryArgs.Add(item);
                 stringBuilder.Append(value);
                 stringBuilder.Append("?");
                 value = ",";
             }
             stringBuilder.Append(")");
             compileResult3             = new CompileResult();
             compileResult3.CommandText = stringBuilder.ToString();
             compileResult3.Value       = obj2;
             return(compileResult3);
         }
         queryArgs.Add(obj2);
         compileResult3             = new CompileResult();
         compileResult3.CommandText = "?";
         compileResult3.Value       = obj2;
         return(compileResult3);
     }
     throw new NotSupportedException("Cannot compile: " + expr.NodeType.ToString());
 }