Esempio n. 1
0
 public void Gen(GeneratorFolder folder)
 {
     folder.AddFile($"{context.Name}Components", GenComponentsFile());
     //自动System生成
     foreach (var type in componentTypes)
     {
         var cleanup = type.GetCustomAttribute <LiteECS.CleanupAttribute>();
         if (cleanup == null)
         {
             continue;
         }
         CSharpWriter writer    = new CSharpWriter();
         string       className = $"{type.Name}CleanupSystem";
         writer.Write($"using TComponent = {type.FullName};").NewLine();
         writer.Write($"public class {className} : LiteECS.ICleanupSystem");
         using (new CSharpWriter.Scop(writer))
         {
             if (cleanup.Mode == LiteECS.CleanupMode.DestroyEntity)
             {
                 GenDestroySystem(type, writer, className);
             }
             else
             {
                 GenRemoveSystem(type, writer, className);
             }
         }
         folder.AddFile(className, writer.ToString());
     }
 }
Esempio n. 2
0
        public static string Gen(string className, string context, ECSSystemGenerateType type, string componentName = null)
        {
            CSharpWriter writer = new CSharpWriter(true);

            if (type < ECSSystemGenerateType.GroupExecute)
            {
                writer.Write($"public class {className} : LiteECS.I{type}System");
                using (new CSharpWriter.Scop(writer))
                {
                    writer.Write($"{context}Context context;").NewLine();
                    writer.Write($"public {className}({context}Context context)");
                    using (new CSharpWriter.Scop(writer))
                    {
                        writer.Write("this.context = context;");
                    }
                    writer.Write($"public void On{type}()");
                    writer.EmptyScop();
                }
            }
            else if (type == ECSSystemGenerateType.GroupExecute)
            {
                GenGroupExecuteSystem(writer, className, context, componentName);
            }
            else if (type == ECSSystemGenerateType.ReactiveExecute)
            {
                GenReactiveExecuteSystem(writer, className, context, componentName);
            }
            return(writer.ToString());
        }
Esempio n. 3
0
 private void GenRemoveSystem(Type type, CSharpWriter writer, string className)
 {
     writer.Write($"private readonly {className}Context context;").NewLine();
     writer.Write($"public {className}({context.Name}Context context)");
     using (new CSharpWriter.Scop(writer))
     {
         writer.Write("this.context = context;");
     }
     writer.Write($"public void OnCleanup()");
     using (new CSharpWriter.Scop(writer))
     {
         writer.Write($"context.RemoveAll<TComponent>();");
     }
 }
Esempio n. 4
0
        public static string Format(string cSharpCode)
        {
            // We prepare stuff
            CodeConfiguration configuration = CodeConfiguration.Default;

            configuration.Formatting.Tabs.TabStyle = TabStyle.Tabs;
            configuration.Formatting.LineSpacing.RemoveConsecutiveBlankLines = true;
            configuration.Formatting.Regions.Style = RegionStyle.NoDirective;
            CodeArranger       codeArranger = new CodeArranger(configuration);
            ICodeElementParser parser       = new CSharpParser {
                Configuration = configuration
            };

            // We parse
            StringReader reader = new StringReader(cSharpCode);
            ReadOnlyCollection <ICodeElement> elements = parser.Parse(reader);

            // We reorganize the AST
            elements = codeArranger.Arrange(elements);

            // We rewrite
            ICodeElementWriter codeWriter = new CSharpWriter {
                Configuration = configuration
            };
            StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);

            codeWriter.Write(elements, writer);
            return(writer.ToString());
        }
Esempio n. 5
0
        public void Writes_writes_a_single_statement()
        {
            writer.AppendStatement("var testVariable = 0;");
            writer.Write("test-project");
            var programText = File.ReadAllText("test-project/Program.cs");

            Assert.That(programText.Contains("var testVariable = 0;"));
        }
Esempio n. 6
0
 public static void GenReactiveExecuteSystem(CSharpWriter writer, string className, string context, string componentName)
 {
     if (string.IsNullOrEmpty(componentName))
     {
         componentName = $"I{context}Component";
     }
     writer.Write($"using TComponent = {componentName};").NewLine();
     writer.Write($"public class {className} : LiteECS.ReactiveExecuteSystem<{context}Entity, TComponent>");
     using (new CSharpWriter.Scop(writer))
     {
         writer.Write($" private {context}Context Context => context as {context}Context;").NewLine();
         writer.Write($"public {className}({context}Context context):base(context)");
         writer.EmptyScop();
         writer.Write($"protected override void OnExecuteEntity({context}Entity entity, TComponent component)");
         writer.EmptyScop();
     }
 }
Esempio n. 7
0
        public string Describe(Expression expression)
        {
            var stringWriter = new StringWriter();
            var csharpWriter = new CSharpWriter(new TextFormatter(stringWriter));

            csharpWriter.Write(expression);

            return(stringWriter.ToString());
        }
Esempio n. 8
0
        public static void GenerateContextExtern(Type type, CSharpWriter writer)
        {
            string shortName = CommandShortName(type);

            writer.Write($"Add{shortName}(this EntityCommand.ICommandContext context, long id{ToParamList(type)})");
            using (new CSharpWriter.Scop(writer))
            {
                writer.Write($"if(context.IsValid(id)");
                using (new CSharpWriter.Scop(writer))
                {
                    writer.Write($"var cmd = context.NewCommand<{TypeUtil.TypeToName(type)}>();");
                    var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
                    foreach (var field in fields)
                    {
                        writer.Write($"cmd.{field.Name} = new{field.Name};").NewLine();
                    }
                    writer.Write($"context.AddCommand(id, cmd)");
                }
            }
        }
Esempio n. 9
0
        private void BuildTree(string stem, string content)
        {
            Environment.CurrentDirectory = DirRef.ProjectDir().Dir("Grammar");

            var grammarSource = FileRef.From($"./{stem}.Grammar");

            var dests = FileRef.From(grammarSource.Directory + "/Out/" + grammarSource.BaseName).With(".Out");

            var raw = Parser.Parse(grammarSource);

            if (raw != null)
            {
                var builder = new Build.GrammarBuilder(raw);

                var grammar = builder.Build();
                new Dumper(grammar).Dump(dests);

                var ccOut = DirRef.ProjectDir().Dir("..").Dir("Lingu.CC").Dir("Gen");

                var csharp = new CSharpWriter(grammar, grammarSource, ccOut);
                csharp.Write();

                Debug.Assert(grammar.Eof != null);

                var dfaSet = new CompactDfaReader(new BinReader(new CompactDfaWriter(grammar).Write())).Read();

                //var dfaSet = new DfaSet(grammar.Dfas.Select(dfa => dfa.Convert()).ToArray(), grammar.StateToDfa, grammar.SpacingDfa.Convert());

                var context = new LinguContext(
                    grammar.Symbols,
                    grammar.Productions,
                    grammar.ParseTable,
                    dfaSet);

                Source source;

                if (File.Exists(content))
                {
                    source = Source.FromFile(content);
                }
                else
                {
                    source = Source.FromString(content);
                }

                var tree = context.Try(source);

                new TreeDumper(dests.Add(".Tree")).Dump(tree);
            }
        }
Esempio n. 10
0
        public static void GenerateExterns(IEnumerable <Type> types, string className, string filePath)
        {
            CSharpWriter writer = new CSharpWriter();

            writer.Write($"public static {className}");
            using (new CSharpWriter.Scop(writer))
            {
                foreach (var type in types)
                {
                    GenerateContextExtern(type, writer);
                }
            }
            FileUtil.WriteFileWithCreateFolder(filePath, writer.ToString());
        }
	static void Main (string [] args)
	{
		var a = Expression.Parameter (typeof (int), "a");
		var b = Expression.Parameter (typeof (int), "b");

		var return_label = Expression.Label (typeof (int), "ret");

		var c = Expression.Parameter (typeof (int), "c");
		var d = Expression.Parameter (typeof (int), "d");

		var left = Expression.Block (
			new [] { c },
			Expression.Assign (c, Expression.AddChecked (a, b)),
			Expression.AddAssignChecked (c, Expression.Constant (42)),
			c);

		var right = Expression.Block (
			new [] { d },
			Expression.Assign (d, Expression.SubtractChecked (a, b)),
			Expression.SubtractAssignChecked (d, Expression.Constant (42)),
			d);

		var conditional = Expression.Condition (
			Expression.GreaterThan (a, b),
			left, right);

		var lambda = Expression.Lambda<Func<int, int, int>> (conditional, a, b);

		var add = lambda.Compile ();

		Console.WriteLine (add (2, 2));

		Console.WriteLine ("--------------------");

		var csharp = new CSharpWriter (new TextFormatter (Console.Out));

		csharp.Write (lambda);

		Console.WriteLine ("--------------------");

		Console.WriteLine (typeof (Expression).GetProperty ("DebugView", BindingFlags.NonPublic | BindingFlags.NonPublic | BindingFlags.Instance).GetValue (lambda, new object [0]));
	}
    static void Main(string [] args)
    {
        var a = Expression.Parameter(typeof(int), "a");
        var b = Expression.Parameter(typeof(int), "b");

        var return_label = Expression.Label(typeof(int), "ret");

        var c = Expression.Parameter(typeof(int), "c");
        var d = Expression.Parameter(typeof(int), "d");

        var left = Expression.Block(
            new [] { c },
            Expression.Assign(c, Expression.AddChecked(a, b)),
            Expression.AddAssignChecked(c, Expression.Constant(42)),
            c);

        var right = Expression.Block(
            new [] { d },
            Expression.Assign(d, Expression.SubtractChecked(a, b)),
            Expression.SubtractAssignChecked(d, Expression.Constant(42)),
            d);

        var conditional = Expression.Condition(
            Expression.GreaterThan(a, b),
            left, right);

        var lambda = Expression.Lambda <Func <int, int, int> > (conditional, a, b);

        var add = lambda.Compile();

        Console.WriteLine(add(2, 2));

        Console.WriteLine("--------------------");

        var csharp = new CSharpWriter(new TextFormatter(Console.Out));

        csharp.Write(lambda);

        Console.WriteLine("--------------------");

        Console.WriteLine(typeof(Expression).GetProperty("DebugView", BindingFlags.NonPublic | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(lambda, new object [0]));
    }
Esempio n. 13
0
 private void GenDestroySystem(Type type, CSharpWriter writer, string className)
 {
     writer.Write($"private readonly {context.Name}Context context;").NewLine();
     writer.Write($"public {className}({context.Name}Context context)");
     using (new CSharpWriter.Scop(writer))
     {
         writer.Write($"this.context = context;");
     }
     writer.Write($"public void OnCleanup()");
     using (new CSharpWriter.Scop(writer))
     {
         writer.Write("var group = context.CreatGroup<TComponent>();").NewLine();
         writer.Write("while (group.MoveNext())");
         using (new CSharpWriter.Scop(writer))
         {
             writer.Write("group.Entity.Destroy();");
         }
     }
 }
Esempio n. 14
0
        private void BuildCC0()
        {
            var projectDir = DirRef.ProjectDir();
            var cc0        = projectDir.Dir("..").Dir("LinguCC0");
            var genDir     = cc0.Dir("Gen");

            Environment.CurrentDirectory = genDir;

            var grammarSource = FileRef.From($"./Lingu.Grammar");
            var outs          = FileRef.From("./Lingu").Add(".Out");

            var raw = Parser.Parse(grammarSource);

            if (raw != null)
            {
                var builder = new GrammarBuilder(raw);

                var grammar = builder.Build();
                new Dumper(grammar).Dump(outs);

                var csharp = new CSharpWriter(grammar, grammarSource, genDir);
                csharp.Write();
            }
        }
Esempio n. 15
0
        private string GenComponentsFile()
        {
            CSharpWriter writer = new CSharpWriter();

            writer.Write($"public static partial class {context.Name}Components");
            using (new CSharpWriter.Scop(writer))
            {
                writer.Write($"static {context.Name}Components()");
                using (new CSharpWriter.Scop(writer))
                {
                    writer.Write($"OnContextCreat = DoContentInit;").NewLine();
                    writer.Write($"ComponentCount = {componentTypes.Count};").NewLine();
                    writer.Write("InitComponentsIdentity();");
                }
                writer.Write($"static void InitComponentsIdentity()");
                using (new CSharpWriter.Scop(writer))
                {
                    for (int i = 0; i < componentTypes.Count; ++i)
                    {
                        var type = componentTypes[i];
                        if (typeof(LiteECS.IUnique).IsAssignableFrom(type))
                        {
                            writer.Write($"LiteECS.ComponentIdentity<{type.FullName}>.Unique = true;").NewLine();
                        }
                        writer.Write($"LiteECS.ComponentIdentity<{type.FullName}>.Id = {i};");
                        if (i < componentTypes.Count - 1)
                        {
                            writer.NewLine();
                        }
                    }
                }
                writer.Write($"static void DoContentInit({context.Name}Context context)");
                using (new CSharpWriter.Scop(writer))
                {
                    for (int i = 0; i < componentTypes.Count; ++i)
                    {
                        var type = componentTypes[i];

                        if (typeof(LiteECS.IUnique).IsAssignableFrom(type))
                        {
                            writer.Write($"context.InitUniqueComponentCollector<{type.FullName}>();");
                        }
                        else
                        {
                            writer.Write($"context.InitComponentCollector<{type.FullName}>();");
                        }
                        if (i < componentTypes.Count - 1)
                        {
                            writer.NewLine();
                        }
                    }
                }
            }
            return(writer.ToString());
        }
Esempio n. 16
0
	static void Main (string [] args)
	{
		var a = Expression.Parameter (typeof (int), "a");
		var b = Expression.Parameter (typeof (int), "b");

        var scope = Expression.Parameter(typeof(object), "scope");

        var instance = Expression.Constant(scope);

        var binder = Binder.GetMember(
        CSharpBinderFlags.None,
        "Text",
        typeof(object),
        new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }
        );
        
        var expArgs = new List<Expression>() { instance };

        var binderM = Binder.InvokeMember(
        CSharpBinderFlags.None,
        "ToString",
        null,
        typeof(object),
        expArgs.Select(x => CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null))
        );

        Expression resultm = Expression.Dynamic(binderM, typeof(object), expArgs);

        Expression result = Expression.Dynamic(binder, typeof(object), instance);

		var return_label = Expression.Label (typeof (int), "ret");

		var c = Expression.Parameter (typeof (int), "c");
		var d = Expression.Parameter (typeof (int), "d");

		var left = Expression.Block (
			new [] { c },
			Expression.Assign (c, Expression.AddChecked (a, b)),
			Expression.AddAssignChecked (c, Expression.Constant (42)),
			c);

		var right = Expression.Block (
			new [] { d },
			Expression.Assign (d, Expression.SubtractChecked (a, b)),
			Expression.SubtractAssignChecked (d, Expression.Constant (42)),
            result,
            resultm,
			d);

		var conditional = Expression.Condition (
			Expression.GreaterThan (a, b),
			left, right);

        var lambda = Expression.Lambda<Func<int, int, int>> (conditional, a, b);

		var add = lambda.Compile ();

		//Console.WriteLine (add (2, 2));

		Console.WriteLine ("--------------------");

		var csharp = new CSharpWriter (new TextFormatter (Console.Out));

		csharp.Write (lambda);

		Console.WriteLine ("--------------------");

		Console.WriteLine (typeof (Expression).GetProperty ("DebugView", BindingFlags.NonPublic | BindingFlags.NonPublic | BindingFlags.Instance).GetValue (lambda, new object [0]));
	}
Esempio n. 17
0
        public static string Gen(string name, string upLevelContext)
        {
            CSharpWriter writer = new CSharpWriter(true);

            writer.Write($"public interface I{name}Component : LiteECS.IComponent");
            writer.EmptyScop();

            writer.Write($"public class {name}Entity : LiteECS.EntityT<I{name}Component>");
            using (new CSharpWriter.Scop(writer))
            {
                writer.Write($"public {name}Entity(LiteECS.Context context, int id) : base(context, id)");
                writer.EmptyScop(false);
            }

            writer.Write($"public static partial class {name}Components");
            using (new CSharpWriter.Scop(writer))
            {
                writer.Write($"public static System.Action<{name}Context> OnContextCreat;").NewLine();
                writer.Write($"public static int ComponentCount {{ get; private set; }}").NewLine();
            }

            writer.Write($"public class {name}Context : LiteECS.ContextT<{name}Entity>");
            using (new CSharpWriter.Scop(writer))
            {
                if (!string.IsNullOrEmpty(upLevelContext))
                {
                    writer.Write($"public {upLevelContext}Context {upLevelContext}{{ get; private set; }}").NewLine();
                }
                //Ctor
                writer.Write($"protected {name}Context(int componentTypeCount) : base(componentTypeCount, CreatFunc)");
                writer.EmptyScop();

                //CreatFunc
                writer.Write($"private static {name}Entity CreatFunc(LiteECS.Context context, int id)");
                using (new CSharpWriter.Scop(writer))
                {
                    writer.Write($"return new {name}Entity(context, id);");
                }

                //Creat
                writer.Write($"public static {name}Context Creat()");
                using (new CSharpWriter.Scop(writer))
                {
                    writer.Write($"var contxt = new {name}Context({name}Components.ComponentCount);").NewLine();
                    writer.Write($"{name}Components.OnContextCreat(contxt);").NewLine();
                    writer.Write("return contxt;");
                }
                if (!string.IsNullOrEmpty(upLevelContext))
                {
                    writer.Write($"public void Set{upLevelContext}( {upLevelContext}Context {upLevelContext.ToLower()} )");
                    using (new CSharpWriter.Scop(writer))
                    {
                        writer.Write($"{upLevelContext} = {upLevelContext.ToLower()};");
                    }
                }
            }


            return(writer.ToString());
        }
Esempio n. 18
0
        private static void WriteProtocol(XContainer doc, CSharpWriter w)
        {
            // for writing the high level API
            var hlw = new CSharpWriter();

            var protocolElement = doc.Element(ProtocolElement);

            if (protocolElement == null)
            {
                throw new Exception("No protocol element found!");
            }

            var protocolName = protocolElement.Attribute(NameAttrib).Value;

            w.Line($"// Protocol: {protocolName}");
            w.Line();

            w.Line("using System;");
            w.Line("using System.Runtime.InteropServices;");
            w.Line();

            hlw.Line("namespace OpenWindow.Backends.Wayland.Managed");
            hlw.OpenBlock();

            w.Line("namespace OpenWindow.Backends.Wayland");
            w.OpenBlock();

            var interfaceElements = protocolElement.Elements(InterfaceElement);
            var ifaces            = interfaceElements.Select(e => new Interface(e)).ToArray();
            var messages          = ifaces.SelectMany(iface => iface.Requests.Concat(iface.Events)).ToArray();
            var ifaceCount        = ifaces.Length;
            var msgCount          = messages.Length;

            _protocolClassName = Util.ToPascalCase(protocolName) + "Bindings";

            w.Line($"internal static unsafe partial class {_protocolClassName}");
            w.OpenBlock();

            w.Line("private static bool _loaded;");
            w.Line();
            w.Line("public static wl_interface* Interfaces;");
            w.Line("private static wl_message* _messages;");
            w.Line("private static wl_interface** _signatureTypes;");
            w.Line();
            w.Line($"private static readonly int InterfaceCount = {ifaceCount};");
            w.Line($"private static readonly int MessageCount = {msgCount};");

            w.Line();

            foreach (var iface in ifaces)
            {
                w.Line($"public const string {iface.RawName}_name = \"{iface.RawName}\";");
            }

            w.Line();

            w.Line("public static void Load()");
            w.OpenBlock();
            w.Line("if (_loaded)");
            w.LineIndented("return;");
            w.Line("_loaded = true;");
            w.Line();

            w.Line("Interfaces = (wl_interface*) Marshal.AllocHGlobal(sizeof(wl_interface) * InterfaceCount);");
            w.Line("_messages = (wl_message*) Marshal.AllocHGlobal(sizeof(wl_message) * MessageCount);");

            w.Line();

            w.Line();

            for (var i = 0; i < ifaces.Length; i++)
            {
                var iface = ifaces[i];
                w.Line($"Util.CreateInterface(&Interfaces[{i}], \"{iface.RawName}\", {iface.Version}, {iface.Requests.Length}, {iface.Events.Length});");
            }

            w.Line();

            var signatureTypes = new List <string>();
            var typeMap        = new List <(string TypeStr, int Index)>();

            var typeMapIndex = 0;

            // handle messages with the most types first so we don't create duplicates
            foreach (var message in messages.OrderByDescending(m => m.SigTypes.Length))
            {
                var typesIndex = 0;
                var typeStr    = ';' + string.Join(";", message.SigTypes) + ';';
                var match      = typeMap.Where(t => t.TypeStr.Contains(typeStr));
                if (match.Any())
                {
                    var m      = match.First();
                    var offset = m.TypeStr.Take(m.TypeStr.IndexOf(typeStr)).Count(c => c == ';');
                    typeMap.Add((typeStr, m.Index + offset));
                    typesIndex = m.Index + offset;
                }
                else
                {
                    typeMap.Add((typeStr, typeMapIndex));
                    typesIndex = typeMapIndex;

                    foreach (var type in message.SigTypes)
                    {
                        var sigTypeStr = type == string.Empty ? null : type;
                        signatureTypes.Add(sigTypeStr);
                        typeMapIndex++;
                    }
                }

                message.SigTypesIndex = typesIndex;
            }

            w.Line($"_signatureTypes = (wl_interface**) Marshal.AllocHGlobal(sizeof(void*) * {signatureTypes.Count});");
            for (int i = 0; i < signatureTypes.Count; i++)
            {
                var stype    = signatureTypes[i];
                var stypeStr = stype == null ? "null" : stype + ".Interface";
                w.Line($"_signatureTypes[{i}] = {stypeStr};");
            }

            w.Line();

            for (var i = 0; i < messages.Length; i++)
            {
                var message = messages[i];
                w.Line($"Util.CreateMessage(&_messages[{i}], \"{message.RawName}\", \"{message.Signature}\", &_signatureTypes[{message.SigTypesIndex}]);");
            }

            w.Line();

            var msgIndex = 0;

            for (var i = 0; i < ifaces.Length; i++)
            {
                var iface   = ifaces[i];
                var reqInit = iface.Requests.Length == 0 ? "null" : $"&_messages[{msgIndex}]";
                w.Line($"Interfaces[{i}].Requests = {reqInit};");
                msgIndex += iface.Requests.Length;

                var evInit = iface.Events.Length == 0 ? "null" : $"&_messages[{msgIndex}]";
                w.Line($"Interfaces[{i}].Events = {evInit};");
                msgIndex += iface.Events.Length;
            }

            w.CloseBlock();
            w.Line();

            w.Line("public static void Unload()");
            w.OpenBlock();
            w.Line("if (!_loaded)");
            w.LineIndented("return;");
            w.Line("_loaded = false;");
            w.Line();

            w.Line("for (var i = 0; i < InterfaceCount; i++)");
            w.LineIndented($"Marshal.FreeHGlobal((IntPtr) Interfaces[i].Name);");

            w.Line();

            w.Line("for (var i = 0; i < MessageCount; i++)");
            w.OpenBlock();
            w.Line("Marshal.FreeHGlobal((IntPtr) _messages[i].Name);");
            w.Line("Marshal.FreeHGlobal((IntPtr) _messages[i].Signature);");
            w.CloseBlock();

            w.Line();
            w.Line("Marshal.FreeHGlobal((IntPtr) _messages);");
            w.Line("Marshal.FreeHGlobal((IntPtr) _signatureTypes);");
            w.Line("Marshal.FreeHGlobal((IntPtr) Interfaces);");
            w.CloseBlock();

            w.Line();

            foreach (var iface in ifaces)
            {
                hlw.Line($"internal unsafe partial struct {iface.ClsName}");
                hlw.OpenBlock();
                hlw.Line($"public static IntPtr Interface => (IntPtr) {iface.RawName}.Interface;");
                hlw.Line($"public static {iface.ClsName} Null => new {iface.ClsName}();");
                hlw.Line($"public readonly {iface.RawName}* Pointer;");
                hlw.Line("public bool IsNull => Pointer == null;");
                if (iface.Events.Length != 0)
                {
                    // cached delegates to prevent GC
                    foreach (var ev in iface.Events)
                    {
                        hlw.Line($"private {_protocolClassName}.{GetDelegateName(iface, ev)} _{ev.RawName};");
                    }
                    // unmanaged listener, needs to be freed by users
                    hlw.Line($"private {_protocolClassName}.{iface.RawName}_listener* _listener;");
                }
                // we need to initialize all fields in the ctor
                var eventInitializer = iface.Events.Length == 0 ? "" :
                                       " _listener = null; " + string.Join(' ', iface.Events.Select(ev => "_" + ev.RawName + " = null;"));
                hlw.Line($"public {iface.ClsName}({iface.RawName}* ptr) {{ Pointer = ptr;{eventInitializer} }}");
                hlw.Line($"public static implicit operator {iface.ClsName}({iface.RawName}* ptr) => new {iface.ClsName}(ptr);");
                hlw.Line($"public static explicit operator {iface.ClsName}(wl_proxy* ptr) => new {iface.ClsName}(({iface.RawName}*) ptr);");

                WriteRequests(iface, w, hlw);
                WriteEvents(iface, w, hlw);

                if (!iface.Requests.Any(m => "destructor".Equals(m.Type)))
                {
                    hlw.Line("public void Destroy() { if (!IsNull) WaylandClient.wl_proxy_destroy((wl_proxy*) Pointer); }");
                }

                hlw.CloseBlock();
            }

            w.CloseBlock(); // class {ProtocolName}Bindings*/

            w.Line();

            // dummy structs for typed pointers
            for (var i = 0; i < ifaces.Length; i++)
            {
                var iface = ifaces[i];
                WriteDescription(iface.Element, w);
                w.Line($"internal struct {iface.RawName} {{ public static unsafe wl_interface* Interface => &{_protocolClassName}.Interfaces[{i}]; }}");
            }

            w.Line();

            foreach (var iface in ifaces)
            {
                foreach (var e in iface.Enums)
                {
                    w.Line();
                    WriteEnum(iface, e, w);
                }
            }

            w.CloseBlock();   // namespace
            hlw.CloseBlock(); // namespace

            w.Line();
            w.Write(hlw);
        }
Esempio n. 19
0
 public void Setup()
 {
     writer = new CSharpWriter();
     writer.Write("test-project");
 }
Esempio n. 20
0
        private void OnWizardCreate()
        {
            var cfg = ECSConfig.Instance.Contexts.Find(it => it.Name == contextNames[selectContextIdx]);

            if (cfg == null)
            {
                EditorUtility.DisplayDialog("错误", "选择的Context不存在,可能被移动位置或者删除\n,请重新创建", "ok");
                return;
            }
            int    typeIdx   = (int)createType;
            string dirPath   = Path.Combine(cfg.DirectoryPath, catalogs[typeIdx][selectCatalogIdx[typeIdx]]);
            string className = nameInput;

            if (createType == CreateType.Component)
            {
                if (!nameInput.StartsWith(cfg.Name))
                {
                    className = $"{cfg.Name}{nameInput}";
                }
            }
            else if (createType == CreateType.System)
            {
                if (!nameInput.StartsWith(cfg.Name))
                {
                    className = $"{cfg.Name}{nameInput}System";
                }
                else
                {
                    className = $"{nameInput}System";
                }
            }
            System.Reflection.Assembly assembly = ECSContextUtils.GetECSAssembly(cfg);
            if (assembly != null)
            {
                if (assembly.GetType(className) != null)
                {
                    EditorUtility.DisplayDialog("错误", $"创建失败,类型 {className} 已存在", "ok");
                    return;
                }
            }
            string filePath = Path.Combine(dirPath, $"{className}.cs");

            if (File.Exists(filePath))
            {
                EditorUtility.DisplayDialog("错误", "创建失败,目标文件已存在", "ok");
                return;
            }
            string content = null;

            if (createType == CreateType.Component)
            {
                CSharpWriter writer = new CSharpWriter(true);
                writer.Write($"public partial class {className} : I{cfg.Name}Component");
                writer.EmptyScop();
                content = writer.ToString();
            }
            else if (createType == CreateType.System)
            {
                string component = null;
                if (systemType >= ECSSystemGenerateType.GroupExecute && componentTypes != null)
                {
                    component = componentTypes[componentSelectIdx];
                }
                content = SystemGenertor.Gen(className, cfg.Name, systemType, component);
            }
            File.WriteAllText(filePath, content, System.Text.Encoding.UTF8);
            AssetDatabase.ImportAsset(filePath);
            if (OpenAfterCreate)
            {
                var obj = AssetDatabase.LoadMainAssetAtPath(filePath);
                if (obj)
                {
                    AssetDatabase.OpenAsset(obj);
                }
            }
        }