Inheritance: MonoBehaviour
        /// <summary>
        /// Traverses the necessary Visual Studio structures to retrieve any and all
        /// C++ Preprocessor definitions currently defined.
        /// </summary>
        /// <returns></returns>
        private Defines GetPreprocessorDefines()
        {
            Defines definesHandler = new Defines();

            RegisterAnsiCompliantPredefinedMacros(definesHandler);

            // Extract defines from property sheets
            foreach (VCPropertySheet sheet in this.PropertySheets)
            {
                VCCLCompilerTool tool = GetVCppCompilerOptions(sheet.Tools);
                if (tool != null)
                {
                    GetPreprocessorDefines(tool, definesHandler);
                }
            }

            // Avoid registering the Microsoft defines if the /u option is specified
            if (!this._compiler.UndefineAllPreprocessorDefinitions)
            {
                RegisterMicrosoftPreDefinedCompilerMacros(definesHandler);
            }

            // Extract defines from compiler options
            GetPreprocessorDefines(this._compiler, definesHandler);

            return definesHandler;
        }
Esempio n. 2
0
        /**
         * Gets value stored at key
         * @param key
         * @return
         */
        public static Object Get(String key)
        {
#if NETFX_CORE
            StorageSettings iss = Defines.GetStorageSettings();
#else
            IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;
#endif
            String value = "";
            if (iss.TryGetValue <String>(key, out value))
            {
                return(value);
            }
            else
            {
                if (iss.Contains(key))
                {
                    return(Convert.ToDouble(iss[key]));
                }
                else
                {
                    return(null);
                }
            }
        }
Esempio n. 3
0
        public Il2CppOutputProgram(string name) : base(name)
        {
            Libraries.Add(LibIL2Cpp);
            Libraries.Add(BoehmGCProgram);
            Sources.Add(Distribution.Path.Combine("external").Combine("xxHash/xxhash.c"));

            this.DynamicLinkerSettingsForMsvc()
            .Add(l => l.WithSubSystemType(SubSystemType.Console).WithEntryPoint("wWinMainCRTStartup"));

            Libraries.Add(c => c.ToolChain.Platform is WindowsPlatform, new SystemLibrary("kernel32.lib"));
            Defines.Add(c => c.Platform is WebGLPlatform, "IL2CPP_DISABLE_GC=1");

            this.DynamicLinkerSettingsForMsvc().Add(l => l
                                                    .WithSubSystemType(SubSystemType.Console)
                                                    .WithEntryPoint("wWinMainCRTStartup")
                                                    );
            Defines.Add(c => c.ToolChain.DynamicLibraryFormat == null, "FORCE_PINVOKE_INTERNAL=1");

            this.DynamicLinkerSettingsForEmscripten().Add(c =>
                                                          c.WithShellFile(BuildProgram.BeeRoot.Combine("shell.html")));


            Libraries.Add(c => c.Platform is WebGLPlatform, new PreJsLibrary(BuildProgram.BeeRoot.Combine("tiny_runtime.js")));
        }
Esempio n. 4
0
        /// <summary>
        /// Registers the Microsoft specific PreDefined compiler defines
        /// </summary>
        private static Defines RegisterMicrosoftPreDefinedCompilerMacros(Defines definesHandler)
        {
            /*
             * taken off https://msdn.microsoft.com/en-us/library/b0084kay(v=vs.110).aspx
             *
             * Only a limited number of pre defined macros is taken off the list present on Microsoft's website. The general philosophy used
             * is that the ones selected are those which are always present. i.e. that their presence is not dependent on the compiler settings, processor
             * architecture used.
             *
             */

            definesHandler.Define("__COUNTER__", "");
            definesHandler.Define("__cplusplus", "");
            definesHandler.Define("__FUNCDNAME__", "");
            definesHandler.Define("__FUNCSIG__", "");
            definesHandler.Define("__FUNCTION__", "");
            definesHandler.Define("_INTEGRAL_MAX_BITS", "");
            definesHandler.Define("_MSC_BUILD", "");
            definesHandler.Define("_MSC_FULL_VER", "");
            definesHandler.Define("_MSC_VER", "");
            definesHandler.Define("_WIN32", "");

            return(definesHandler);
        }
Esempio n. 5
0
        protected IList <string> GenerateReferencedDefines()
        {
            var result = new List <string>();

            foreach (var reference in References)
            {
                var loadedReference = reference as CPlusPlusProject;

                if (loadedReference == null)
                {
                    // What to do in this situation?
                    throw new NotImplementedException();
                }

                result.AddRange(loadedReference.GenerateReferencedDefines());
            }

            foreach (var define in Defines.Where(i => i.Exported && !i.Global))
            {
                result.Add(define.Value);
            }

            return(result);
        }
        /// <summary>
        /// Evaluates an expression
        /// </summary>
        /// <param name="expression">expression to be evaluated</param>
        /// <param name="definesHandler">reference to the defines handler </param>
        /// <returns></returns>
        public EvaluationResult EvaluateExpression(string expression, Defines definesHandler)
        {
            this._definesHandler = definesHandler;

            Expression e = new Expression(expression, EvaluateOptions.NoCache);

            e.EvaluateParameter += EvaluateParam;
            e.EvaluateFunction  += EvaluateFunction;

            EvaluationResult evaluationResult = EvaluationResult.UnDetermined;

            try
            {
                object result = e.Evaluate();

                evaluationResult = Convert.ToBoolean(result, CultureInfo.InvariantCulture) ? EvaluationResult.IsTrue : EvaluationResult.IsFalse;
            }
            catch
            {
                evaluationResult = EvaluationResult.UnDetermined;
            }

            return(evaluationResult);
        }
Esempio n. 7
0
        public Boolean TestWhetherProjectFileBelongs(ProjectFile pf)
        {
            // TODO: allow relax if some defines are absent in one of sets
            if (!CompilerPossiblyRelativePathComparer.Instance.Equals(CompilerInstance.BaseCompiler,
                                                                      pf.CompilerOfFile.BaseCompiler))
            {
                return(false);
            }

            if (OwnerSolution.config.RelaxIncludeDirsOrder)
            {
                if (!IncludeDirectories.ListIdenticalRelaxOrder(pf.IncludeDirectories))
                {
                    return(false);
                }
            }
            else
            {
                if (!IncludeDirectories.ListIdentical(pf.IncludeDirectories))
                {
                    return(false);
                }
            }

            if (!Defines.SetEquals(pf.SetOfDefines))
            {
                return(false);
            }

            if (!ForcedIncludes.SetEquals(pf.ForceIncludes))
            {
                return(false);
            }

            return(true);
        }
Esempio n. 8
0
        public void Initialize(Lua.lua_State L)
        {
            DrawableParser  = LGDrawableParser.Instance;
            DimensionParser = LGDimensionParser.Instance;
            ColorParser     = LGColorParser.Instance;
            StringParser    = LGStringParser.Instance;

            List <String> lst = new List <String>();

            lst.Add("ld");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("sw");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("w");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("h");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("small");
            lst.Add("normal");
            lst.Add("large");
            lst.Add("xlarge");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("port");
            lst.Add("land");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("ldpi");
            lst.Add("mdpi");
            lst.Add("hdpi");
            lst.Add("xhdpi");
            lst.Add("nodpi");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("v");
            MatchStringsStart.Add(lst);

            lst = new List <String>();
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            lst.Add("dp");
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            lst.Add("dp");
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            lst.Add("dp");
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            MatchStringsEnd.Add(lst);
            lst = new List <String>();

            switch (LuaEngine.Instance.GetPrimaryLoad())
            {
            case LuaEngine.EXTERNAL_DATA:
            {
#if NETFX_CORE
                StorageFolder internalScriptsFolder = null;

                /*String[] scriptRootArr = scriptsRoot.Split('/');
                *  foreach (String scriptRootPart in scriptRootArr)*/
                String uiRoot = LuaEngine.Instance.GetUIRoot().Replace("/", "\\");
                internalScriptsFolder = Package.Current.InstalledLocation.GetFolderAsync(uiRoot).AsTask().Synchronize();
                IReadOnlyList <StorageFile> files = internalScriptsFolder.GetFilesAsync().AsTask().Synchronize();
                String        rootPath            = ApplicationData.Current.LocalFolder.Path;
                StorageFolder rootFolder          = ApplicationData.Current.LocalFolder;
                StorageFolder scriptsFolder       = null;
                if (LuaEngine.Instance.GetForceLoad() > 0)
                {
                    try
                    {
                        StorageFolder sf = rootFolder.GetFolderAsync(uiRoot).AsTask().Synchronize();
                        sf.DeleteAsync().AsTask().Synchronize();
                    }
                    catch
                    {
                    }
                    scriptsFolder = rootFolder.CreateFolderAsync(uiRoot, CreationCollisionOption.ReplaceExisting).AsTask().Synchronize();
                }
                else
                {
                    scriptsFolder = rootFolder.CreateFolderAsync(uiRoot, CreationCollisionOption.OpenIfExists).AsTask().Synchronize();
                }

                foreach (StorageFile fileSF in files)
                {
                    String      file          = fileSF.Name;
                    Stream      sr            = Defines.GetResourceAsset(uiRoot + "/", file);
                    StorageFile toWrite       = scriptsFolder.CreateFileAsync(file, CreationCollisionOption.ReplaceExisting).AsTask().Synchronize();
                    var         toWriteStream = toWrite.OpenTransactedWriteAsync().AsTask().Synchronize();
                    byte[]      buffer        = new byte[1024];
                    int         length        = 0;
                    while ((length = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        toWriteStream.Stream.WriteAsync(buffer.AsBuffer()).AsTask().Synchronize();
                    }
                    toWriteStream.CommitAsync().AsTask().Synchronize();
                    toWriteStream.Dispose();
                }
#endif
            } break;

            case LuaEngine.INTERNAL_DATA:
            case LuaEngine.RESOURCE_DATA:
            {
            } break;
            }

            ParseValues(L);
            DrawableParser.Initialize(L);
        }
 /// <summary>
 /// Registers the ANSI-Compliant Predefined Macros
 /// </summary>
 private static void RegisterAnsiCompliantPredefinedMacros(Defines definesHandler)
 {
     definesHandler.Define("__DATE__", "");
     definesHandler.Define("__FILE__", "");
     definesHandler.Define("__LINE__", "");
     definesHandler.Define("__TIME__", "");
     definesHandler.Define("__TIMESTAMP__", "");
 }
        private void AddRegistrationCode(List <TypeMemo> memos)
        {
            var autoClassName = $"__UnmanagedPostProcessorOutput__{(uint)AssemblyDefinition.FullName.GetHashCode()}";
            var mod           = AssemblyDefinition.MainModule;

            var classDef = new TypeDefinition("", autoClassName, TypeAttributes.Class, AssemblyDefinition.MainModule.ImportReference(typeof(object)));

            classDef.IsBeforeFieldInit = false;
            mod.Types.Add(classDef);

            var funcDef = new MethodDefinition(".cctor", MethodAttributes.Static | MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, AssemblyDefinition.MainModule.ImportReference(typeof(void)));

            funcDef.Body.InitLocals = false;

#if !UNITY_DOTSPLAYER // This will need a different solution
            if (!Defines.Contains("UNITY_DOTSPLAYER"))
            {
                // Needs to run automatically in the player.
                var attributeCtor = AssemblyDefinition.MainModule.ImportReference(typeof(UnityEngine.RuntimeInitializeOnLoadMethodAttribute).GetConstructor(Type.EmptyTypes));
                funcDef.CustomAttributes.Add(new CustomAttribute(attributeCtor));
            }

            if (Defines.Contains("UNITY_EDITOR"))
            {
                // Needs to run automatically in the editor.
                var attributeCtor2 = AssemblyDefinition.MainModule.ImportReference(typeof(UnityEditor.InitializeOnLoadMethodAttribute).GetConstructor(Type.EmptyTypes));
                funcDef.CustomAttributes.Add(new CustomAttribute(attributeCtor2));
            }
#endif

            classDef.Methods.Add(funcDef);

            var processor = funcDef.Body.GetILProcessor();

            var registryType      = mod.ImportReference(typeof(SystemBaseRegistry)).Resolve();
            var addMethod         = mod.ImportReference(registryType.Methods.FirstOrDefault((x) => x.Name == nameof(SystemBaseRegistry.AddUnmanagedSystemType)));
            var delegateCtor      = mod.ImportReference(registryType.NestedTypes.FirstOrDefault((x) => x.Name == nameof(SystemBaseRegistry.ForwardingFunc)).GetConstructors().FirstOrDefault((x) => x.Parameters.Count == 2));
            var genericHashFunc   = mod.ImportReference(typeof(BurstRuntime)).Resolve().Methods.FirstOrDefault((x) => x.Name == nameof(BurstRuntime.GetHashCode64) && x.HasGenericParameters);
            var typeType          = mod.ImportReference(typeof(Type)).Resolve();
            var getTypeFromHandle = mod.ImportReference(typeType.Methods.FirstOrDefault((x) => x.Name == "GetTypeFromHandle"));

            foreach (var memo in memos)
            {
                // This craziness is equivalent to typeof(n)
                processor.Emit(OpCodes.Ldtoken, memo.m_SystemType);
                processor.Emit(OpCodes.Call, getTypeFromHandle);

                processor.Emit(OpCodes.Call, mod.ImportReference(genericHashFunc.MakeGenericInstanceMethod(memo.m_SystemType)));

                for (int i = 0; i < memo.m_Wrappers.Length; ++i)
                {
                    processor.Emit(OpCodes.Ldnull);
                    processor.Emit(OpCodes.Ldftn, memo.m_Wrappers[i]);
                    processor.Emit(OpCodes.Newobj, delegateCtor);
                }

                processor.Emit(OpCodes.Ldstr, memo.m_SystemType.Name);
                processor.Emit(OpCodes.Ldc_I4, memo.m_BurstCompileBits);
                processor.Emit(OpCodes.Call, addMethod);
            }

            processor.Emit(OpCodes.Ret);
        }
 private void RemoveDefine(object param)
 {
     Defines.Remove(SelectedDefine);
     UpdateCompileString();
 }
Esempio n. 12
0
 public void AddDefines(string value)
 {
     Defines.Add(value);
 }
        public void FillProjectSpecificMissingInfo(Project project, CppCliMode cliMode, LocalFileSystemDirectory targetDir)
        {
            if (targetDir != null)
            {
                PDBFileName = string.Format("{0}{3}{1}.{2}.pdb",
                                            targetDir.AbsolutePath,
                                            project.Module.Name, project.Name,
                                            Path.DirectorySeparatorChar);
            }

            if (cliMode != CppCliMode.Disabled)
            {
                // Fixing some settings to support C++/CLI mode
                switch (cliMode)
                {
                case CppCliMode.Enabled:
                    CompileAsManaged = ManagedCppType.Managed;
                    break;

                case CppCliMode.Pure:
                    CompileAsManaged = ManagedCppType.Pure;
                    break;

                case CppCliMode.Safe:
                    CompileAsManaged = ManagedCppType.Safe;
                    break;

                case CppCliMode.OldSyntax:
                    CompileAsManaged = ManagedCppType.OldSyntax;
                    break;
                }

                if (!IsDebugInformationFormatSpecified && suite.ActiveGoal.Has(Suite.DebugGoal.Name))
                {
                    DebugInformationFormat = DebugInformationFormat.ProgramDatabase;
                }

                MinimalRebuild          = false;
                SmallerTypeCheck        = false;
                FloatingPointExceptions = false;

                if (project.Type == ProjectType.StaticLibrary)
                {
                    Defines = Defines.Concat(new[] { "_LIB" }).ToArray();
                }
            }

            if (project.EffectiveVersion != null)
            {
                Defines = Defines.Concat(new[]
                {
                    String.Format("BARI_PROJECT_VERSION=\"{0}\"", project.EffectiveVersion)
                }).ToArray();
            }

            if (project.EffectiveCopyright != null)
            {
                Defines = Defines.Concat(new[]
                {
                    String.Format("BARI_PROJECT_COPYRIGHT=\"{0}\"", project.EffectiveCopyright)
                }).ToArray();
            }
        }
        protected override bool PostProcessImpl(TypeDefinition[] componentSystemTypes)
        {
            var assemblyDefinition = AssemblyDefinition;

            var earlyInitHelpers = assemblyDefinition.MainModule.ImportReference(typeof(EarlyInitHelpers)).CheckedResolve();

            var autoClassName = $"__JobReflectionRegistrationOutput__{(uint) assemblyDefinition.FullName.GetHashCode()}";

            var classDef = new TypeDefinition("", autoClassName, TypeAttributes.Class, assemblyDefinition.MainModule.ImportReference(typeof(object)));

            classDef.IsBeforeFieldInit = false;

            classDef.CustomAttributes.Add(new CustomAttribute(AttributeConstructorReferenceFor(typeof(DOTSCompilerGeneratedAttribute), assemblyDefinition.MainModule)));

            var funcDef = new MethodDefinition("CreateJobReflectionData", MethodAttributes.Static | MethodAttributes.Public | MethodAttributes.HideBySig, assemblyDefinition.MainModule.ImportReference(typeof(void)));

            funcDef.Body.InitLocals = false;

            classDef.Methods.Add(funcDef);

            var body      = funcDef.Body;
            var processor = body.GetILProcessor();

            bool anythingChanged = false;

            var declaredGenerics = new HashSet <string>();
            var genericJobs      = new List <TypeReference>();

            foreach (var attr in assemblyDefinition.CustomAttributes)
            {
                if (attr.AttributeType.FullName != RegisterGenericJobTypeAttributeName)
                {
                    continue;
                }

                var openTypeRef = (TypeReference)attr.ConstructorArguments[0].Value;
                var openType    = assemblyDefinition.MainModule.ImportReference(openTypeRef).Resolve();

                if (!openTypeRef.IsGenericInstance || !openType.IsValueType)
                {
                    AddDiagnostic(UserError.DC3001(openType));
                    continue;
                }

                TypeReference result = new GenericInstanceType(assemblyDefinition.MainModule.ImportReference(new TypeReference(openType.Namespace, openType.Name, assemblyDefinition.MainModule, openTypeRef.Scope, true)));

                foreach (var ga in ((GenericInstanceType)openTypeRef).GenericArguments)
                {
                    ((GenericInstanceType)result).GenericArguments.Add(LaunderTypeRef(ga, assemblyDefinition.MainModule));
                }

                genericJobs.Add(result);


                var fn = openType.FullName;
                if (!declaredGenerics.Contains(fn))
                {
                    declaredGenerics.Add(fn);
                }
            }

            foreach (var t in assemblyDefinition.MainModule.Types)
            {
                anythingChanged |= VisitJobStructs(t, processor, body, declaredGenerics);
            }

            foreach (var t in genericJobs)
            {
                anythingChanged |= VisitJobStructs(t, processor, body, declaredGenerics);
            }

            processor.Emit(OpCodes.Ret);

            if (anythingChanged)
            {
                var ctorFuncDef = new MethodDefinition("EarlyInit", MethodAttributes.Static | MethodAttributes.Public | MethodAttributes.HideBySig, assemblyDefinition.MainModule.ImportReference(typeof(void)));

#if !UNITY_DOTSRUNTIME
                if (!Defines.Contains("UNITY_DOTSPLAYER") && !Defines.Contains("UNITY_EDITOR"))
                {
                    // Needs to run automatically in the player, but we need to
                    // exclude this attribute when building for the editor, or
                    // it will re-run the registration for every enter play mode.
                    var loadTypeEnumType = assemblyDefinition.MainModule.ImportReference(typeof(UnityEngine.RuntimeInitializeLoadType));
                    var attributeCtor    = assemblyDefinition.MainModule.ImportReference(typeof(UnityEngine.RuntimeInitializeOnLoadMethodAttribute).GetConstructor(new[] { typeof(UnityEngine.RuntimeInitializeLoadType) }));
                    var attribute        = new CustomAttribute(attributeCtor);
                    attribute.ConstructorArguments.Add(new CustomAttributeArgument(loadTypeEnumType, UnityEngine.RuntimeInitializeLoadType.AfterAssembliesLoaded));
                    ctorFuncDef.CustomAttributes.Add(attribute);
                }

                if (Defines.Contains("UNITY_EDITOR"))
                {
                    // Needs to run automatically in the editor.
                    var attributeCtor2 = assemblyDefinition.MainModule.ImportReference(typeof(UnityEditor.InitializeOnLoadMethodAttribute).GetConstructor(Type.EmptyTypes));
                    ctorFuncDef.CustomAttributes.Add(new CustomAttribute(attributeCtor2));
                }
#endif

                ctorFuncDef.Body.InitLocals = false;

                var p = ctorFuncDef.Body.GetILProcessor();

                p.Emit(OpCodes.Ldnull);
                p.Emit(OpCodes.Ldftn, funcDef);

                var delegateType = assemblyDefinition.MainModule.ImportReference(earlyInitHelpers.NestedTypes.First(x => x.Name == nameof(EarlyInitHelpers.EarlyInitFunction)));
                var delegateCtor = assemblyDefinition.MainModule.ImportReference(delegateType.CheckedResolve().GetConstructors().FirstOrDefault((x) => x.Parameters.Count == 2));
                p.Emit(OpCodes.Newobj, delegateCtor);

                p.Emit(OpCodes.Call, assemblyDefinition.MainModule.ImportReference(earlyInitHelpers.Methods.First(x => x.Name == nameof(EarlyInitHelpers.AddEarlyInitFunction))));

                p.Emit(OpCodes.Ret);

                classDef.Methods.Add(ctorFuncDef);

                assemblyDefinition.MainModule.Types.Add(classDef);
            }

            return(anythingChanged);
        }
Esempio n. 15
0
            public ManagedTestInfo(Platform platform, ManagedTestVariant type = ManagedTestVariant.None)
            {
                bool fsharp = type == ManagedTestVariant.FSharp;

                Platform = platform;

                ManagedTestCount = GetBaseTestCount(fsharp);
                Defines.Add("TEST_FRAMEWORK=1");

                // There would be a lot of fsharp projects to clone to do them all...
                if (fsharp && Platform != Platform.macOSModern)
                {
                    throw new NotImplementedException();
                }

                if (type == ManagedTestVariant.ManagedExceptions)
                {
                    Defines.Add("NATIVEEXCEPTION");
                    AdditionalGeneratorArgs = "--nativeexception";
                }

                switch (platform)
                {
                case Platform.macOSFull:
                    Dlldir  = "macos-full";
                    Dllname = "managed-macos-full.dll";
                    Defines.Add("XAMARIN_MAC=1");
                    Defines.Add("XAMARIN_MAC_FULL=1");
                    Abi = "x86_64";                     // FIXME: fat XM apps not supported yet
                    ManagedTestCount += GetMacTestCount();
                    return;

                case Platform.macOSSystem:
                    Dlldir  = "macos-system";
                    Dllname = "managed-macos-system.dll";
                    Defines.Add("XAMARIN_MAC=1");
                    Defines.Add("XAMARIN_MAC_SYSTEM=1");
                    Abi = "x86_64";                     // FIXME: fat XM apps not supported yet
                    ManagedTestCount += GetMacTestCount();
                    return;

                case Platform.macOSModern:
                    if (fsharp)
                    {
                        Dlldir  = "fsharp-macos";
                        Dllname = "fsharp-macos.dll";
                        Defines.Add("XAMARIN_FSHARP=1");
                    }
                    else
                    {
                        Dlldir  = "macos-modern";
                        Dllname = "managed-macos-modern.dll";
                        Defines.Add("XAMARIN_MAC_MODERN=1");
                    }
                    Defines.Add("XAMARIN_MAC=1");
                    Abi = "x86_64";                     // FIXME: fat XM apps not supported yet
                    ManagedTestCount += GetMacTestCount(fsharp);
                    return;

                case Platform.macOS:
                    Dlldir  = "generic";
                    Dllname = "managed.dll";
                    Abi     = "i386,x86_64";
                    return;

                case Platform.iOS:
                    Dlldir  = "ios";
                    Dllname = "managed-ios.dll";
                    Defines.Add("XAMARIN_IOS=1");
                    Abi = "armv7,arm64,i386,x86_64";
                    ManagedTestCount += GetIOSTestCount();
                    return;

                case Platform.tvOS:
                    Dlldir  = "tvos";
                    Dllname = "managed-tvos.dll";
                    Defines.Add("XAMARIN_TVOS=1");
                    Abi = "arm64,x86_64";
                    ManagedTestCount += GetTVTestCount();
                    return;

                default:
                    throw new NotImplementedException();
                }
            }
Esempio n. 16
0
        //Options: Case insensitive; Exact spacing; Dot matches line breaks; ^$ don't match at line breaks; Numbered capture
        //
        //Match the regex below and capture its match into backreference number 1 «(\r\n?|\n)»
        //   Match this alternative (attempting the next alternative only if this one fails) «\r\n?»
        //      Match the carriage return character «\r»
        //      Match the line feed character «\n?»
        //         Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
        //   Or match this alternative (the entire group fails if this one fails to match) «\n»
        //      Match the line feed character «\n»

        #region ISourceFilter

        /// <summary>
        /// Applies the quoted strings filter action on the supplied sourceCode string
        /// </summary>
        /// <param name="cppSourceFile">CppSourceFile object containing the source file information</param>
        /// <param name="definesHandler">not used for this filter</param>
        public void Filter(CppSourceFile cppSourceFile, Defines definesHandler)
        {
            Utility.Code.Require(cppSourceFile, "cppSourceFile");

            cppSourceFile.SourceCode = stringLiteralsRegex.Replace(cppSourceFile.SourceCode, ComputeReplacement);
        }
Esempio n. 17
0
 /// <summary>
 /// Adds a define item.
 /// </summary>
 /// <param name="define">to add</param>
 public void AddDefine(MatchRecognizeDefineItem define)
 {
     Defines.Add(define);
 }
Esempio n. 18
0
    public AsmDefCSharpProgram(AsmDefDescription asmDefDescription)
        : base(asmDefDescription.Directory,
               asmDefDescription.IncludedAsmRefs.Select(asmref => asmref.Path.Parent),
               deferConstruction: true)
    {
        AsmDefDescription = asmDefDescription;

        var asmDefReferences = AsmDefDescription.References.Select(asmDefDescription1 => BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(asmDefDescription1)).ToList();
        var isExe            = asmDefDescription.DefineConstraints.Contains("UNITY_DOTS_ENTRYPOINT") || asmDefDescription.Name.EndsWith(".Tests");

        Construct(asmDefDescription.Name, isExe);

        ProjectFile.AdditionalFiles.Add(asmDefDescription.Path);

        IncludePlatforms = AsmDefDescription.IncludePlatforms;
        ExcludePlatforms = AsmDefDescription.ExcludePlatforms;
        Unsafe           = AsmDefDescription.AllowUnsafeCode;
        References.Add(config =>
        {
            if (config is DotsRuntimeCSharpProgramConfiguration dotsConfig)
            {
                if (dotsConfig.TargetFramework == TargetFramework.Tiny)
                {
                    return(asmDefReferences.Where(rp => rp.IsSupportedFor(dotsConfig) && !IncompatibleTinyBCLAsmDefs.Contains(rp.FileName)));
                }
                else
                {
                    return(asmDefReferences.Where(rp => rp.IsSupportedFor(dotsConfig)));
                }
            }

            //this codepath will be hit for the bindgem invocation
            return(asmDefReferences);
        });

        if (AsmDefDescription.IsTinyRoot || isExe)
        {
            AsmDefCSharpProgramCustomizer.RunAllAddPlatformImplementationReferences(this);
        }

        if (BuildProgram.UnityTinyBurst != null)
        {
            References.Add(BuildProgram.UnityTinyBurst);
        }
        if (BuildProgram.ZeroJobs != null)
        {
            References.Add(BuildProgram.ZeroJobs);
        }
        if (BuildProgram.UnityLowLevel != null)
        {
            References.Add(BuildProgram.UnityLowLevel);
        }
        if (BuildProgram.TinyIO != null)
        {
            References.Add(BuildProgram.TinyIO);
        }

        // Add in any precompiled references found in the asmdef directory or sub-directory
        foreach (var pcr in asmDefDescription.PrecompiledReferences)
        {
            var files = asmDefDescription.Path.Parent.Files(pcr, true);
            if (files.Any())
            {
                References.Add(files);
            }
        }

        if (IsTestAssembly)
        {
            var nunitLiteMain = BuildProgram.BeeRoot.Combine("CSharpSupport/NUnitLiteMain.cs");
            Sources.Add(nunitLiteMain);

            // Setup for IL2CPP
            var tinyTestFramework = BuildProgram.BeeRoot.Parent.Combine("TinyTestFramework");
            Sources.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).ScriptingBackend == ScriptingBackend.TinyIl2cpp || ((DotsRuntimeCSharpProgramConfiguration)c).TargetFramework == TargetFramework.Tiny, tinyTestFramework);
            Defines.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).ScriptingBackend == ScriptingBackend.TinyIl2cpp || ((DotsRuntimeCSharpProgramConfiguration)c).TargetFramework == TargetFramework.Tiny, "UNITY_PORTABLE_TEST_RUNNER");

            // Setup for dotnet
            References.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).ScriptingBackend == ScriptingBackend.Dotnet && ((DotsRuntimeCSharpProgramConfiguration)c).TargetFramework != TargetFramework.Tiny, BuildProgram.NUnitFramework);
            ProjectFile.AddCustomLinkRoot(nunitLiteMain.Parent, "TestRunner");
            References.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).ScriptingBackend == ScriptingBackend.Dotnet && ((DotsRuntimeCSharpProgramConfiguration)c).TargetFramework != TargetFramework.Tiny, BuildProgram.NUnitLite);

            // General setup
            References.Add(BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(AsmDefConfigFile.AsmDefDescriptionFor("Unity.Entities")));
            References.Add(BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(AsmDefConfigFile.AsmDefDescriptionFor("Unity.Tiny.Core")));
            References.Add(BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(AsmDefConfigFile.AsmDefDescriptionFor("Unity.Tiny.UnityInstance")));
            References.Add(BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(AsmDefConfigFile.AsmDefDescriptionFor("Unity.Collections")));
        }
        else if (IsILPostProcessorAssembly)
        {
            References.Add(BuildProgram.UnityCompilationPipeline);
            References.Add(MonoCecil.Paths);
            References.Add(Il2Cpp.Distribution.Path.Combine("build/deploy/net471/Unity.Cecil.Awesome.dll"));
        }
    }
        /// <summary>
        /// Registers the Microsoft specific PreDefined compiler defines
        /// </summary>
        private static Defines RegisterMicrosoftPreDefinedCompilerMacros(Defines definesHandler)
        {
            /*
             * taken off https://msdn.microsoft.com/en-us/library/b0084kay(v=vs.110).aspx
             *
             * Only a limited number of pre defined macros is taken off the list present on Microsoft's website. The general philosophy used
             * is that the ones selected are those which are always present. i.e. that their presence is not dependent on the compiler settings, processor
             * architecture used.
             *
             */

            definesHandler.Define("__COUNTER__", "");
            definesHandler.Define("__cplusplus", "");
            definesHandler.Define("__FUNCDNAME__", "");
            definesHandler.Define("__FUNCSIG__", "");
            definesHandler.Define("__FUNCTION__", "");
            definesHandler.Define("_INTEGRAL_MAX_BITS", "");
            definesHandler.Define("_MSC_BUILD", "");
            definesHandler.Define("_MSC_FULL_VER", "");
            definesHandler.Define("_MSC_VER", "");
            definesHandler.Define("_WIN32", "");

            return definesHandler;
        }
Esempio n. 20
0
	/////////////////////////////////////////////////////////////////////////
	//強制フラグのセット(mReelStartメソッドの前で呼んで下さい。)
	/////////////////////////////////////////////////////////////////////////
	// flagIndex : 強制フラグ(0:無効/1~DfOHHB_V23_DEF.DEF_FORCE_MAX-1)※下記のワードを参照。
	//-----------------------------------------------------------------------
	//					BB未動作時		|	BB作動時				|	JAC作動中
	//DfOHHB_V23_DEF.DEF_FORCE_HAZURE	:(ハズレ)			|(ハズレ)					|(ハズレ)		
	//DfOHHB_V23_DEF.DEF_FORCE_CHERY 	:(チェリー)			|(15枚役)ドン・ベル・ベル	|(無効)	
	//FORCE_DfOHHB_V23_DEF.DEF_BELL 	:(ベル)			|(ベル)					|(無効)		
	//DfOHHB_V23_DEF.DEF_FORCE_SUIKA 	:(スイカ)			|(スイカ or チェリー)			|(無効)
	//DfOHHB_V23_DEF.DEF_FORCE_REPLAY	:(リプレイ)			|(JACIN)					|(15枚役)リプ・リプ・リプ
	//DfOHHB_V23_DEF.DEF_FORCE_REG 	:(レギュラーボーナス)	|(無効)					|(無効)
	//DfOHHB_V23_DEF.DEF_FORCE_BIG 	:(ビッグボーナス)	|(無効)					|(無効)
	//DfOHHB_V23_DEF.DEF_FORCE_MAX 	: フラグ数
	//-----------------------------------------------------------------------
	//※無効時は、通常通りmReelStart()がRAMDOMXを参照し処理されます。
	//※セットされている強制フラグはDfOHHB_V23_DEF.DEF_FORCE_FLAGという名の場所に保存されます。
	//※DfOHHB_V23_DEF.DEF_FORCE_FLAGワークはclaerWork(DfOHHB_V23_DEF.DEF_CLR_AREA_3)でゼロクリアされます。
	//-----------------------------------------------------------------------
	public static void mSetForceFlag(Defines.ForceYakuFlag flagIndex)
	{
		Defines.RAM_TRACE("mSetForceFlag:["+Defines.DEF_FORCE_FLAG+"]" + flagIndex);
        setWork(Defines.DEF_FORCE_FLAG, (ushort)((int)flagIndex & (Enum.GetNames(typeof(Defines.ForceYakuFlag)).Length - 1)));	
	}
Esempio n. 21
0
        public void Load(Defines defines, RemoteAgent agent)
        {
            this.Agent = agent;
            TopModule  = defines.TopModule;


            foreach (var c in defines.Consts)
            {
                AddType(new DefConst(c));
            }

            foreach (var e in defines.Enums)
            {
                AddType(new DefEnum(e));
            }

            foreach (var b in defines.Beans)
            {
                AddType(new DefBean(b));
            }

            foreach (var p in defines.DbTables)
            {
                AddType(new DefTable(p));
            }

            foreach (var type in Types.Values)
            {
                type.AssemblyBase = this;
            }

            foreach (var type in Types.Values)
            {
                try
                {
                    s_logger.Trace("precompile type:{0} begin", type.FullName);
                    type.PreCompile();
                    s_logger.Trace("precompile type:{0} end", type.FullName);
                }
                catch (Exception)
                {
                    agent.Error("precompile type:{0} error", type.FullName);
                    throw;
                }
            }
            foreach (var type in Types.Values)
            {
                try
                {
                    s_logger.Trace("compile type:{0} begin", type.FullName);
                    type.Compile();
                    s_logger.Trace("compile type:{0} end", type.FullName);
                }
                catch (Exception)
                {
                    agent.Error("compile type:{0} error", type.FullName);
                    s_logger.Error("compile type:{0} error", type.FullName);
                    throw;
                }
            }
            foreach (var type in Types.Values)
            {
                try
                {
                    s_logger.Trace("post compile type:{0} begin", type.FullName);
                    type.PostCompile();
                    s_logger.Trace("post compile type:{0} end", type.FullName);
                }
                catch (Exception)
                {
                    agent.Error("post compile type:{0} error", type.FullName);
                    s_logger.Error("post compile type:{0} error", type.FullName);
                    throw;
                }
            }
        }
Esempio n. 22
0
    protected void Construct(string name, bool isExe)
    {
        FileName = name + (isExe ? ".exe" : ".dll");

        Framework.Add(c => ShouldTargetTinyCorlib(c, this), Bee.DotNet.Framework.FrameworkNone);
        References.Add(c => ShouldTargetTinyCorlib(c, this), Il2Cpp.TinyCorlib);

        Framework.Add(c => !ShouldTargetTinyCorlib(c, this), Bee.DotNet.Framework.Framework471);
        References.Add(c => !ShouldTargetTinyCorlib(c, this), new SystemReference("System"));

        ProjectFile.Path = DeterminePathForProjectFile();

        ProjectFile.ReferenceModeCallback = arg =>
        {
            // Most projects are AsmDefCSharpProgram. For everything else we'll look up their
            // packagestatus by the fact that we know it's in the same package as Unity.Entities.CPlusPlus
            // XXX This is not true any more!
            //var asmdefDotsProgram = (arg as AsmDefCSharpProgram)?.AsmDefDescription ?? AsmDefConfigFile.AsmDefDescriptionFor("Unity.Entities.CPlusPlus");
            return(ProjectFile.ReferenceMode.ByCSProj);
        };

        LanguageVersion = "7.3";
        Defines.Add(
            "UNITY_DOTSPLAYER",
            "NET_DOTS",
            // TODO -- figure out what's gated with this, and if it should have a UNITY_DOTSPLAYER || ...
            "UNITY_2018_3_OR_NEWER",
            // And these might not make sense for DOTS Runtime anyway beacuse they are UnityEngine/UnityEditor APIs.
            // They break the build if we add them.
            //"UNITY_2019_1_OR_NEWER",
            //"UNITY_2019_2_OR_NEWER",
            //"UNITY_2019_3_OR_NEWER",
            // TODO -- removing this breaks Burst, it should be using DOTSPLAYER!
            "UNITY_ZEROPLAYER"
            );

        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is WebGLPlatform, "UNITY_WEBGL");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is WindowsPlatform, "UNITY_WINDOWS");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is MacOSXPlatform, "UNITY_MACOSX");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is LinuxPlatform, "UNITY_LINUX");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is IosPlatform, "UNITY_IOS");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is AndroidPlatform, "UNITY_ANDROID");
        Defines.Add(c => !((DotsRuntimeCSharpProgramConfiguration)c).MultiThreadedJobs, "UNITY_SINGLETHREADED_JOBS");

        CopyReferencesNextToTarget = false;

        WarningsAsErrors = false;
        //hack, fix this in unity.mathematics

        foreach (var sourcePath in AllSourcePaths)
        {
            if (sourcePath.FileName == "Unity.Mathematics")
            {
                Sources.Add(sourcePath.Files("*.cs", true)
                            .Where(f => f.FileName != "math_unity_conversion.cs" && f.FileName != "PropertyAttributes.cs"));
            }
            else
            {
                Sources.Add(new CustomProvideFiles(sourcePath));
            }
        }
        foreach (var sourcePath in AllSourcePaths)
        {
            var cppFolder     = sourcePath.Combine("cpp~");
            var prejsFolder   = sourcePath.Combine("prejs~");
            var jsFolder      = sourcePath.Combine("js~");
            var postjsFolder  = sourcePath.Combine("postjs~");
            var beeFolder     = sourcePath.Combine("bee~");
            var includeFolder = cppFolder.Combine("include");

            NPath[] cppFiles = Array.Empty <NPath>();
            if (cppFolder.DirectoryExists())
            {
                cppFiles = cppFolder.Files("*.c*", true);
                ProjectFile.AdditionalFiles.AddRange(cppFolder.Files(true));
                GetOrMakeNativeProgram().Sources.Add(cppFiles);
            }

            if (prejsFolder.DirectoryExists())
            {
                var jsFiles = prejsFolder.Files("*.js", true);
                ProjectFile.AdditionalFiles.AddRange(prejsFolder.Files(true));
                GetOrMakeNativeProgram()
                .Libraries.Add(c => c.Platform is WebGLPlatform,
                               jsFiles.Select(jsFile => new PreJsLibrary(jsFile)));
            }

            //todo: get rid of having both a regular js and a prejs folder
            if (jsFolder.DirectoryExists())
            {
                var jsFiles = jsFolder.Files("*.js", true);
                ProjectFile.AdditionalFiles.AddRange(jsFolder.Files(true));
                GetOrMakeNativeProgram()
                .Libraries.Add(c => c.Platform is WebGLPlatform,
                               jsFiles.Select(jsFile => new JavascriptLibrary(jsFile)));
            }

            if (postjsFolder.DirectoryExists())
            {
                var jsFiles = postjsFolder.Files("*.js", true);
                ProjectFile.AdditionalFiles.AddRange(postjsFolder.Files(true));
                GetOrMakeNativeProgram()
                .Libraries.Add(c => c.Platform is WebGLPlatform,
                               jsFiles.Select(jsFile => new PostJsLibrary(jsFile)));
            }

            if (beeFolder.DirectoryExists())
            {
                ProjectFile.AdditionalFiles.AddRange(beeFolder.Files("*.cs"));
            }

            if (includeFolder.DirectoryExists())
            {
                GetOrMakeNativeProgram().PublicIncludeDirectories.Add(includeFolder);
            }
        }

        SupportFiles.Add(AllSourcePaths.SelectMany(p =>
                                                   p.Files()
                                                   .Where(f => f.HasExtension("jpg", "png", "wav", "mp3", "jpeg", "mp4", "webm", "ogg", "ttf", "json"))));

        Defines.Add(c => c.CodeGen == CSharpCodeGen.Debug || (c as DotsRuntimeCSharpProgramConfiguration)?.DotsConfiguration < DotsConfiguration.Release, "DEBUG");

        Defines.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).EnableUnityCollectionsChecks, "ENABLE_UNITY_COLLECTIONS_CHECKS");

        Defines.Add(
            c => (c as DotsRuntimeCSharpProgramConfiguration)?.ScriptingBackend == ScriptingBackend.TinyIl2cpp,
            "UNITY_DOTSPLAYER_IL2CPP");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.ScriptingBackend == ScriptingBackend.Dotnet, "UNITY_DOTSPLAYER_DOTNET");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Defines ?? new List <string>());

        ProjectFile.RedirectMSBuildBuildTargetToBee = true;
        ProjectFile.AddCustomLinkRoot(MainSourcePath, ".");
        ProjectFile.RootNameSpace = "";

        DotsRuntimeCSharpProgramCustomizer.RunAllCustomizersOn(this);
    }
 /// <summary>
 /// Identifies the project's configured preprocessor definitions
 /// </summary>
 /// <param name="definitions">The preprocessor definitions in use by this project</param>
 /// <returns>this</returns>
 public FakeProjectBuilder Defines(Defines definitions)
 {
     this._definitions = definitions;
     return(this);
 }
Esempio n. 24
0
 private void RemoveDefine()
 {
     Defines.Remove(SelectedDefine);
     Save();
 }
Esempio n. 25
0
        /// <summary>
        /// Renders the clause in textual representation.
        /// </summary>
        /// <param name="writer">to output to</param>
        public void ToEPL(TextWriter writer)
        {
            string delimiter;

            writer.Write(" match_recognize (");

            if (PartitionExpressions.Count > 0)
            {
                delimiter = "";
                writer.Write(" partition by ");
                foreach (Expression part in PartitionExpressions)
                {
                    writer.Write(delimiter);
                    part.ToEPL(writer, ExpressionPrecedenceEnum.MINIMUM);
                    delimiter = ", ";
                }
            }

            delimiter = "";
            writer.Write(" measures ");
            foreach (SelectClauseExpression part in Measures)
            {
                writer.Write(delimiter);
                part.ToEPLElement(writer);
                delimiter = ", ";
            }

            if (IsAll)
            {
                writer.Write(" all matches");
            }

            if (SkipClause != MatchRecognizeSkipClause.PAST_LAST_ROW)
            {
                writer.Write(" after match skip " + SkipClause.GetText());
            }

            writer.Write(" pattern (");
            Pattern.WriteEPL(writer);
            writer.Write(")");

            if ((IntervalClause != null) && (IntervalClause.Expression != null))
            {
                writer.Write(" interval ");
                IntervalClause.Expression.ToEPL(writer, ExpressionPrecedenceEnum.MINIMUM);
                if (IntervalClause.IsOrTerminated)
                {
                    writer.Write(" or terminated");
                }
            }

            delimiter = "";
            if (!Defines.IsEmpty())
            {
                writer.Write(" define ");
                foreach (MatchRecognizeDefine def in Defines)
                {
                    writer.Write(delimiter);
                    writer.Write(def.Name);
                    writer.Write(" as ");
                    def.Expression.ToEPL(writer, ExpressionPrecedenceEnum.MINIMUM);
                    delimiter = ", ";
                }
            }

            writer.Write(")");
        }
 private void RemoveDefine(object param)
 {
     Defines.Remove(SelectedDefine);
     Save();
 }
Esempio n. 27
0
        // (/\*(?:.+?)\*/)
        //
        // Options: Case insensitive; Exact spacing; Dot matches line breaks; ^$ don't match at line breaks; Numbered capture
        //
        // Match the regex below and capture its match into backreference number 1 «(/\*(?:.+?)\*/)»
        //    Match the character “/” literally «/»
        //    Match the character “*” literally «\*»
        //    Match the regular expression below «(?:.+?)»
        //       Match any single character «.+?»
        //          Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
        //    Match the character “*” literally «\*»
        //    Match the character “/” literally «/»

        #region ISourceFilter

        /// <summary>
        /// Filters any multiline comments from the source code.
        /// </summary>
        /// <param name="cppSourceFile">CppSourceFile object containing the source file information</param>
        /// <param name="definesHandler">not used for this filter</param>
        public void Filter(CppSourceFile cppSourceFile, Defines definesHandler)
        {
            Utility.Code.Require(cppSourceFile, "cppSourceFile");
            cppSourceFile.SourceCode = multiLineCommentRegex.Replace(cppSourceFile.SourceCode, ComputeMultiLineCommentReplacement);
        }
Esempio n. 28
0
        public void Load(Defines defines, RemoteAgent agent, GenArgs args)
        {
            LoadCommon(defines, agent, args);

            foreach (var e in defines.Enums)
            {
                AddType(new DefEnum(e));
            }

            foreach (var b in defines.Beans)
            {
                AddType(new DefBean(b));
            }

            foreach (var p in defines.Protos)
            {
                AddType(new DefProto(p));
            }
            foreach (var r in defines.Rpcs)
            {
                AddType(new DefRpc(r));
            }

            foreach (var type in Types.Values)
            {
                type.AssemblyBase = this;
            }

            foreach (var type in Types.Values)
            {
                try
                {
                    s_logger.Trace("precompile type:{0} begin", type.FullName);
                    type.PreCompile();
                    s_logger.Trace("precompile type:{0} end", type.FullName);
                }
                catch (Exception)
                {
                    agent.Error("precompile type:{0} error", type.FullName);
                    throw;
                }
            }
            foreach (var type in Types.Values)
            {
                try
                {
                    s_logger.Trace("compile type:{0} begin", type.FullName);
                    type.Compile();
                    s_logger.Trace("compile type:{0} end", type.FullName);
                }
                catch (Exception)
                {
                    agent.Error("compile type:{0} error", type.FullName);
                    s_logger.Error("compile type:{0} error", type.FullName);
                    throw;
                }
            }
            foreach (var type in Types.Values)
            {
                try
                {
                    s_logger.Trace("post compile type:{0} begin", type.FullName);
                    type.PostCompile();
                    s_logger.Trace("post compile type:{0} end", type.FullName);
                }
                catch (Exception)
                {
                    agent.Error("post compile type:{0} error", type.FullName);
                    s_logger.Error("post compile type:{0} error", type.FullName);
                    throw;
                }
            }
        }
    protected void Construct(string name, bool isExe)
    {
        FileName = name + (isExe ? ".exe" : ".dll");

        Framework.Add(c => ShouldTargetTinyCorlib(c, this), Bee.DotNet.Framework.FrameworkNone);
        References.Add(c => ShouldTargetTinyCorlib(c, this), Il2Cpp.TinyCorlib);

        Framework.Add(c => !ShouldTargetTinyCorlib(c, this), Bee.DotNet.Framework.Framework471);
        References.Add(c => !ShouldTargetTinyCorlib(c, this), new SystemReference("System"));

        ProjectFile.Path = new NPath(FileName).ChangeExtension(".csproj");

        ProjectFile.ReferenceModeCallback = arg =>
        {
            if (arg == Il2Cpp.TinyCorlib)
            {
                return(ProjectFile.ReferenceMode.ByCSProj);
            }

            //most projects are AsmDefBasedDotsRuntimeCSharpProgram. The remained are things like ZeroJobs. For them we'll look up their packagestatus by the fact that we know
            //it's in the same package as Unity.Entities.CPlusPlus
            var asmdefDotsProgram = (arg as AsmDefBasedDotsRuntimeCSharpProgram)?.AsmDefDescription ?? BuildProgramConfigFile.AsmDefDescriptionFor("Unity.Entities.CPlusPlus");

            switch (asmdefDotsProgram.PackageSource)
            {
            case "NoPackage":
            case "Embedded":
            case "Local":
                return(ProjectFile.ReferenceMode.ByCSProj);

            default:
                return(ProjectFile.ReferenceMode.ByDotNetAssembly);
            }
        };

        LanguageVersion = "7.3";
        Defines.Add(
            "UNITY_2018_3_OR_NEWER",
            "UNITY_DOTSPLAYER",
            "UNITY_ZEROPLAYER", //<-- this was used for a while, let's keep it around to not break people's incoming PR's.
            "NET_TINY",
            "NET_DOTS",
            "UNITY_USE_TINYMATH",
            "UNITY_BINDGEM"
            );

        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is WebGLPlatform, "UNITY_WEBGL");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is WindowsPlatform, "UNITY_WINDOWS");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is MacOSXPlatform, "UNITY_MACOSX");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is LinuxPlatform, "UNITY_LINUX");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is IosPlatform, "UNITY_IOS");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is AndroidPlatform, "UNITY_ANDROID");

        CopyReferencesNextToTarget = false;

        WarningsAsErrors = false;
        //hack, fix this in unity.mathematics
        if (SourcePath.FileName == "Unity.Mathematics")
        {
            Sources.Add(SourcePath.Files("*.cs", true).Where(f => f.FileName != "math_unity_conversion.cs" && f.FileName != "PropertyAttributes.cs"));
        }
        else
        {
            var csFilesForDirectory = CSFilesForDirectory(SourcePath).ToList();
            if (csFilesForDirectory.Count == 0)
            {
                csFilesForDirectory.Add(BuildProgram.BeeRoot.Combine("CSharpSupport/PlaceHolderForEmptyProject.cs"));
            }
            Sources.Add(csFilesForDirectory);
        }

        var cppFolder     = SourcePath.Combine("cpp~");
        var prejsFolder   = SourcePath.Combine("prejs~");
        var jsFolder      = SourcePath.Combine("js~");
        var postjsFolder  = SourcePath.Combine("postjs~");
        var beeFolder     = SourcePath.Combine("bee~");
        var includeFolder = cppFolder.Combine("include");

        NPath[] cppFiles = Array.Empty <NPath>();
        if (cppFolder.DirectoryExists())
        {
            cppFiles = cppFolder.Files("*.c*", true);
            ProjectFile.AdditionalFiles.AddRange(cppFolder.Files(true));
            GetOrMakeNativeProgram().Sources.Add(cppFiles);
        }

        if (prejsFolder.DirectoryExists())
        {
            var jsFiles = prejsFolder.Files("*.js", true);
            ProjectFile.AdditionalFiles.AddRange(prejsFolder.Files(true));
            GetOrMakeNativeProgram().Libraries.Add(jsFiles.Select(jsFile => new PreJsLibrary(jsFile)));
        }

        //todo: get rid of having both a regular js and a prejs folder
        if (jsFolder.DirectoryExists())
        {
            var jsFiles = jsFolder.Files("*.js", true);
            ProjectFile.AdditionalFiles.AddRange(jsFolder.Files(true));
            GetOrMakeNativeProgram().Libraries.Add(jsFiles.Select(jsFile => new JavascriptLibrary(jsFile)));
        }

        if (postjsFolder.DirectoryExists())
        {
            var jsFiles = postjsFolder.Files("*.js", true);
            ProjectFile.AdditionalFiles.AddRange(postjsFolder.Files(true));
            GetOrMakeNativeProgram().Libraries.Add(jsFiles.Select(jsFile => new PostJsLibrary(jsFile)));
        }

        if (beeFolder.DirectoryExists())
        {
            ProjectFile.AdditionalFiles.AddRange(beeFolder.Files("*.cs"));
        }

        if (includeFolder.DirectoryExists())
        {
            GetOrMakeNativeProgram().PublicIncludeDirectories.Add(includeFolder);
        }

        SupportFiles.Add(SourcePath.Files().Where(f => f.HasExtension("jpg", "png", "wav", "mp3", "jpeg", "mp4", "webm", "ogg")));


        Defines.Add(c => c.CodeGen == CSharpCodeGen.Debug, "DEBUG");

        Defines.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).EnableUnityCollectionsChecks, "ENABLE_UNITY_COLLECTIONS_CHECKS");

        Defines.Add(
            c => (c as DotsRuntimeCSharpProgramConfiguration)?.ScriptingBackend == ScriptingBackend.TinyIl2cpp,
            "UNITY_DOTSPLAYER_IL2CPP");
        Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.ScriptingBackend == ScriptingBackend.Dotnet, "UNITY_DOTSPLAYER_DOTNET");

        ProjectFile.RedirectMSBuildBuildTargetToBee = true;
        ProjectFile.AddCustomLinkRoot(SourcePath, ".");
        ProjectFile.RootNameSpace = "";

        DotsRuntimeCSharpProgramCustomizer.RunAllCustomizersOn(this);
    }
 private void AddDefine(object param)
 {
     Defines.Add(DefineText);
     DefineText = string.Empty;
     UpdateCompileString();
 }
        public override bool Execute()
        {
            int buildId;

            try {
                dynamic buildEngine = BuildEngine.AccessPrivate();

                var     host  = buildEngine.host;
                dynamic pHost = new AccessPrivateWrapper(host);
                var     bp    = pHost.buildParameters;
                dynamic pBp   = new AccessPrivateWrapper(bp);

                buildId = pBp.buildId;

                lock (typeof(InvokeBuild)) {
                    if (buildId <= MaxBuildId)
                    {
                        // this happens when we build a solution, and it wants to build each project
                        return(true);
                    }
                    MaxBuildId = buildId;
                }
            }
            catch {
            }

            using (new PushDirectory(Environment.CurrentDirectory)) {
                try {
                    if (Location.Is())
                    {
                        Environment.CurrentDirectory = Location.GetFullPath();
                    }

                    if (string.IsNullOrWhiteSpace(ScriptFile))
                    {
                        // search for it.
                        ScriptFile = new[] {
                            @"copkg\.buildinfo", @"contrib\.buildinfo", @"contrib\coapp\.buildinfo", @".buildinfo"
                        }.WalkUpPaths();

                        if (string.IsNullOrEmpty(ScriptFile))
                        {
                            throw new ClrPlusException(@"Unable to find .buildinfo file anywhere in the current directory structure.");
                        }
                    }

                    if (!File.Exists(ScriptFile))
                    {
                        throw new ClrPlusException(@"Unable to find Invoke-build script file '{0}'.".format(ScriptFile));
                    }

                    string[] defines = Defines.IsNullOrEmpty() ? new string[0] : Defines.Select(each => each.ItemSpec).ToArray();

                    using (var buildScript = new BuildScript(ScriptFile)) {
                        buildScript.BuildMessage += message => {
                            try {
                                switch (message.EventType)
                                {
                                case "BuildWarning":
                                    Log.LogWarning(message.Subcategory, message.Code, message.HelpKeyword, message.File, message.LineNumber, message.ColumnNumber, message.EndLineNumber, message.EndColumnNumber, message.Message);
                                    break;

                                case "BuildError":
                                    Log.LogError(message.Subcategory, message.Code, message.HelpKeyword, message.File, message.LineNumber, message.ColumnNumber, message.EndLineNumber, message.EndColumnNumber, message.Message);
                                    break;

                                case "ProjectStarted":
                                    Log.LogExternalProjectStarted(message.Message, message.HelpKeyword, message.ProjectFile, message.TargetNames);
                                    break;

                                case "ProjectFinished":
                                    Log.LogExternalProjectFinished(message.Message, message.HelpKeyword, message.ProjectFile, message.Succeeded);
                                    break;

                                case "TaskStarted":
                                    Log.LogMessage(MessageImportance.Low, message.Message);
                                    break;

                                case "TaskFinished":
                                    Log.LogMessage(MessageImportance.Low, message.Message);
                                    break;

                                case "TargetStarted":
                                    Log.LogMessage(MessageImportance.Low, message.Message);
                                    break;

                                case "TargetFinished":
                                    Log.LogMessage(MessageImportance.Low, message.Message);
                                    break;

                                case "BuildStarted":
                                    Log.LogMessage(MessageImportance.Low, message.Message);
                                    break;

                                case "BuildFinished":
                                    Log.LogMessage(MessageImportance.Low, message.Message);
                                    break;

                                case "BuildMessage":
                                    Log.LogMessage((MessageImportance)message.Importance, message.Message);
                                    break;

                                default:
                                    Log.LogMessage(MessageImportance.Low, message.Message);
                                    break;
                                }
                            }
                            catch (Exception e) {
                                LogError("{0}/{1}/{2}", e.GetType().Name, e.Message, e.StackTrace);
                            }
                            return(false);
                        };

                        foreach (var i in defines)
                        {
                            var p = i.IndexOf("=");
                            var k = p > -1 ? i.Substring(0, p) : i;
                            var v = p > -1 ? i.Substring(p + 1) : "";
                            buildScript.AddMacro(k, v);
                        }

                        var targets = Targets.IsNullOrEmpty() ? new string[0] : Targets.Select(each => each.ItemSpec).ToArray();

                        if (Targets.IsNullOrEmpty())
                        {
                            targets = new string[] {
                                "default"
                            };
                        }

                        Environment.SetEnvironmentVariable("MaxThreads", "" + MaxThreads);
                        Environment.SetEnvironmentVariable("HIDE_THREADS", "true");

                        buildScript.MaxThreads = MaxThreads;
                        return(buildScript.Execute(targets));
                    }
                } catch (Exception e) {
                    LogError("{0}/{1}/{2}".format(e.GetType().Name, e.Message, e.StackTrace));
                    return(false);
                } finally {
                    Environment.SetEnvironmentVariable("HIDE_THREADS", null);
                    Environment.SetEnvironmentVariable("MaxThreads", null);
                }
            }
        }
        public CompileSettingsFormViewModel(IProject project) : base("Compiler", project)
        {
            settings = project.GetToolchainSettings <GccToolchainSettings>().CompileSettings;

            defines      = new ObservableCollection <string>(settings.Defines);
            includePaths = new ObservableCollection <string>(settings.Includes);

            miscOptions = settings.CustomFlags;

            optimizationLevelSelectedIndex   = (int)settings.Optimization;
            cppLanguageStandardSelectedIndex = (int)settings.CppLanguageStandard;
            clanguageStandardSelectedIndex   = (int)settings.CLanguageStandard;
            fpuSelectedIndex = (int)settings.Fpu;
            debugSymbols     = settings.DebugInformation;
            rtti             = settings.Rtti;
            exceptions       = settings.Exceptions;

            AddDefineCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.DefineText, define => !string.IsNullOrEmpty(define) && !Defines.Contains(define)));
            AddDefineCommand.Subscribe(AddDefine);

            RemoveDefineCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.SelectedDefine, selected => !string.IsNullOrEmpty(selected)));
            RemoveDefineCommand.Subscribe(RemoveDefine);

            AddIncludePathCommand = ReactiveCommand.Create();
            AddIncludePathCommand.Subscribe(AddIncludePath);

            RemoveIncludePathCommand = ReactiveCommand.Create();
            RemoveIncludePathCommand.Subscribe(RemoveIncludePath);

            UpdateCompileString();
        }
Esempio n. 33
0
 public void DisableExceptions()
 {
     Defines.Add("_HAS_EXCEPTIONS=0");
     Options.Add(Sharpmake.Options.Vc.Compiler.Exceptions.Disable);
 }
Esempio n. 34
0
        public override bool Execute()
        {
            if ((_sources == null) || (_sources.Length == 0))
            {
                Log.LogError("No source files were specified");
                return(false);
            }

            for (int i = 0; i < _sources.Length; i++)
            {
                ITaskItem source = _sources[i];
                if (File.Exists(source.ItemSpec) == false)
                {
                    Log.LogError("'" + source.ItemSpec + "' was not found.");
                    _hasErrors = true;
                }
            }

            if (_hasErrors)
            {
                return(false);
            }

            if (String.IsNullOrEmpty(Defines) == false)
            {
                _preprocessorVariables = Defines.Split(',', ';', ' ');
            }

            Log.LogMessage(MessageImportance.Low,
                           String.Format("Parameters: Debug={0}, Minimize={1}, StripCommentsOnly={2}, WindowsLineBreaks={3}\r\n            Defines={4}",
                                         Debug, Minimize, StripCommentsOnly, WindowsLineBreaks, Defines));

            ArrayList scripts = new ArrayList(_sources.Length);

            for (int i = 0; i < _sources.Length; i++)
            {
                ITaskItem source = _sources[i];

                string    sourcePath = source.ItemSpec;
                string    outputPath = null;
                BuildType type       = BuildType.Unknown;

                string extension = Path.GetExtension(sourcePath);
                if (String.Compare(extension, ".jsa", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    type = BuildType.ScriptAssembly;
                }
                else if (String.Compare(extension, ".jsx", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    type = BuildType.ExtendedScript;
                }
                else if (String.Compare(extension, ".js", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    type = BuildType.StandardScript;
                }
                else
                {
                    Log.LogError("'" + sourcePath + "' is an unknown file type.");
                    _hasErrors = true;
                }

                if (type != BuildType.Unknown)
                {
                    Log.LogMessage(MessageImportance.Low, "Building '" + sourcePath + "'");
                    if (type == BuildType.StandardScript)
                    {
                        outputPath = CopyStandardScriptFile(sourcePath);
                    }
                    else
                    {
                        outputPath = ConvertScriptFile(type, sourcePath);
                    }

                    if (String.IsNullOrEmpty(outputPath) == false)
                    {
                        scripts.Add(new TaskItem(outputPath));
                    }
                    else
                    {
                        _hasErrors = true;
                    }
                }
            }

            if (_hasErrors == false)
            {
                _scripts = (ITaskItem[])scripts.ToArray(typeof(ITaskItem));
                return(true);
            }
            return(false);
        }
        /// <summary>
        /// Populates the provided definesHandler with the preprocessor defines available within the compiler argument
        /// </summary>
        /// <param name="compiler">The base Visual Studio C++ compiler configuration</param>
        /// <param name="definesHandler">The target structure which will host the extracted preprocessor definitions</param>
        private static void GetPreprocessorDefines(VCCLCompilerTool compiler, Defines definesHandler)
        {
            string definitions = compiler.PreprocessorDefinitions.Trim();
            string undefinitions = compiler.UndefinePreprocessorDefinitions.Trim();

            if (definitions.Length > 0)
            {
                string[] preProcessorDefinesArray = definitions.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string preProcessorDefine in preProcessorDefinesArray)
                {
                    // the below code is to support valued defines as per https://msdn.microsoft.com/en-us/library/vstudio/hhzbb5c8%28v=vs.100%29.aspx

                    Match matchResult = RegexPreProcesserDefines.Match(preProcessorDefine);

                    if (matchResult.Success)
                    {
                        definesHandler.Define(matchResult.Groups[1].Value.Trim(), matchResult.Groups[2].Value);
                    }
                    else
                    {
                        if (!preProcessorDefine.Contains("$(INHERIT)"))
                        {
                            definesHandler.Define(preProcessorDefine.Trim(), "1");
                            //by default user assigned pre-processor defines have a value of 1
                        }
                    }
                }
            }

            if (undefinitions.Length > 0)
            {
                string[] preProcessorUnDefinesArray = undefinitions.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var preProcessorUnDefine in preProcessorUnDefinesArray)
                {
                    if (!preProcessorUnDefine.Contains("$(NOINHERIT)"))
                    {
                        definesHandler.UnDefine(preProcessorUnDefine.Trim());
                    }
                }
            }
        }