Esempio n. 1
0
        public void DeleteUnusedAssemblies()
        {
            string text = Path.Combine(Path.GetDirectoryName(Application.dataPath), EditorCompilation.EditorAssemblyPath);

            if (Directory.Exists(text))
            {
                List <string> list = new List <string>(Directory.GetFiles(text));
                list.Remove(Path.Combine(Path.GetDirectoryName(Application.dataPath), EditorCompilation.AssemblyTimestampPath));
                ScriptAssembly[] allScriptAssemblies = this.GetAllScriptAssemblies(BuildFlags.BuildingForEditor, EditorScriptCompilationOptions.BuildingForEditor);
                ScriptAssembly[] array = allScriptAssemblies;
                for (int i = 0; i < array.Length; i++)
                {
                    ScriptAssembly scriptAssembly = array[i];
                    if (scriptAssembly.Files.Length > 0)
                    {
                        string text2 = Path.Combine(text, scriptAssembly.Filename);
                        list.Remove(text2);
                        list.Remove(EditorCompilation.MDBPath(text2));
                        list.Remove(EditorCompilation.PDBPath(text2));
                    }
                }
                foreach (string current in list)
                {
                    File.Delete(current);
                }
            }
        }
Esempio n. 2
0
 private static void CopyAssembly(string sourcePath, string destinationPath)
 {
     if (EditorCompilation.MoveOrReplaceFile(sourcePath, destinationPath))
     {
         string text  = EditorCompilation.MDBPath(sourcePath);
         string text2 = EditorCompilation.MDBPath(destinationPath);
         if (File.Exists(text))
         {
             EditorCompilation.MoveOrReplaceFile(text, text2);
         }
         else if (File.Exists(text2))
         {
             File.Delete(text2);
         }
         string text3 = EditorCompilation.PDBPath(sourcePath);
         string text4 = EditorCompilation.PDBPath(destinationPath);
         if (File.Exists(text3))
         {
             EditorCompilation.MoveOrReplaceFile(text3, text4);
         }
         else if (File.Exists(text4))
         {
             File.Delete(text4);
         }
     }
 }
            public static void PostProcess(ref CompilerMessage message, EditorCompilation editorCompilation)
            {
                if (!message.message.Contains("CS0227"))
                {
                    return;
                }

                var customScriptAssembly = CustomScriptAssemblyFor(message, editorCompilation);

                var unityUnsafeMessage = customScriptAssembly != null
                    ? $"Enable \"Allow 'unsafe' code\" in the inspector for '{customScriptAssembly.FilePath}' to fix this error."
                    : "Enable \"Allow 'unsafe' code\" in Player Settings to fix this error.";

                message.message += $". {unityUnsafeMessage}";
            }
Esempio n. 4
0
 private static void CheckCyclicAssemblyReferences(CustomScriptAssembly[] customScriptAssemblies)
 {
     if (customScriptAssemblies != null && customScriptAssemblies.Length >= 2)
     {
         Dictionary <string, CustomScriptAssembly> dictionary = new Dictionary <string, CustomScriptAssembly>();
         for (int i = 0; i < customScriptAssemblies.Length; i++)
         {
             CustomScriptAssembly customScriptAssembly = customScriptAssemblies[i];
             dictionary[customScriptAssembly.Name] = customScriptAssembly;
         }
         HashSet <CustomScriptAssembly> visited = new HashSet <CustomScriptAssembly>();
         for (int j = 0; j < customScriptAssemblies.Length; j++)
         {
             CustomScriptAssembly visitAssembly = customScriptAssemblies[j];
             EditorCompilation.CheckCyclicAssemblyReferencesDFS(visitAssembly, visited, dictionary);
         }
     }
 }
Esempio n. 5
0
        public void SetAllCustomScriptAssemblyJsons(string[] paths)
        {
            List <CustomScriptAssembly> list = new List <CustomScriptAssembly>();

            for (int i = 0; i < paths.Length; i++)
            {
                string text = paths[i];
                try
                {
                    string path = (!Path.IsPathRooted(text)) ? Path.Combine(this.projectDirectory, text) : text;
                    CustomScriptAssembly loadedCustomScriptAssembly = EditorCompilation.LoadCustomScriptAssemblyFromJson(path);
                    if (list.Any((CustomScriptAssembly a) => string.Equals(a.Name, loadedCustomScriptAssembly.Name, StringComparison.OrdinalIgnoreCase)))
                    {
                        throw new Exception(string.Format("Assembly with name '{0}' is already defined ({1})", loadedCustomScriptAssembly.Name.Length, loadedCustomScriptAssembly.FilePath));
                    }
                    if (loadedCustomScriptAssembly.References == null)
                    {
                        loadedCustomScriptAssembly.References = new string[0];
                    }
                    if (loadedCustomScriptAssembly.References.Length != loadedCustomScriptAssembly.References.Distinct <string>().Count <string>())
                    {
                        throw new Exception(string.Format("Duplicate assembly references in {0}", loadedCustomScriptAssembly.FilePath));
                    }
                    list.Add(loadedCustomScriptAssembly);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message + " - '" + text + "'");
                }
            }
            this.customScriptAssemblies = list.ToArray();
            try
            {
                EditorCompilation.CheckCyclicAssemblyReferences(this.customScriptAssemblies);
            }
            catch (Exception ex2)
            {
                this.customScriptAssemblies = null;
                this.customTargetAssemblies = null;
                throw ex2;
            }
            this.customTargetAssemblies = EditorBuildRules.CreateTargetAssemblies(this.customScriptAssemblies);
        }
Esempio n. 6
0
 private static void CheckCyclicAssemblyReferencesDFS(CustomScriptAssembly visitAssembly, HashSet <CustomScriptAssembly> visited, IDictionary <string, CustomScriptAssembly> nameToCustomScriptAssembly)
 {
     if (visited.Contains(visitAssembly))
     {
         throw new Exception(string.Format("Cyclic assembly references detected. Assemblies: {0}", string.Join(", ", (from a in visited
                                                                                                                      select string.Format("'{0}'", a.Name)).ToArray <string>())));
     }
     visited.Add(visitAssembly);
     string[] references = visitAssembly.References;
     for (int i = 0; i < references.Length; i++)
     {
         string text = references[i];
         CustomScriptAssembly visitAssembly2;
         if (!nameToCustomScriptAssembly.TryGetValue(text, out visitAssembly2))
         {
             throw new Exception(string.Format("Reference to non-existent assembly. Assembly {0} has a reference to {1}", visitAssembly.Name, text));
         }
         EditorCompilation.CheckCyclicAssemblyReferencesDFS(visitAssembly2, visited, nameToCustomScriptAssembly);
     }
     visited.Remove(visitAssembly);
 }
Esempio n. 7
0
 public static BeeDriver Make(RunnableProgram buildProgram, EditorCompilation editorCompilation, string dagName, string dagDirectory = null, bool useScriptUpdater = true)
 {
     return(Make(buildProgram, dagName, dagDirectory, useScriptUpdater, editorCompilation.projectDirectory));
 }
Esempio n. 8
0
        public static void AddScriptCompilationData(BeeDriver beeDriver,
                                                    EditorCompilation editorCompilation,
                                                    ScriptAssembly[] assemblies,
                                                    bool debug,
                                                    string outputDirectory,
                                                    BuildTarget buildTarget,
                                                    bool buildingForEditor,
                                                    string[] extraScriptingDefines = null)
        {
            // Need to call AssemblyDataFrom before calling CompilationPipeline.GetScriptAssemblies,
            // as that acts on the same ScriptAssemblies, and modifies them with different build settings.
            var cachedAssemblies = AssemblyDataFrom(assemblies);

            AssemblyData[] codeGenAssemblies;
            using (new ProfilerMarker("GetScriptAssembliesForCodeGen").Auto())
            {
                codeGenAssemblies = buildingForEditor
                    ? null
                    : AssemblyDataFrom(CodeGenAssemblies(CompilationPipeline.GetScriptAssemblies(editorCompilation, AssembliesType.Editor, extraScriptingDefines)));
            }

            var movedFromExtractorPath = EditorApplication.applicationContentsPath + $"/Tools/ScriptUpdater/ApiUpdater.MovedFromExtractor.exe";
            var dotNetSdkRoslynPath    = EditorApplication.applicationContentsPath + $"/DotNetSdkRoslyn";

            var localization = "en-US";

            if (LocalizationDatabase.currentEditorLanguage != SystemLanguage.English && EditorPrefs.GetBool("Editor.kEnableCompilerMessagesLocalization", false))
            {
                localization = LocalizationDatabase.GetCulture(LocalizationDatabase.currentEditorLanguage);
            }


            var assembliesToScanForTypeDB = new HashSet <string>();
            var searchPaths = new HashSet <string>(BuildPlayerDataGenerator.GetStaticSearchPaths(buildTarget));
            var options     = EditorScriptCompilationOptions.BuildingIncludingTestAssemblies;

            if (buildingForEditor)
            {
                options |= EditorScriptCompilationOptions.BuildingForEditor;
            }
            foreach (var a in editorCompilation.GetAllScriptAssemblies(options, extraScriptingDefines))
            {
                if (!a.Flags.HasFlag(AssemblyFlags.EditorOnly))
                {
                    var path = a.FullPath.ToNPath();
                    assembliesToScanForTypeDB.Add(path.ToString());
                    searchPaths.Add(path.Parent.ToString());
                }
            }

            var precompileAssemblies = editorCompilation.PrecompiledAssemblyProvider.GetPrecompiledAssembliesDictionary(
                buildingForEditor,
                BuildPipeline.GetBuildTargetGroup(buildTarget),
                buildTarget,
                extraScriptingDefines);

            if (precompileAssemblies != null)
            {
                foreach (var a in precompileAssemblies)
                {
                    if (!a.Value.Flags.HasFlag(AssemblyFlags.EditorOnly))
                    {
                        var path = a.Value.Path.ToNPath();
                        assembliesToScanForTypeDB.Add(path.ToString());
                        searchPaths.Add(path.Parent.ToString());
                    }
                }
            }

            beeDriver.DataForBuildProgram.Add(new ScriptCompilationData
            {
                OutputDirectory        = outputDirectory,
                DotnetRuntimePath      = NetCoreProgram.DotNetRuntimePath.ToString(),
                DotnetRoslynPath       = dotNetSdkRoslynPath,
                MovedFromExtractorPath = movedFromExtractorPath,
                Assemblies             = cachedAssemblies,
                CodegenAssemblies      = codeGenAssemblies,
                Debug                           = debug,
                BuildTarget                     = buildTarget.ToString(),
                Localization                    = localization,
                EnableDiagnostics               = editorCompilation.EnableDiagnostics,
                BuildPlayerDataOutput           = $"Library/BuildPlayerData/{(buildingForEditor ? "Editor" : "Player")}",
                ExtractRuntimeInitializeOnLoads = !buildingForEditor,
                AssembliesToScanForTypeDB       = assembliesToScanForTypeDB.OrderBy(p => p).ToArray(),
                SearchPaths                     = searchPaths.OrderBy(p => p).ToArray()
            });
        }
Esempio n. 9
0
        /// <summary>
        /// the returned array of compiler messages corresponds to the input array of noderesult. Each node result can result in 0,1 or more compilermessages.
        /// We return them as an array of arrays, so on the caller side you're still able to map a compilermessage to the noderesult where it originated from,
        /// which we need when invoking per assembly compilation callbacks.
        /// </summary>
        public static CompilerMessage[][] ParseAllResultsIntoCompilerMessages(BeeDriverResult.Message[] beeDriverMessages, NodeResult[] nodeResults, EditorCompilation editorCompilation)
        {
            // If there's any messages from the bee driver, we add one additional array to the result which contains all of the driver messages converted and augmented like the nodes messages arrays.
            bool hasBeeDriverMessages = beeDriverMessages.Length > 0;
            var  result = new CompilerMessage[nodeResults.Length + (hasBeeDriverMessages ? 1 : 0)][];

            int resultIndex = 0;

            if (hasBeeDriverMessages)
            {
                result[resultIndex] = beeDriverMessages.Select(AsCompilerMessage).ToArray();
                ++resultIndex;
            }
            for (int i = 0; i != nodeResults.Length; i++)
            {
                result[resultIndex] = ParseCompilerOutput(nodeResults[i]);
                ++resultIndex;
            }

            //To be more kind to performance issues in situations where there are thousands of compiler messages, we're going to assume
            //that after the first 10 compiler error messages, we get very little benefit from augmenting the rest with higher quality unity specific messaging.
            int totalErrors         = 0;
            int nextResultToAugment = 0;

            while (totalErrors < 10 && nextResultToAugment < result.Length)
            {
                UnitySpecificCompilerMessages.AugmentMessagesInCompilationErrorsWithUnitySpecificAdvice(result[nextResultToAugment], editorCompilation);
                totalErrors += result[nextResultToAugment].Count(m => m.type == CompilerMessageType.Error);
                ++nextResultToAugment;
            }

            return(result);
        }
Esempio n. 10
0
 public static BuildRequest BuildRequestFor(RunnableProgram buildProgram, EditorCompilation editorCompilation, string dagName, string dagDirectory = null, bool useScriptUpdater = true)
 {
     return(BuildRequestFor(buildProgram, dagName, dagDirectory, useScriptUpdater, editorCompilation.projectDirectory, new ILPostProcessingProgram(), StdOutModeForScriptCompilation));
 }
        public static void AugmentMessagesInCompilationErrorsWithUnitySpecificAdvice(CompilerMessage[] messages, EditorCompilation editorCompilation)
        {
            for (int i = 0; i != messages.Length; i++)
            {
                //we only postprocess errors
                if (messages[i].type != CompilerMessageType.Error)
                {
                    continue;
                }

                UnsafeErrorProcessor.PostProcess(ref messages[i], editorCompilation);
                ModuleReferenceErrorProcessor.PostProcess(ref messages[i]);
                DeterministicAssemblyVersionErrorProcessor.PostProcess(ref messages[i]);
                CyclicAssemblyReferencesErrorProcessor.PostProcess(ref messages[i]);
            }
        }
            private static CustomScriptAssembly CustomScriptAssemblyFor(CompilerMessage m, EditorCompilation editorCompilation)
            {
                if (editorCompilation == null)
                {
                    return(null);
                }

                var file = new NPath(m.file).MakeAbsolute(editorCompilation.projectDirectory);

                return(editorCompilation
                       .GetCustomScriptAssemblies()
                       .FirstOrDefault(c => file.IsChildOf(new NPath(c.PathPrefix).MakeAbsolute())));
            }
Esempio n. 13
0
        internal bool CompileScripts(ScriptAssemblySettings scriptAssemblySettings, string tempBuildDirectory, BuildFlags buildflags, ref EditorBuildRules.TargetAssembly[] notCompiledTargetAssemblies)
        {
            this.DeleteUnusedAssemblies();
            this.allScripts.RemoveWhere((string path) => !File.Exists(Path.Combine(this.projectDirectory, path)));
            this.StopAllCompilation();
            if (!Directory.Exists(scriptAssemblySettings.OutputDirectory))
            {
                Directory.CreateDirectory(scriptAssemblySettings.OutputDirectory);
            }
            if (!Directory.Exists(tempBuildDirectory))
            {
                Directory.CreateDirectory(tempBuildDirectory);
            }
            IEnumerable <string> enumerable = (!this.areAllScriptsDirty) ? this.dirtyScripts.ToArray <string>() : this.allScripts.ToArray <string>();

            this.areAllScriptsDirty = false;
            this.dirtyScripts.Clear();
            bool result;

            if (!enumerable.Any <string>() && this.runScriptUpdaterAssemblies.Count == 0)
            {
                result = false;
            }
            else
            {
                EditorBuildRules.CompilationAssemblies assemblies = new EditorBuildRules.CompilationAssemblies
                {
                    UnityAssemblies          = this.unityAssemblies,
                    PrecompiledAssemblies    = this.precompiledAssemblies,
                    CustomTargetAssemblies   = this.customTargetAssemblies,
                    EditorAssemblyReferences = ModuleUtils.GetAdditionalReferencesForUserScripts()
                };
                EditorBuildRules.GenerateChangedScriptAssembliesArgs generateChangedScriptAssembliesArgs = new EditorBuildRules.GenerateChangedScriptAssembliesArgs
                {
                    AllSourceFiles       = this.allScripts,
                    DirtySourceFiles     = enumerable,
                    ProjectDirectory     = this.projectDirectory,
                    BuildFlags           = buildflags,
                    Settings             = scriptAssemblySettings,
                    Assemblies           = assemblies,
                    RunUpdaterAssemblies = this.runScriptUpdaterAssemblies
                };
                ScriptAssembly[] array = EditorBuildRules.GenerateChangedScriptAssemblies(generateChangedScriptAssembliesArgs);
                notCompiledTargetAssemblies = generateChangedScriptAssembliesArgs.NotCompiledTargetAssemblies.ToArray <EditorBuildRules.TargetAssembly>();
                if (!array.Any <ScriptAssembly>())
                {
                    result = false;
                }
                else
                {
                    this.compilationTask = new CompilationTask(array, tempBuildDirectory, buildflags, SystemInfo.processorCount);
                    this.compilationTask.OnCompilationStarted += delegate(ScriptAssembly assembly, int phase)
                    {
                        Console.WriteLine("- Starting compile {0}", Path.Combine(scriptAssemblySettings.OutputDirectory, assembly.Filename));
                    };
                    IEnumerable <MonoIsland> compilingMonoIslands = from i in this.GetAllMonoIslands()
                                                                    where 0 < i._files.Length
                                                                    select i;
                    this.compilationTask.OnCompilationFinished += delegate(ScriptAssembly assembly, List <CompilerMessage> messages)
                    {
                        Console.WriteLine("- Finished compile {0}", Path.Combine(scriptAssemblySettings.OutputDirectory, assembly.Filename));
                        if (this.runScriptUpdaterAssemblies.Contains(assembly.Filename))
                        {
                            this.runScriptUpdaterAssemblies.Remove(assembly.Filename);
                        }
                        if (!messages.Any((CompilerMessage m) => m.type == CompilerMessageType.Error))
                        {
                            string engineAssemblyPath = InternalEditorUtility.GetEngineAssemblyPath();
                            string unityUNet          = EditorApplication.applicationContentsPath + "/UnityExtensions/Unity/Networking/UnityEngine.Networking.dll";
                            if (!Weaver.WeaveUnetFromEditor(compilingMonoIslands, Path.Combine(tempBuildDirectory, assembly.Filename), Path.Combine(EditorCompilation.EditorTempPath, assembly.Filename), engineAssemblyPath, unityUNet, (buildflags & BuildFlags.BuildingForEditor) != BuildFlags.None))
                            {
                                messages.Add(new CompilerMessage
                                {
                                    message = "UNet Weaver failed",
                                    type    = CompilerMessageType.Error,
                                    file    = assembly.FullPath,
                                    line    = -1,
                                    column  = -1
                                });
                                this.StopAllCompilation();
                            }
                            else
                            {
                                EditorCompilation.CopyAssembly(Path.Combine(tempBuildDirectory, assembly.Filename), assembly.FullPath);
                            }
                        }
                    };
                    this.compilationTask.Poll();
                    result = true;
                }
            }
            return(result);
        }
Esempio n. 14
0
 public ILPostProcessing(EditorCompilation editorCompilation)
 {
     this.editorCompilation = editorCompilation;
 }
 public static BeeDriver Make(RunnableProgram buildProgram, EditorCompilation editorCompilation, string dagName, ILPostProcessingProgram ilpp, string dagDirectory = null, bool useScriptUpdater = true)
 {
     return(Make(buildProgram, dagName, dagDirectory, useScriptUpdater, editorCompilation.projectDirectory, ilpp, StdOutModeForScriptCompilation));
 }