コード例 #1
0
ファイル: Program.cs プロジェクト: sixofdloc/sixbasictools
 static void Main(string[] args)
 {
     try
     {
         if (args.Length < 2)
         {
             Console.WriteLine("bas2prg");
             Console.WriteLine("A commandline CBM Basic compiler.");
             Console.WriteLine("By Six/Style 2016-2018");
             Console.WriteLine("usage: bas2prg basfile.bas prgfile.prg");
             Console.WriteLine();
         }
         else
         {
             //var basic = new BASIC();
             var pp               = new PreProcessor();
             var basfile          = File.ReadAllLines(args[0]).ToList();
             var compilerSettings = new CompilerSettings();
             var p     = pp.PreProcess(basfile, ref compilerSettings);
             var bytes = (true) ? SixBASICTokenizer.Tokenize(p, ref compilerSettings) : Tokenizer.Tokenize(p, ref compilerSettings);
             File.WriteAllBytes(args[1], bytes);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
コード例 #2
0
        public CSharpProject(
            ICSharpFileFactory cSharpFileFactory,
            MicrosoftBuildProject msBuildProject,
            string title)
        {
            Title = title;

            AssemblyName = msBuildProject.AssemblyName;
            FileName     = msBuildProject.FileName;

            CompilerSettings =
                #region new CompilerSettings
                new CompilerSettings
            {
                AllowUnsafeBlocks = msBuildProject.AllowUnsafeBlocks,
                CheckForOverflow  = msBuildProject.CheckForOverflowUnderflow,
            };

            CompilerSettings.ConditionalSymbols.AddRange(msBuildProject.DefineConstants);
            #endregion

            ProjectContent = new CSharpProjectContent();
            ProjectContent = ProjectContent.SetAssemblyName(msBuildProject.AssemblyName);
            ProjectContent = ProjectContent.SetProjectFileName(msBuildProject.FileName.FullPath);
            ProjectContent = ProjectContent.SetCompilerSettings(CompilerSettings);

            Files = msBuildProject.CompiledFileNames.Select(
                f => cSharpFileFactory.BuildCSharpFile(this, new FilePath(f))).ToList();

            ProjectContent = ProjectContent.AddOrUpdateFiles(
                Files.Select(f => f.UnresolvedTypeSystemForFile));

            ProjectContent = ProjectContent.AddAssemblyReferences(msBuildProject.ReferencedAssemblies);
        }
コード例 #3
0
ファイル: McsCompiler.cs プロジェクト: kangel429/CodingGame2
        public CompilerResults CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames)
        {
            // Check for null
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            // Get the compiler settings
            CompilerSettings settings = GetSettings(options);

            foreach (string file in fileNames)
            {
                string path = Path.GetFullPath(file);

                // Create a new source unit
                SourceFile unit = new SourceFile(file, path, settings.SourceFiles.Count + 1);

                // Add the source file
                settings.SourceFiles.Add(unit);
            }

            // Call through compile
            return(CompileFromSettings(settings, options.GenerateInMemory));
        }
コード例 #4
0
        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.None;

            CompilerSettings settings = new CompilerSettings();

            settings.CodeSource = SourceCode;
            settings.AddReference("mscorlib.dll");

            CompilerResults results = Mosa.Utility.CodeDomCompiler.Compiler.ExecuteCompiler(settings);

            if (results.Errors.HasErrors)
            {
                tbErrors.Text = string.Empty;

                foreach (CompilerError error in results.Errors)
                {
                    tbErrors.AppendText(error.ToString());
                    tbErrors.AppendText("\n");
                }
            }
            else
            {
                Assembly     = results.PathToAssembly;
                DialogResult = DialogResult.OK;
                Close();
            }
        }
コード例 #5
0
ファイル: McsCompiler.cs プロジェクト: kangel429/CodingGame2
        private CompilerResults CompileFromSettings(CompilerSettings settings, bool generateInMemory)
        {
            // Create the compiler results
            CompilerResults compilerResults = new CompilerResults(new TempFileCollection(Path.GetTempPath()));

            // Create the compiler driver
            McsDriver driver = new McsDriver(new CompilerContext(settings, new McsReporter(compilerResults)));

            AssemblyBuilder outAssembly = null;

            try
            {
                // Try to compile
                driver.Compile(out outAssembly, AppDomain.CurrentDomain, generateInMemory);
            }
            catch (Exception e)
            {
                // Add the exception as an error
                compilerResults.Errors.Add(new CompilerError()
                {
                    IsWarning = false,
                    ErrorText = e.ToString(),
                });
            }

            // Get the compiled assembly
            compilerResults.CompiledAssembly = outAssembly;

            return(compilerResults);
        }
コード例 #6
0
        public CSharpCompiler()
        {
            CompilerSettings settings = new CompilerSettings();
            Report           report   = new Report(new NullReportPrinter());

            evaluator = new Evaluator(settings, report);
        }
コード例 #7
0
        /// <summary>
        /// compile script
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public override bool Compile(string code)
        {
            IsCompiled = false;

            var sourceCode = GetScript(code);

            var compilerSettings = new CompilerSettings
            {
                GenerateDebugInfo = false,
                WarningsAreErrors = false,
                WarningLevel      = 0,
            };

            compilerSettings.AssemblyReferences.AddRange(new[]
            {
                "System.dll",
                "System.Core.dll",
            });

            var errSb = new StringBuilder();

            using (var writer = new StringWriter(errSb))
            {
                var streamReport = new StreamReportPrinter(writer);

                var ctx = new CompilerContext(compilerSettings, streamReport)
                {
                };

                _evaluator = new Evaluator(ctx);

                try
                {
                    var result = _evaluator.Compile(sourceCode);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }

                var errs = errSb.ToString();
                Errors = new List <string>();
                using (var reader = new StringReader(errs))
                {
                    var line = default(string);
                    while ((line = reader.ReadLine()) != null)
                    {
                        Errors.Add(line);
                    }
                }

                if (Errors.Count == 0)
                {
                    Type botFactoryType = (Type)_evaluator.Evaluate($"typeof({typeof(BotFactory).FullName});");
                    IsCompiled = CreateInstance(botFactoryType);
                }
            }

            return(IsCompiled);
        }
コード例 #8
0
        public IController Create(RequestContext requestContext, Type controllerType)
        {
            CompilerSettings settings = new CompilerSettings();
            Report           report   = new Report(new ConsoleReportPrinter());
            Evaluator        eval     = new Evaluator(settings, report);

            object instance        = null;
            bool   instanceCreated = false;

            eval.ReferenceAssembly(typeof(Controller).Assembly);

            foreach (Assembly assembly in assemblies)
            {
                eval.ReferenceAssembly(assembly);
            }

            string controllerName = GetControllerName(requestContext, controllerType);
            string path           = pathProvider.GetPath(requestContext, controllerName);
            CSharpControllerFile controllerFile = CSharpControllerFile.Parse(File.ReadAllText(path));

            eval.Run(controllerFile.ClassSource);
            eval.Evaluate("new " + controllerName + "();", out instance, out instanceCreated);

            return((IController)instance);
        }
コード例 #9
0
		public CSharpProjectContent()
		{
			this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(Platform.FileNameComparer);
			this.assemblyReferences = new List<IAssemblyReference>();
			this.compilerSettings = new CompilerSettings();
			compilerSettings.Freeze();
		}
コード例 #10
0
        public static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: CheeseCake FileName OptionFileName");
                return;
            }

            var sourceFileName = args [0];
            var optionFileName = args [1];

            var policy   = LoadFormattingProfile(optionFileName);
            var options  = LoadTextEditorProfile(optionFileName);
            var settings = new CompilerSettings();

            settings.ConditionalSymbols.Add("UNITY_EDITOR");
            settings.ConditionalSymbols.Add("UNITY_IOS");
            settings.ConditionalSymbols.Add("UNITY_ANDROID");
            var formatter = new CSharpFormatter(policy, options);

            var text     = File.ReadAllText(sourceFileName);
            var document = new StringBuilderDocument(text);

            var syntaxTree = SyntaxTree.Parse(document, document.FileName, settings);
            var changes    = formatter.AnalyzeFormatting(document, syntaxTree);

            changes.ApplyChanges();

            File.WriteAllText(sourceFileName, document.Text, Encoding.UTF8);
        }
コード例 #11
0
ファイル: Mod.cs プロジェクト: ZaRx485/smapi-mod-dump
        private CompiledMethod makeFunc(string userCode)
        {
            var settings = new CompilerSettings()
            {
                Unsafe = true,
            };

            var libs = new List <string>();

            foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    settings.AssemblyReferences.Add(asm.CodeBase);
                }
                catch (Exception e)
                {
                    //Log.trace("Couldn't add assembly " + asm + ": " + e);
                }
            }

            var eval = new Evaluator(new CompilerContext(settings, new ConsoleReportPrinter()));
            var code = @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StardewModdingAPI;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewValley;
using xTile;";

            eval.Compile(code);
            return(eval.Compile("IModHelper Helper = ConsoleCode.Mod.instance.Helper;\n" + userCode));
        }
コード例 #12
0
ファイル: Mod.cs プロジェクト: Pathoschild/smapi-mod-dump
        private CompiledMethod MakeFunc(string userCode)
        {
            var settings = new CompilerSettings
            {
                Unsafe = true
            };

            foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    settings.AssemblyReferences.Add(asm.CodeBase);
                }
                catch
                {
                    //Log.trace("Couldn't add assembly " + asm + ": " + e);
                }
            }

            var eval = new Evaluator(new CompilerContext(settings, new ConsoleReportPrinter()));

            eval.Compile(@"
                using System;
                using System.Collections.Generic;
                using System.Linq;
                using System.Text;
                using StardewModdingAPI;
                using Microsoft.Xna.Framework;
                using Microsoft.Xna.Framework.Graphics;
                using StardewValley;
                using xTile;
            ");
            return(eval.Compile(userCode));
        }
コード例 #13
0
        void Init()
        {
            object res;
            bool   hasRes;

            if (evaluator != null)
            {
                return;
            }

            CompilerSettings settings = new CompilerSettings();
            var context = new CompilerContext(settings, printer);

            evaluator = new Evaluator(context);

            foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
            {
                AddReference(a);
            }

            evaluator.Evaluate("using System;", out res, out hasRes);
            evaluator.Evaluate("using System.Collections.Generic;", out res, out hasRes);
            evaluator.Evaluate("using System.Linq;", out res, out hasRes);
            evaluator.Evaluate("using System.IO;", out res, out hasRes);
            evaluator.Evaluate("using SkiaSharp;", out res, out hasRes);
        }
コード例 #14
0
        private static Evaluator Initialize(StringBuilder builder)
        {
            var settings  = new CompilerSettings();
            var writer    = new StringWriter(builder);
            var printer   = new StreamReportPrinter(writer);
            var context   = new CompilerContext(settings, printer);
            var evaluator = new Evaluator(context)
            {
                InteractiveBaseClass    = typeof(Interactive),
                DescribeTypeExpressions = true
            };

            evaluator.ReferenceAssembly(typeof(CSharpEvaluator).Assembly);
            foreach (var assembly in AssemblyLoader.NewAssemblies)
            {
                evaluator.ReferenceAssembly(assembly);
            }

            var nameSpaces = new[]
            {
                "System",
                "System.Linq",
                "System.Linq.Expressions",
                "System.Collections.Generic"
            }.Concat(InteractiveSection.Namespaces.Select(n => n.Namespace));

            foreach (var nameSpace in nameSpaces)
            {
                evaluator.Run(string.Format("using {0};", nameSpace));
            }
            return(evaluator);
        }
コード例 #15
0
        void Update()
        {
            if (evaluator == null)
            {
                instance = this;
                CompilerSettings cs = new CompilerSettings();
                cs.AssemblyReferences = (new string[] { "System.dll", "System.Core.dll", "Assembly-CSharp.dll", "Assembly-CSharp-firstpass.dll", "UnityEngine.dll", "KSPPP.dll" }).ToList();
                //cs.Version = LanguageVersion.V_3;
                evaluator = new Evaluator(new CompilerContext(cs, new NewDelegateReportPrinter(Log)));
                evaluator.ReferenceAssembly(Assembly.GetCallingAssembly());

                /*
                 * foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                 * {
                 * console += "Loading assembly: " + a.FullName + "\n";
                 * evaluator.ReferenceAssembly(a);
                 * }
                 */

                if (File.Exists(KSP.IO.IOUtils.GetFilePathFor(typeof(NewEmbeddedCSharp), "autorun.cs")))
                {
                    code = File.ReadAllText(KSP.IO.IOUtils.GetFilePathFor(typeof(NewEmbeddedCSharp), "autorun.cs"));
                }
            }
            if (Input.GetKeyDown(hotkey))
            {
                Visible = !Visible;
            }
            //if (Input.GetKeyDown(KeyCode.Alpha8) && (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))) { hidden = !hidden; }
        }
コード例 #16
0
ファイル: context.cs プロジェクト: wskjava/SharpDevelop
 public CompilerContext(CompilerSettings settings, ReportPrinter reportPrinter)
 {
     this.settings      = settings;
     this.report        = new Report(this, reportPrinter);
     this.builtin_types = new BuiltinTypes();
     this.TimeReporter  = DisabledTimeReporter;
 }
コード例 #17
0
ファイル: MonoScriptSession.cs プロジェクト: samvik/cake
        public MonoScriptSession(IScriptHost host, ICakeLog log)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            _log = log;

            // Create the evaluator.
            var compilerSettings = new CompilerSettings();
            var reportPrinter    = new MonoConsoleReportPrinter(_log);
            var compilerContext  = new CompilerContext(compilerSettings, reportPrinter);

            _evaluator = new Evaluator(compilerContext);

            // Set our instance of the script host to this static member
            MonoScriptHostProxy.ScriptHost = host;

            // This will be our 'base' type from which the evaluator grants access
            // to static members to the script being run
            _evaluator.InteractiveBaseClass = typeof(MonoScriptHostProxy);
        }
コード例 #18
0
ファイル: EvaluatorFixture.cs プロジェクト: pmq20/mono_forked
        public void Setup()
        {
            settings = new CompilerSettings();
            var ctx = new CompilerContext(settings, new AssertReportPrinter());

            evaluator = new Evaluator(ctx);
        }
コード例 #19
0
ファイル: DurangoPlatform.cs プロジェクト: Vazquinhos/EXON
            public override void AddCompilerSettings(
                IDictionary <string, CompilerSettings> masterCompilerSettings,
                string compilerName,
                string rootPath,
                DevEnv devEnv,
                string projectRootPath
                )
            {
                switch (devEnv)
                {
                case DevEnv.vs2012:
                {
                    CompilerSettings compilerSettings = GetMasterCompilerSettings(masterCompilerSettings, compilerName, rootPath, devEnv, projectRootPath, false);
                    compilerSettings.PlatformFlags |= Platform.durango;
                    SetConfiguration(compilerSettings.Configurations, string.Empty, projectRootPath, devEnv, false);
                }
                break;

                case DevEnv.vs2015:
                case DevEnv.vs2017:
                {
                    var win64PlatformSettings = PlatformRegistry.Get <IPlatformBff>(Platform.win64);

                    string           overrideName     = "Compiler-" + Sharpmake.Util.GetSimplePlatformString(Platform.win64) + "-" + devEnv;
                    CompilerSettings compilerSettings = win64PlatformSettings.GetMasterCompilerSettings(masterCompilerSettings, overrideName, rootPath, devEnv, projectRootPath, false);
                    compilerSettings.PlatformFlags |= Platform.durango;
                    SetConfiguration(compilerSettings.Configurations, string.Empty, projectRootPath, devEnv, false);
                }
                break;

                default:
                    throw new NotImplementedException("This devEnv (" + devEnv + ") is not supported!");
                }
            }
コード例 #20
0
            public override void AddCompilerSettings(
                IDictionary <string, CompilerSettings> masterCompilerSettings,
                string compilerName,
                string rootPath,
                DevEnv devEnv,
                string projectRootPath
                )
            {
                var fastBuildCompilerSettings = PlatformRegistry.Get <IWindowsFastBuildCompilerSettings>(Platform.win64);

                if (!fastBuildCompilerSettings.BinPath.ContainsKey(devEnv))
                {
                    fastBuildCompilerSettings.BinPath.Add(devEnv, devEnv.GetVisualStudioBinPath(Platform.win64));
                }
                if (!fastBuildCompilerSettings.LinkerPath.ContainsKey(devEnv))
                {
                    fastBuildCompilerSettings.LinkerPath.Add(devEnv, fastBuildCompilerSettings.BinPath[devEnv]);
                }
                if (!fastBuildCompilerSettings.ResCompiler.ContainsKey(devEnv))
                {
                    fastBuildCompilerSettings.ResCompiler.Add(devEnv, devEnv.GetWindowsResourceCompiler(Platform.win64));
                }

                CompilerSettings compilerSettings = GetMasterCompilerSettings(masterCompilerSettings, compilerName, rootPath, devEnv, projectRootPath, false);

                compilerSettings.PlatformFlags |= Platform.win64;
                SetConfiguration(compilerSettings.Configurations, string.Empty, projectRootPath, devEnv, false);
            }
コード例 #21
0
        private void initEvalEngine()
        {
            if (mEngine == null)
            {
                // Initialize the expression evaluator
                mEngineReport = new StringBuilder();
                var writer       = new StringWriter(mEngineReport);
                var printer      = new StreamReportPrinter(writer);
                var evalSettings = new CompilerSettings();
                evalSettings.AssemblyReferences.Add("Recomedia_de.Logic.VisuWeb.dll");
                var evalContext = new CompilerContext(evalSettings, new StreamReportPrinter(writer));
                mEngine = new Evaluator(evalContext);

                // Using supported namespaces
                mEngine.Run("using System;" + Environment.NewLine +
                            "using Recomedia_de.Logic.VisuWeb;");

                // Declare all variables we will ever use
                string declText = getVariableDecls();
                mEngine.Run(declText);

                // After we declared all needed variables is the time to get access to
                // them for later field updates
                const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
                FieldInfo          fieldInfo    = typeof(Evaluator).GetField("fields", bindingFlags);
                mFields = fieldInfo.GetValue(mEngine) as FieldDictionary;

                // Start with nulled compiled expressions (lazy-init in Execute)
                mCompiled = new List <CompiledMethod>(
                    Enumerable.Repeat <CompiledMethod>(null, mOutputs.Count));
            }
        }
コード例 #22
0
ファイル: CreateHarmonyDlls.cs プロジェクト: blipvert/DMT
        public override bool Patch(PatchData data)
        {
            var mods = data.GetHarmonyMods();

            foreach (var mod in mods)
            {
                CompilerSettings compilerSettings = new CompilerSettings();
                LogInternal($"Compiling Harmony mod for {mod.Name}...");

                var scriptPaths = mod.FindFiles("Harmony", "*.cs", true);

                for (int i = 0; i < scriptPaths.Count; ++i)
                {
                    compilerSettings.Files.Add(scriptPaths[i]);
                }

                var startPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
                compilerSettings.AddReference("DMT.dll");
                compilerSettings.AddReference(startPath + "/0Harmony.dll");

                var filename = $"Harmony-{mod.Name.MakeSafeFilename()}.dll";
                compilerSettings.OutputPath = mod.Location + "/Harmony/" + filename;

                var dllRefs = Directory.GetFiles(data.ManagedFolder, "*.dll").Where(d => !d.EndsWith("/Mods.dll")).ToArray();
                compilerSettings.AddReferences(dllRefs);

                var modsDll = $"{data.BuildFolder}Mods.dll";
                compilerSettings.AddReferenceAtIndex(modsDll, 0);

                var dllPaths = mod.FindFiles("Harmony", "*.dll", true);
                for (int i = 0; i < dllPaths.Count; ++i)
                {
                    var dllPath = dllPaths[i];
                    if (Path.GetFullPath(compilerSettings.OutputPath) == Path.GetFullPath(dllPath))
                    {
                        //Logging.Log("Ignoring harmony DLL: " + Path.GetFileName(dllPath));
                        continue; //can't reference self as we're building the DLL
                    }

                    compilerSettings.AddReference(dllPath);
                }

                var compilerResults = data.Compiler.Compile(data, compilerSettings);
                // Logging.LogInfo($"Built in {compilerResults.Duration}ms");

                if (!compilerResults.Success)
                {
                    for (int i = 0; i < compilerResults.Errors.Count; ++i)
                    {
                        LogWarning(compilerResults.Errors[i]);
                    }
                    LogError("Failed to compile Harmony dll " + filename);
                    return(false);
                }

                // Log("Harmony dll compile successful");
            }

            return(true);
        }
コード例 #23
0
            private CompilerSettings GetMasterCompilerSettings(
                IDictionary <string, CompilerSettings> masterCompilerSettings,
                string compilerName,
                string rootPath,
                DevEnv devEnv,
                string projectRootPath,
                bool useCCompiler
                )
            {
                CompilerSettings compilerSettings;

                if (masterCompilerSettings.ContainsKey(compilerName))
                {
                    compilerSettings = masterCompilerSettings[compilerName];
                }
                else
                {
                    var     fastBuildCompilerSettings = PlatformRegistry.Get <IFastBuildCompilerSettings>(Platform.durango);
                    Strings extraFiles;
                    if (!fastBuildCompilerSettings.ExtraFiles.TryGetValue(devEnv, out extraFiles))
                    {
                        extraFiles = new Strings();
                    }
                    string executable;

                    switch (devEnv)
                    {
                    case DevEnv.vs2012:
                    {
                        extraFiles.Add(
                            @"$ExecutableRootPath$\c1.dll",
                            @"$ExecutableRootPath$\c1xx.dll",
                            @"$ExecutableRootPath$\c1xxast.dll",
                            @"$ExecutableRootPath$\c2.dll",
                            @"$ExecutableRootPath$\msobj110.dll",
                            @"$ExecutableRootPath$\mspdb110.dll",
                            @"$ExecutableRootPath$\mspdbcore.dll",
                            @"$ExecutableRootPath$\mspdbsrv.exe",
                            @"$ExecutableRootPath$\mspft110.dll",
                            @"$ExecutableRootPath$\1033\clui.dll",
                            @"$ExecutableRootPath$\msvcp110.dll",
                            @"$ExecutableRootPath$\msvcr110.dll",
                            @"$ExecutableRootPath$\vccorlib110.dll");

                        executable = @"$ExecutableRootPath$\cl.exe";
                        fastBuildCompilerSettings.BinPath.TryGetValue(devEnv, out rootPath);
                    }
                    break;

                    default:
                        throw new NotImplementedException("This devEnv (" + devEnv + ") is not supported!");
                    }

                    compilerSettings = new CompilerSettings(compilerName, Platform.durango, extraFiles, executable, rootPath, devEnv, new Dictionary <string, CompilerSettings.Configuration>());
                    masterCompilerSettings.Add(compilerName, compilerSettings);
                }

                return(compilerSettings);
            }
コード例 #24
0
        private static CompilerSettings MapSettings(CompilerOptions options, string outputAssemblyPath, string outputDocFilePath, IErrorReporter er)
        {
            var allPaths = options.AdditionalLibPaths.Concat(new[] { Environment.CurrentDirectory }).ToList();

            var result = new CompilerSettings {
                Target                    = (options.HasEntryPoint ? Target.Exe : Target.Library),
                Platform                  = Platform.AnyCPU,
                TargetExt                 = (options.HasEntryPoint ? ".exe" : ".dll"),
                MainClass                 = options.EntryPointClass,
                VerifyClsCompliance       = false,
                Optimize                  = false,
                Version                   = LanguageVersion.V_5,
                EnhancedWarnings          = false,
                LoadDefaultReferences     = false,
                TabSize                   = 1,
                WarningsAreErrors         = options.TreatWarningsAsErrors,
                FatalCounter              = 100,
                WarningLevel              = options.WarningLevel,
                AssemblyReferences        = options.References.Where(r => r.Alias == null).Select(r => ResolveReference(r.Filename, allPaths, er)).ToList(),
                AssemblyReferencesAliases = options.References.Where(r => r.Alias != null).Select(r => Tuple.Create(r.Alias, ResolveReference(r.Filename, allPaths, er))).ToList(),
                Encoding                  = Encoding.UTF8,
                DocumentationFile         = !string.IsNullOrEmpty(options.DocumentationFile) ? outputDocFilePath : null,
                OutputFile                = outputAssemblyPath,
                AssemblyName              = GetAssemblyName(options),
                StdLib                    = false,
                StdLibRuntimeVersion      = RuntimeVersion.v4,
                StrongNameKeyContainer    = options.KeyContainer,
                StrongNameKeyFile         = options.KeyFile,
            };

            result.SourceFiles.AddRange(options.SourceFiles.Select((f, i) => new SourceFile(f, f, i + 1)));
            foreach (var c in options.DefineConstants)
            {
                result.AddConditionalSymbol(c);
            }
            foreach (var w in options.DisabledWarnings)
            {
                result.SetIgnoreWarning(w);
            }
            result.SetIgnoreWarning(660);               // 660 and 661: class defines operator == or operator != but does not override Equals / GetHashCode. These warnings don't really apply, since we have no Equals / GetHashCode methods to override.
            result.SetIgnoreWarning(661);
            foreach (var w in options.WarningsAsErrors)
            {
                result.AddWarningAsError(w);
            }
            foreach (var w in options.WarningsNotAsErrors)
            {
                result.AddWarningOnly(w);
            }

            if (result.AssemblyReferencesAliases.Count > 0)                     // NRefactory does currently not support reference aliases, this check will hopefully go away in the future.
            {
                er.Region = DomRegion.Empty;
                er.Message(7998, "aliased reference");
            }

            return(result);
        }
コード例 #25
0
        private CompilerSettings GetSettings(CompilerParameters parameters)
        {
            CompilerSettings settings = new CompilerSettings();

            // Reset parameter output

            // Copy references
            foreach (string assembly in parameters.ReferencedAssemblies)
            {
                settings.AssemblyReferences.Add(assembly);
            }

            settings.Encoding             = Encoding.UTF8;
            settings.GenerateDebugInfo    = parameters.IncludeDebugInformation;
            settings.MainClass            = parameters.MainClass;
            settings.Platform             = Platform.AnyCPU;
            settings.StdLibRuntimeVersion = RuntimeVersion.v4;

            // Store the type - We need to do some hacky stuff here because Unity copied the Mono.CSharp.Target enum which caused duplication errors.
            // Normally this can be fixed by creating a reference alias but since Unity also manages the .csproj file this will not work
            FieldInfo field = typeof(CompilerSettings).GetField("Target");

            // Target settings
            if (parameters.GenerateExecutable == true)
            {
                //settings.Target = Target.Exe;         // The type 'Target' exists in 2 assemblies
                SetTargetEnumField(field, settings, MCSTarget.Exe);
                settings.TargetExt = ".exe";
            }
            else
            {
                //settings.Target = Target.Library;     // The type 'Target' exists in 2 assemblies
                SetTargetEnumField(field, settings, MCSTarget.Library);
                settings.TargetExt = ".dll";
            }

            // Target location
            if (parameters.GenerateInMemory == true)
            {
                SetTargetEnumField(field, settings, MCSTarget.Library);
            }
            //settings.Target = Target.Library;     // The type 'Target' exists in 2 assemblies

            // Generate a name for the output
            {
                parameters.OutputAssembly = settings.OutputFile = Path.Combine(outputDirectory, "DynamicAssembly_" + assemblyCounter + settings.TargetExt);
                assemblyCounter++;
            }

            settings.OutputFile        = parameters.OutputAssembly;
            settings.GenerateDebugInfo = generateSymbols;
            settings.Version           = LanguageVersion.Default;
            settings.WarningLevel      = parameters.WarningLevel;
            settings.WarningsAreErrors = parameters.TreatWarningsAsErrors;
            settings.Optimize          = false;

            return(settings);
        }
コード例 #26
0
    public void TestCompiled(int milliseconds)
    {
        CompilerSettings cts = new CompilerSettings();

        cts.Unsafe = true;
        CompilerContext ctx = new CompilerContext(cts, new ConsoleReportPrinter());
        Evaluator       ev  = new Evaluator(ctx);

        // ------------------------------------------------------------------------------------------------------------
        // A compiled expression will be simple sealed as a function.
        // THis method is parameterless.
        // ------------------------------------------------------------------------------------------------------------

        Stopwatch st = new Stopwatch();

        st.Reset();
        st.Start();

        const string evClassDef =
            @"
            public class EVTest
            {
                public int Add(int a, int b)
                {
                    return a + b;
                }
            }
        ";

        const string evExpression = @"new EVTest();";

        // Notice this is not C# itself, it is an REPL style C#.
        // This command will "import" this class to ev's execution context.
        ev.Run(evClassDef);

        // Looks like holding the returning object...
        CompiledMethod res = ev.Compile(evExpression);

        // This will obviously not cause memory leak...
        while (st.ElapsedMilliseconds <= milliseconds)
        {
            object evtest = null;
            res.Invoke(ref evtest);
            int ans = (int)evtest.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, evtest, new object[] { 1, 2 });
            Debug.Assert(ans == 1 + 2);
        }

        // 64MB memory limitation.
        const int bytesLimit = 1 << 26;

        using (var proc = Process.GetCurrentProcess())
        {
            Debug.Assert(Process.GetCurrentProcess().PrivateMemorySize64 <= bytesLimit);
        }

        Console.WriteLine("Test.Compile Finished.");
    }
コード例 #27
0
        public override bool Patch(PatchData data)
        {
            LogInternal("Compiling Mods.dll...");

            CompilerSettings compilerSettings = new CompilerSettings();

            compilerSettings.OutputPath = data.ModsDllTempLocation;

            var scriptPaths = data.FindFiles("Scripts", "*.cs", true);

            for (int i = 0; i < scriptPaths.Count; ++i)
            {
                compilerSettings.Files.Add(scriptPaths[i]);
            }
            var sdxfakeFile = @"namespace SDX.Compiler { public class SDXCompilerWrapper {} } namespace SDX { public class SDXWrapper {} } namespace SDX.Core { public class SDXCoreWrapper {} } namespace SDX.Payload { public class SDXPayloadWrapper {} }";
            var sdxtempPath = (data.BuildFolder + "BlankClass.cs").Replace("/", "\\");

            File.WriteAllText(sdxtempPath, sdxfakeFile);
            compilerSettings.Files.Add(sdxtempPath);


            compilerSettings.AddReference("DMT.dll");
            var dllRefs = Directory.GetFiles(data.ManagedFolder, "*.dll").Where(d => d.EndsWith("/Mods.dll") == false && d.Contains("Assembly-CSharp") == false).ToArray();

            compilerSettings.AddReferences(dllRefs);

            var patchedDll = $"{data.BuildFolder}InitialPatch.dll";

            compilerSettings.AddReferenceAtIndex(patchedDll, 0);

            var dllPaths = data.FindFiles("Scripts", "*.dll", true);

            for (int i = 0; i < dllPaths.Count; ++i)
            {
                compilerSettings.AddReference(dllPaths[i]);
                Logging.LogInfo($"Copy file {dllPaths[i]} -> {data.ManagedFolder}");
                Helper.CopyFileToDir(dllPaths[i], data.ManagedFolder);
            }

            var compilerResults = data.Compiler.Compile(data, compilerSettings);

            Logging.LogInfo($"Built in {compilerResults.Duration}ms");

            if (compilerResults.Success == false)
            {
                for (int i = 0; i < compilerResults.Errors.Count; ++i)
                {
                    LogWarning(compilerResults.Errors[i]);
                }
                LogError("Failed to compile Mods.dll");
                return(false);
            }

            Log("Mods.dll compile successful");
            return(true);
        }
コード例 #28
0
 protected VSharpProjectContent(VSharpProjectContent pc)
 {
     this.assemblyName       = pc.assemblyName;
     this.fullAssemblyName   = pc.fullAssemblyName;
     this.projectFileName    = pc.projectFileName;
     this.location           = pc.location;
     this.unresolvedFiles    = new Dictionary <string, IUnresolvedFile>(pc.unresolvedFiles, Base.Platform.FileNameComparer);
     this.assemblyReferences = new List <IAssemblyReference>(pc.assemblyReferences);
     this.compilerSettings   = pc.compilerSettings;
 }
コード例 #29
0
		protected CSharpProjectContent(CSharpProjectContent pc)
		{
			this.assemblyName = pc.assemblyName;
			this.fullAssemblyName = pc.fullAssemblyName;
			this.projectFileName = pc.projectFileName;
			this.location = pc.location;
			this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(pc.unresolvedFiles, Platform.FileNameComparer);
			this.assemblyReferences = new List<IAssemblyReference>(pc.assemblyReferences);
			this.compilerSettings = pc.compilerSettings;
		}
コード例 #30
0
        public CSharpProject(CSharpSolution solution, string title, string fileName)
        {
            Files            = new List <CSharpFile>();
            CompilerSettings = new CompilerSettings();
            Solution         = solution;
            Title            = title;
            FileName         = fileName;

            LoadCSharpProject(solution, fileName);
        }
コード例 #31
0
        /// <summary>
        /// 从旧的脚本加载
        /// </summary>
        public void Load(string script)
        {
            CompilerSettings setting = new CompilerSettings();

            setting.LanguageVersion = new System.Version(2, 0, 0, 0);
            CSharpParser cpaser = new CSharpParser(setting);

            tree        = cpaser.Parse(script);
            firstCreate = false;
        }
コード例 #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CompilerContext"/> class with a parent context
 /// </summary>
 /// <param name="view">The type for the context</param>
 /// <param name="sourceData">The source expression for the type</param>
 /// <param name="compilerSettings">The compilation settings</param>
 /// <param name="partialLoader">A loader for partial templates</param>
 /// <param name="settings">The compilation settings for the compiler</param>
 /// <param name="parentContext">The parent context for the new context</param>
 public CompilerContext(Type view, Expression sourceData, CompilerSettings compilerSettings, IStubbleLoader partialLoader, CompilationSettings settings, CompilerContext parentContext)
     : base(partialLoader, parentContext)
 {
     CompilerSettings    = compilerSettings;
     CompilationSettings = settings;
     View       = view;
     SourceData = sourceData;
     cache      = new Dictionary <string, Expression>()
     {
         { ".", sourceData }
     };
 }
コード例 #33
0
ファイル: CSharpParser.cs プロジェクト: 0xb1dd1e/NRefactory
		public CSharpParser(CompilerSettings args)
		{
			compilerSettings = args ?? new CompilerSettings();
		}
コード例 #34
0
ファイル: CSharpParser.cs プロジェクト: 0xb1dd1e/NRefactory
		public CSharpParser()
		{
			compilerSettings = new CompilerSettings();
		}
コード例 #35
0
		public CSharpParser (CompilerSettings args)
		{
			CompilerSettings = args;
		}
コード例 #36
0
		public CSharpParser ()
		{
			CompilerSettings = new CompilerSettings ();
			CompilerSettings.Unsafe = true;
		}
コード例 #37
0
        public PeWriter(CompilerSettings settings)
            : base(settings)
        {

        }