Example #1
0
        public static void GenerateClassSerializer(ProtoMessage m, CodeWriter cw)
        {
            if (m.OptionExternal || m.OptionType == "interface")
            {
                //Don't make partial class of external classes or interfaces
                //Make separate static class for them
                cw.Bracket(m.OptionAccess + " static class " + m.SerializerType);
            }
            else
            {
                cw.Attribute("System.Serializable()");
                cw.Bracket(m.OptionAccess + " partial " + m.OptionType + " " + m.SerializerType);
            }

            GenerateReader(m, cw);

            GenerateWriter(m, cw);
            foreach (ProtoMessage sub in m.Messages.Values)
            {
                cw.WriteLine();
                GenerateClassSerializer(sub, cw);
            }
            cw.EndBracket();
            cw.WriteLine();
            return;
        }
        public string GenerateInterface(Service service, Interface intr)
        {
            CodeWriter writer = new CodeWriter();
            writer.WriteLine("define([\"dojo/request\", \"dojo/json\"], function (request, JSON) {");
            writer.PushIdent();
            writer.WriteLine("var serviceClient = {");
            writer.PushIdent();
            writer.WriteLine("urlString: '',");
            writer.WriteLine();

            int methodCount = intr.Methods.Count;
            for (int i = 0; i < methodCount; i++)
            {
                Method method = intr.Methods[i];
                string comma = i < methodCount - 1 ? "," : "";
                writer.Write(GenerateMethod(intr, method).Trim());
                writer.WriteLineNoIdent(comma);
                writer.WriteLine();
            }
            writer.PopIdent();
            writer.WriteLine("}");
            writer.WriteLine("return serviceClient;");
            writer.PopIdent();
            writer.Write("});");
            return writer.Code;
        }
Example #3
0
 private string Translate(CompilationUnit typedCompilationUnit)
 {
     var code = new CodeWriter();
     WriteAction write = typedCompilationUnit.Visit(csTranslator);
     write(code);
     return code.ToString();
 }
 protected virtual void WriteDataContextCtors(CodeWriter writer, Database schema, Type contextBaseType, GenerationContext context)
 {
     // ctor taking a connections tring
     WriteDataContextCtor(writer, schema, contextBaseType,
            new[] { new ParameterDefinition { Name = "connectionString", Type = typeof(string) } },
            new[] { "connectionString" },
            new[] { typeof(string) },
            context);
     // the two constructors below have the same prototype, so they are mutually exclusive
     // the base class requires a IVendor
     if (!WriteDataContextCtor(writer, schema, contextBaseType,
                          new[] { new ParameterDefinition { Name = "connection", Type = typeof(IDbConnection) } },
                          new[] { "connection", writer.GetNewExpression(writer.GetMethodCallExpression(writer.GetLiteralFullType(context.SchemaLoader.Vendor.GetType()))) },
                          new[] { typeof(IDbConnection), typeof(IVendor) },
                          context))
     {
         // OR the base class requires no IVendor
         WriteDataContextCtor(writer, schema, contextBaseType,
                              new[] { new ParameterDefinition { Name = "connection", Type = typeof(IDbConnection) } },
                              new[] { "connection" },
                              new[] { typeof(IDbConnection) },
                              context);
     }
     // ctor(string, MappingSource)
     WriteDataContextCtor(writer, schema, contextBaseType,
            new[] {
                new ParameterDefinition { Name = "connection", Type = typeof(string) },
                new ParameterDefinition { Name = "mappingSource", Type = typeof(MappingSource) },
            },
            new[] { "connection", "mappingSource" },
            new[] { typeof(string), typeof (MappingSource) },
            context);
     // ctor(IDbConnection, MappingSource)
     WriteDataContextCtor(writer, schema, contextBaseType,
             new[] {
                 new ParameterDefinition { Name = "connection", Type = typeof(IDbConnection) },
                 new ParameterDefinition { Name = "mappingSource", Type = typeof(MappingSource) },
             },
             new[] { "connection", "mappingSource" },
             new[] { typeof(IDbConnection), typeof(MappingSource) },
             context);
     // just in case you'd like to specify another vendor than the one who helped generating this file
     WriteDataContextCtor(writer, schema, contextBaseType,
             new[] {
                 new ParameterDefinition { Name = "connection", Type = typeof(IDbConnection) },
                 new ParameterDefinition { Name = "vendor", Type = typeof(IVendor) },
             },
             new[] { "connection", "vendor" },
             new[] { typeof(IDbConnection), typeof(IVendor) },
             context);
     WriteDataContextCtor(writer, schema, contextBaseType,
             new[] {
                 new ParameterDefinition { Name = "connection", Type = typeof(IDbConnection) },
                 new ParameterDefinition { Name = "mappingSource", Type = typeof(MappingSource) },
                 new ParameterDefinition { Name = "vendor", Type = typeof(IVendor) },
             },
             new[] { "connection", "mappingSource", "vendor" },
             new[] { typeof(IDbConnection), typeof(MappingSource), typeof(IVendor) },
             context);
 }
Example #5
0
 /// <summary>
 /// Saves the file header to disk.
 /// </summary>
 internal override void SaveHeader(CodeWriter writer, PFile file)
 {
     writer.Write(file.Name);
     writer.Write(new FileInfo(file.FilePath).Length);
     writer.Write(file.LastModified.Ticks);
     writer.Write((int) file.Attributes);
 }
 protected virtual void WriteDataContextProcedures(CodeWriter writer, DbLinq.Schema.Dbml.Database schema, GenerationContext context)
 {
     foreach (var procedure in schema.Functions)
     {
         WriteDataContextProcedure(writer, procedure, context);
     }
 }
        private void WriteDataContextProcedure(CodeWriter writer, Function procedure, GenerationContext context)
        {
            if (procedure == null || procedure.Name == null)
            {
                //Logger.Write(Level.Error, "CodeGenStoredProc: Error L33 Invalid storedProcedure object");
                writer.WriteCommentLine("error L33 Invalid storedProcedure object");
                return;
            }

            var functionAttribute = NewAttributeDefinition<FunctionAttribute>();
            functionAttribute["Name"] = procedure.Name;
            functionAttribute["IsComposable"] = procedure.IsComposable;

            SpecificationDefinition specifications;
            if (procedure.AccessModifierSpecified)
                specifications = GetSpecificationDefinition(procedure.AccessModifier);
            else
                specifications = SpecificationDefinition.Public;
            if (procedure.ModifierSpecified)
                specifications |= GetSpecificationDefinition(procedure.Modifier);

            using (writer.WriteAttribute(functionAttribute))
            using (writer.WriteMethod(specifications, GetProcedureName(procedure),
                                      GetProcedureType(procedure), GetProcedureParameters(procedure)))
            {
                string result = WriteProcedureBodyMethodCall(writer, procedure, context);
                WriteProcedureBodyOutParameters(writer, procedure, result, context);
                WriteProcedureBodyReturnValue(writer, procedure, result, context);
            }
            writer.WriteLine();
        }
Example #8
0
        /// <summary>
        /// Generates the properties.
        /// </summary>
        /// <param name='template'>
        /// if true it will generate only properties that are not included by default, because of the [generate=false] option.
        /// </param>
        static void GenerateProperties(ProtoMessage m, CodeWriter cw)
        {
            foreach (Field f in m.Fields.Values)
            {
                if (f.OptionExternal)
                    cw.WriteLine("//" + GenerateProperty(f) + " // Implemented by user elsewhere");
                else
                {
                    if (f.Comments != null)
                        cw.Summary(f.Comments);
                    cw.WriteLine(GenerateProperty(f));
                    cw.WriteLine();
                }

            }

            //Wire format field ID
            #if DEBUG
            cw.Comment("ProtocolBuffers wire field id");
            foreach (Field f in m.Fields.Values)
            {
                cw.WriteLine("public const int " + f.CsName + "FieldID = " + f.ID + ";");
            }
            #endif
        }
        protected virtual void WriteClass(CodeWriter writer, Table table, Database schema, GenerationContext context)
        {
            writer.WriteLine();

            string entityBase = context.Parameters.EntityBase;
            if (string.IsNullOrEmpty(entityBase))
                entityBase = schema.EntityBase;

            var specifications = SpecificationDefinition.Partial;
            if (table.Type.AccessModifierSpecified)
                specifications |= GetSpecificationDefinition(table.Type.AccessModifier);
            else
                specifications |= SpecificationDefinition.Public;
            if (table.Type.ModifierSpecified)
                specifications |= GetSpecificationDefinition(table.Type.Modifier);

            var tableAttribute = NewAttributeDefinition<TableAttribute>();
            tableAttribute["Name"] = table.Name;
            using (writer.WriteAttribute(tableAttribute))
            using (writer.WriteClass(specifications,
                                     table.Type.Name, entityBase, context.Parameters.EntityInterfaces))
            {
                WriteClassHeader(writer, table, context);
                WriteCustomTypes(writer, table, schema, context);
                WriteClassExtensibilityDeclarations(writer, table, context);
                WriteClassProperties(writer, table, context);
                if (context.Parameters.GenerateEqualsHash)
                    WriteClassEqualsAndHash(writer, table, context);
                WriteClassChildren(writer, table, schema, context);
                WriteClassParents(writer, table, schema, context);
                WriteClassChildrenAttachment(writer, table, schema, context);
                WriteClassCtor(writer, table, schema, context);
            }
        }
Example #10
0
        private string generateUpdateBody(Table table, List<Column> keyColumns, List<Column> updateColumns)
        {
            CodeWriter writer = new CodeWriter();
            writer.WriteLineFormat("UPDATE [{0}].[{1}]", table.Schema.Name, table.Name);
            writer.WriteLine("SET");
            writer.PushIdent();
            for (int i = 0; i < updateColumns.Count; i++)
            {
                Column column = updateColumns[i];
                string and = i < updateColumns.Count - 1 ? "," : "";
                string cond = string.Format("[{0}] = @{0} {1}", column.Name, and).Trim();
                writer.WriteLine(cond);
            }
            writer.PopIdent();

            writer.WriteLine("WHERE");
            writer.PushIdent();
            for (int i = 0; i < keyColumns.Count; i++)
            {
                Column column = keyColumns[i];
                string and = i < keyColumns.Count - 1 ? "AND" : "";
                string cond = string.Format("[{0}] = @{0} {1}", column.Name, and).Trim();
                writer.WriteLine(cond);
            }
            writer.PopIdent();
            return writer.Code;
        }
Example #11
0
 static void GenerateEnums(ProtoMessage m, CodeWriter cw)
 {
     foreach (ProtoEnum me in m.Enums.Values)
     {
         GenerateEnum(me, cw);
     }
 }
 public override string GenerateClass(Schema schema)
 {
     CodeWriter writer = new CodeWriter();
     string className = "DataStore";
     writer.WriteLine(USING_STRING);
     writer.WriteLine();
     writer.WriteLine("namespace DataAccess");
     writer.WriteLine("{");
     writer.PushIdent();
     writer.WriteLineFormat("public class {0}: DatabaseContext, IDataStore", className);
     writer.WriteLine("{");
     writer.PushIdent();
     writer.WriteLineFormat("public {0}(IDbConnection connection, IDbTransaction transaction) : base(connection, transaction) {{ }}", className);
     writer.WriteLineFormat("public {0}(IDbConnection connection) : base(connection, null) {{ }}", className);
     writer.WriteLine();
     
     foreach (StoredProcedure sp in schema.StoredProcedures)
     {
         string methodHeader = "public " + generateMethodHeader(sp);
         string methodBody = GenerateMethodBody(sp);
         writer.WriteLine(methodHeader);
         writer.WriteLine(methodBody);
         writer.WriteLine();
     }
     writer.PopIdent();
     writer.WriteLine("}");
     writer.PopIdent();
     writer.WriteLine("}");
     return writer.Code;
 }
Example #13
0
        public string GenerateInterface(Service service, Interface intr)
        {
            CodeWriter writer = new CodeWriter();
            writer.WriteFormat(".factory(\"{0}Client\", function($http, serviceUrl)", intr.Name);
            writer.WriteLineNoIdent(" {");
            writer.PushIdent();
            writer.WriteLine("return {");

            int methodCount = intr.Methods.Count;
            for (int i = 0; i < methodCount; i++)
            {
                writer.PushIdent();
                Method method = intr.Methods[i];
                string comma = i < methodCount - 1 ? "," : "";
                writer.Write(GenerateMethod(intr, method).Trim());
                writer.WriteLineNoIdent(comma);
                writer.WriteLine();
                writer.PopIdent();
            }
 
            writer.WriteLine("}");
            writer.PopIdent();
            writer.WriteLine("})");
            return writer.Code;
        }
Example #14
0
        public string GenerateClass(Service service, Interface intr)
        {
            CodeWriter writer = new CodeWriter();
            writer.WriteLine(HEADER);
            writer.WriteLineFormat("package {0}", service.Name);
            writer.WriteLine("{");
            writer.PushIdent();
            writer.WriteLine(IMPORT);
            writer.WriteLine();
            writer.WriteLineFormat("public class {0}Client", intr.Name);
            writer.WriteLine("{");
            writer.PushIdent();
            writer.WriteLine("public var url: String = \"\";");
            writer.WriteLine(LOAD);
            writer.WriteLine();

            foreach(Method method in intr.Methods)
            {
                writer.WriteLine(GenerateMethodHeader(intr, method));
                writer.WriteLine("{"); 
                writer.PushIdent();
                writer.WriteLine(GenerateMethodBody(intr, method));
                writer.PopIdent();
                writer.WriteLine("}");
                writer.WriteLine();
            }
            writer.PopIdent();
            writer.WriteLine("}");
            writer.PopIdent();
            writer.WriteLine("}");
            return writer.Code;
        }
        public override void WriteClassHeader(CodeWriter writer, DbLinq.Schema.Dbml.Table table, GenerationContext context)
        {
            using (writer.WriteRegion(string.Format("{0} handling", typeof(INotifyPropertyChanging).Name)))
            {
                const string eventName = "PropertyChanging"; // do not change, part of INotifyPropertyChanging
                const string emptyArgs = "emptyChangingEventArgs";

                // event
                writer.WriteEvent(SpecificationDefinition.Public, eventName, typeof(PropertyChangingEventHandler).Name);
                writer.WriteLine();
                // empty event arg
                writer.WriteField(SpecificationDefinition.Private | SpecificationDefinition.Static,
                                  writer.GetAssignmentExpression(emptyArgs, writer.GetNewExpression(
                                                                                writer.GetMethodCallExpression(typeof(PropertyChangingEventArgs).Name, "\"\""))),
                                  typeof(PropertyChangingEventArgs).Name);
                // method
                using (writer.WriteMethod(SpecificationDefinition.Protected | SpecificationDefinition.Virtual,
                                          sendPropertyChangingMethod, null))
                {
                    using (writer.WriteIf(writer.GetDifferentExpression(eventName, writer.GetNullExpression())))
                    {
                        writer.WriteLine(writer.GetStatement(writer.GetMethodCallExpression(eventName,
                                                                                            writer.GetThisExpression(), emptyArgs)));
                    }
                }
            }
        }
Example #16
0
 private static void GenerateFileFooter(StreamWriter file, CodeWriter writer)
 {
     writer.Indent--;
     writer.WriteLine("}"); // end of test type
     writer.Indent--;
     writer.WriteLine("}"); // namesapce
     file.Close();
 }
 public override string Generate(Schema schema)
 {
     CodeWriter writer = new CodeWriter();
     writer.WriteLine("----- TABLES -----");
     writer.Write(GenerateTables(schema));
     writer.WriteLine("----- STORED PROCEDURES -----");
     writer.Write(GenerateStoredProcedures(schema));
     return writer.Code;
 }
Example #18
0
 private string GenerateDropIfExists(string spName)
 {
     CodeWriter writer = new CodeWriter();
     writer.WriteLineFormat("IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'{0}') AND type in (N'P', N'PC'))", spName);
     writer.PushIdent();
     writer.WriteLineFormat("DROP PROCEDURE {0};", spName);
     writer.PopIdent();
     writer.WriteLine("GO");
     return writer.Code;
 }
Example #19
0
 public static void GenerateEnum(ProtoEnum me, CodeWriter cw)
 {
     cw.Bracket("public enum " + me.CsType);
     foreach (var epair in me.Enums)
     {
         cw.Summary(epair.Comment);
         cw.WriteLine(epair.Name + " = " + epair.Value + ",");
     }
     cw.EndBracket();
     cw.WriteLine();
 }
Example #20
0
 public override string GenerateTables(Schema schema)
 {
     CodeWriter writer = new CodeWriter();
     foreach(Table table in schema.Tables)
     {
         writer.WriteLineFormat("-- {0} --", table.Name);
         writer.WriteLine(GenerateSqlCreate(table));
         writer.WriteLine();
     }
     return writer.Code;
 }
        public override string GenerateSqlCreate(Table table)
        {
            CodeWriter writer = new CodeWriter();
            writer.WriteLineFormat("create table [{0}].[{1}](", table.Schema.Name, table.Name);
            writer.PushIdent();
            int colCount = table.Columns.Count;
            int conCount = table.Constraints.Count;
            for (int i = 0; i < colCount; i++)
            {
                Column col = table.Columns[i];
                DataType dt = TypeMap == null ? col.DataType : TypeMap.MapDataType(col.DataType);
                string nullDef = col.IsNullable? "null": "not null";
                string autoIncrementDef = col.IsAutoIncremented ? "identity(1, 1)" : "";
                string colDef = string.Format("[{0}] {1} {2} {3}", col.Name, dt.FullName, nullDef, autoIncrementDef).Trim();
                string comma = (i < colCount - 1 || conCount > 0) ? "," : "";
                writer.WriteLineFormat("{0}{1}", colDef, comma);
            }

            
            for (int i = 0; i < conCount; i++)
            {
                TableConstraint con = table.Constraints[i];
                string conDef = null;
                if (con.Type == ConstraintType.PrimaryKey)
                {
                    string colDef = StringUtils.GenerateCommaSeparatedString(con.Columns, "[", "]");
                    conDef = string.Format("constraint [{0}] primary key({1})", con.Name, colDef);
                }
                else if (con.Type == ConstraintType.Unique)
                {
                    string colDef = StringUtils.GenerateCommaSeparatedString(con.Columns, "[", "]");
                    conDef = string.Format("constraint [{0}] unique({1})", con.Name, colDef);
                }
                else if (con.Type == ConstraintType.Check)
                {
                    CheckConstraint chk = (CheckConstraint)con;
                    conDef = string.Format("constraint [{0}] check {1}", chk.Name, chk.Clause);
                }
                else if (con.Type == ConstraintType.ForeignKey)
                {
                    ForeignKeyConstraint fk = (ForeignKeyConstraint)con;
                    string colDef = StringUtils.GenerateCommaSeparatedString(fk.Columns, "[", "]");
                    string refColDef = StringUtils.GenerateCommaSeparatedString(fk.ReferencedColumns, "[", "]");
                    conDef = string.Format("constraint [{0}] foreign key({1}) references [{2}].[{3}]({4}) on update {5} on delete {6}", 
                        fk.Name, colDef, con.Table.Schema.Name, fk.ReferencedTable, refColDef, fk.UpdateRule, fk.DeleteRule);
                }
                string comma = i < conCount - 1 ? "," : "";
                writer.WriteLineFormat("{0}{1}", conDef, comma);
            }

            writer.PopIdent();
            writer.Write(")");
            return writer.Code;
        }
Example #22
0
    public CodeWriter Main( IEnumerable value )
    {
        var writer = new CodeWriter();

        writer.Indent = 0;
        writer.Append( "SELECT " );
        {
            var list = new List<CodeWriter>();
            CodeWriter temp;

            list.Add( this.Invoke( "SetField", "Temp" ) );
            foreach (var item in value)
            {
                temp = this.Invoke( "SetField", item );
                list.Add( temp );
            }

            writer.AppendType = AppendType.SpaceLastLine;
            for (var listI = 0; listI < list.Count; listI++)
            {
                var codeWriter = list[listI];
                writer.Append( codeWriter );
                if (listI < list.Count - 1)
                    writer.AppendText( ",\r\n" );
            }
            writer.AppendType = AppendType.EmptyLastLine;
        }
        writer.Indent = 0;
        writer.AppendLine( " FROM [Table]" );
        writer.Append( "// " );
        {
            var list = new List<CodeWriter>();
            CodeWriter temp;

            list.Add( this.Invoke( "SetField", "Temp" ) );
            foreach (var item in value)
            {
                temp = this.Invoke( "SetField", item );
                list.Add( temp );
            }

            writer.AppendType = AppendType.CloneLastLine;
            for (var listI = 0; listI < list.Count; listI++)
            {
                var codeWriter = list[listI];
                writer.Append( codeWriter );
                if (listI < list.Count - 1)
                    writer.AppendText( ",\r\n" );
            }
            writer.AppendType = AppendType.EmptyLastLine;
        }

        return writer;
    }
Example #23
0
 public string GenerateMethod(Interface intr, Method method)
 {
     CodeWriter writer = new CodeWriter();
     writer.Write(generateMethodHeader(intr, method));
     writer.WriteLine(" {");
     writer.PushIdent();
     writer.WriteLine(generateMethodBody(intr, method));
     writer.PopIdent();
     writer.Write("}");
     return writer.Code;
 }
        protected virtual void WriteClasses(CodeWriter writer, Database schema, GenerationContext context)
        {
            IEnumerable<Table> tables = schema.Tables;

            var types = context.Parameters.GenerateTypes;
            if (types.Count > 0)
                tables = tables.Where(t => types.Contains(t.Type.Name));

            foreach (var table in tables)
                WriteClass(writer, table, schema, context);
        }
Example #25
0
 public override string GenerateStoredProcedures(Schema schema)
 {
     CodeWriter writer = new CodeWriter();
     foreach (StoredProcedure sp in schema.StoredProcedures)
     {
         writer.WriteLineFormat("-- {0} --", sp.Name);
         sp.Definition = DUMMY_BODY;
         writer.WriteLine(GenerateStoredProcedureCreate(sp));
         writer.WriteLine();
     }
     return writer.Code;
 }
Example #26
0
    public CodeWriter SetField_Default( string field )
    {
        var writer = new CodeWriter();

        writer.Indent = 0;
        writer.Append( "'[" );
        writer.AppendText( field );
        writer.Indent = 0;
        writer.Append( "]' = @" );
        writer.AppendText( field );

        return writer;
    }
Example #27
0
 private static void GenerateCheck(CodeWriter writer, string typeName)
 {
     var helperName = "Check" + typeName;
     writer.WriteLine("public void {0}({1} value, string format)", helperName, typeName);
     writer.WriteLine("{");
     writer.WriteLine("    var parsed = Format.Parse(format);");
     writer.WriteLine("    formatter.Clear();");
     writer.WriteLine("    formatter.Append(value, parsed);");
     writer.WriteLine("    var result = formatter.ToString();");
     writer.WriteLine("    var clrResult = value.ToString(format, CultureInfo.InvariantCulture);");
     writer.WriteLine("    Assert.Equal(clrResult, result);");
     writer.WriteLine("}");
     writer.WriteLine("");
 }
Example #28
0
        public override string GenerateSqlCreate(Table table)
        {
            CodeWriter writer = new CodeWriter();
            writer.WriteLine("DELIMITER $$");
            writer.WriteLineFormat("create table `{0}`.`{1}`(", table.Schema.Name, table.Name);
            writer.PushIdent();
            int colCount = table.Columns.Count;
            int conCount = table.Constraints.Where(c => c.Type != ConstraintType.Check).Count();
            for (int i = 0; i < colCount; i++)
            {
                Column col = table.Columns[i];
                DataType dt = TypeMap == null ? col.DataType : TypeMap.MapDataType(col.DataType);
                string nullDef = col.IsNullable? "null": "not null";
                string autoIncrementDef = col.IsAutoIncremented ? "auto_increment" : "";
                string colDef = string.Format("`{0}` {1} {2} {3}", col.Name, dt.FullName, nullDef, autoIncrementDef).Trim();
                string comma = (i < colCount - 1 || conCount > 0) ? "," : "";
                writer.WriteLineFormat("{0}{1}", colDef, comma);
            }

            
            for (int i = 0; i < conCount; i++)
            {
                TableConstraint con = table.Constraints[i];
                string conDef = null;
                if (con.Type == ConstraintType.PrimaryKey)
                {
                    string colDef = StringUtils.GenerateCommaSeparatedString(con.Columns, "`", "`");
                    conDef = string.Format("constraint `{0}` primary key({1})", con.Name, colDef);
                }
                else if (con.Type == ConstraintType.Unique)
                {
                    string colDef = StringUtils.GenerateCommaSeparatedString(con.Columns, "`", "`");
                    conDef = string.Format("constraint `{0}` unique({1})", con.Name, colDef);
                }
                else if (con.Type == ConstraintType.ForeignKey)
                {
                    ForeignKeyConstraint fk = (ForeignKeyConstraint)con;
                    string colDef = StringUtils.GenerateCommaSeparatedString(fk.Columns, "`", "`");
                    string refColDef = StringUtils.GenerateCommaSeparatedString(fk.ReferencedColumns, "`", "`");
                    conDef = string.Format("constraint `{0}` foreign key({1}) references `{2}`.`{3}`({4}) on update {5} on delete {6}", 
                        fk.Name, colDef, con.Table.Schema.Name, fk.ReferencedTable, refColDef, fk.UpdateRule, fk.DeleteRule);
                }
                string comma = i < conCount - 1 ? "," : "";
                writer.WriteLineFormat("{0}{1}", conDef, comma);
            }

            writer.PopIdent();
            writer.Write(")$$");
            return writer.Code;
        }
Example #29
0
    private static void GenerateTimeSpanTests()
    {
        var file = new StreamWriter(@"..\..\..\tests\TimeSpanFormattingTests.Generated.cs");
        var writer = new CodeWriter(file);

        GenerateFileHeader(writer);

        GenerateCheck(writer, "TimeSpan");
        GenerateTest(writer, "TimeSpan", 'G');
        //GenerateTest(writer, "TimeSpan", 'g');
        GenerateTest(writer, "TimeSpan", 'c');

        GenerateFileFooter(file, writer);
    }
Example #30
0
 protected override string WriteProcedureBodyMethodCall(CodeWriter writer, DbLinq.Schema.Dbml.Function procedure, GenerationContext context)
 {
     // picrap: there may be some more elegant ways to invoke a stored procedure, because ExecuteMethodCall is 
     //         for internal use only
     const string result = "result";
     var parametersBuilder = new StringBuilder();
     foreach (var parameter in procedure.Parameters)
     {
         if (parameter.DirectionIn)
             parametersBuilder.AppendFormat(", {0}", parameter.Name);
     }
     writer.WriteLine(string.Format("var {0} = ExecuteMethodCall(this, (MethodInfo)MethodBase.GetCurrentMethod(){1});",
                                    result, parametersBuilder));
     return result;
 }
 /// <inheritdoc />
 public override void DumpTo(CodeWriter writer)
 {
     ElementType.DumpTo(writer);
 }
        private void GenerateManageMethodHead(CodeWriter cw, Method method)
        {
            var param = string.Join(", ", method.InputTypes.Select(v => v.GetTypeCppOgiginal()));

            cw.WriteLine($"virtual {method.ReturnType.GetTypeCppOgiginal()} {method.Name}({param}) override;");
        }
 private void GenerateProperty(IPropertySymbol ps, CodeWriter cw)
 {
     MemberPrefix(cw, ps.Type.FullyQualifiedName(), ps.Name);
     cw.AppendLine();
     PropertyBlock(ps, cw, "." + ps.Name);
 }
Example #34
0
 protected override void categoryTypeToEDialect(CodeWriter writer)
 {
     writer.append("native category");
 }
 public override void WriteAttribute(CodeWriter writer)
 {
     writer.WriteLine("[global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)]");
 }
Example #36
0
    static void TypeGen(Type t)
    {
        //TODO: we only handle ordinary classes for now

        /*
         *       else if (t.IsSubclassOf (typeof (Delegate))) {
         *       Console.WriteLine ("Ignoring delegate: " + t.Name);
         *       return;
         *       }
         */

        cur_type = NsToC(ns) + "_" + CamelToC(t.Name);
        //CurType = NsToFlat (ns) + t.Name;
        CurType = CsTypeToG(t);
        if (t.IsInterface)
        {
            CurTypeClass = GToGI(CurType);
        }
        else
        {
            CurTypeClass = GToGC(CurType);
        }

        //ns = t.Namespace;
        string fname = NsToFlat(ns).ToLower() + t.Name.ToLower();

        C = new CodeWriter(target_dir + fname + ".c");
        H = new CodeWriter(target_dir + fname + ".h");
        Hindex.WriteLine("#include <" + fname + ".h" + ">");


        string H_id = "__" + NsToFlat(ns).ToUpper() + "_" + t.Name.ToUpper() + "_H__";

        H.WriteLine("#ifndef " + H_id);
        H.WriteLine("#define " + H_id);
        H.WriteLine();

        H.WriteLine("#include <glib.h>");
        H.WriteLine("#include <glib-object.h>");

        foreach (string include in extincludes)
        {
            H.WriteLine("#include <" + include + ">");
        }

        H.WriteLine();

        if (t.BaseType != null && IsRegistered(t.BaseType) && !IsExternal(t.BaseType))
        {
            H.WriteLine("#include \"" + NsToFlat(t.BaseType.Namespace).ToLower() + t.BaseType.Name.ToLower() + ".h\"");
        }

        foreach (string ext_ns in namespaces)
        {
            H.WriteLine("#include \"" + NsToFlat(ext_ns).ToLower() + "types.h\"");
        }

        H.WriteLine();

        if (disable_glib)
        {
            H.WriteLine("#ifdef __cplusplus");
            H.WriteLine("extern \"C\" {", false);
            H.WriteLine("#endif /* __cplusplus */");
        }
        else
        {
            H.WriteLine("G_BEGIN_DECLS");
        }

        H.WriteLine();

        C.WriteLine("#include \"" + fname + ".h" + "\"");

        Type[] ifaces;
        ifaces = t.GetInterfaces();
        foreach (Type iface in ifaces)
        {
            if (!IsRegistered(iface))
            {
                continue;
            }

            string iface_fname = NsToFlat(ns).ToLower() + iface.Name.ToLower();
            C.WriteLine("#include \"" + iface_fname + ".h" + "\"");
        }

        C.WriteLine("#include <mono/metadata/object.h>");
        C.WriteLine("#include <mono/metadata/debug-helpers.h>");
        C.WriteLine("#include <mono/metadata/appdomain.h>");
        C.WriteLine();

        if (t.IsClass)
        {
            ClassGen(t);
        }
        else if (t.IsInterface)
        {
            ClassGen(t);
        }
        else if (t.IsEnum)
        {
            EnumGen(t);
        }

        H.WriteLine();

        if (disable_glib)
        {
            H.WriteLine("#ifdef __cplusplus");
            H.WriteLine("}", false);
            H.WriteLine("#endif /* __cplusplus */");
        }
        else
        {
            H.WriteLine("G_END_DECLS");
        }

        H.WriteLine();

        H.WriteLine("#endif /* " + H_id + " */");

        C.Close();
        H.Close();
    }
Example #37
0
    public static void Generate(string assembly, string target)
    {
        target_dir = target + Path.DirectorySeparatorChar;

        if (Directory.Exists(target_dir))
        {
            Console.WriteLine("Error: Target directory " + target_dir + " already exists.");
            return;
        }

        Directory.CreateDirectory(target_dir);

        Assembly a = Assembly.LoadFrom(assembly);

        Console.WriteLine();
        Console.WriteLine("References (not followed):");
        foreach (AssemblyName reference in a.GetReferencedAssemblies())
        {
            Console.WriteLine("  " + reference.Name);
        }
        Console.WriteLine();

        dllname = Path.GetFileName(assembly);
        AssemblyGen(a);

        //we might not want to do this in future
        File.Copy(dllname, target_dir + dllname);

        string soname = "lib" + NsToFlat(Path.GetFileNameWithoutExtension(assembly)).ToLower() + ".so";

        //create the static makefile
        StreamWriter makefile = new StreamWriter(File.Create(target_dir + "Makefile"));
        StreamReader sr       = new StreamReader(Assembly.GetAssembly(typeof(cilc)).GetManifestResourceStream("res-Makefile"));

        makefile.Write(sr.ReadToEnd());
        sr.Close();
        makefile.Close();

        //create makefile defs
        CodeWriter makefile_defs = new CodeWriter(target_dir + "defs.mk");

        makefile_defs.Indenter = "\t";
        makefile_defs.WriteLine("ASSEMBLY = " + assembly);
        makefile_defs.WriteLine("SONAME = " + soname);
        makefile_defs.WriteLine(@"OBJS = $(shell ls *.c | sed -e 's/\.c/.o/')");

        if (extpkgs != String.Empty)
        {
            makefile_defs.WriteLine("EXTRAINCLUDES = $(shell pkg-config --cflags" + extpkgs + ")");
            makefile_defs.WriteLine("EXTRALIBS = $(shell pkg-config --libs" + extpkgs + ")");
        }
        makefile_defs.Close();

        Console.WriteLine();

        //identify hits on types that were registered too late
        foreach (string tn in registered_types)
        {
            if (registry_hits.Contains(tn))
            {
                Console.WriteLine("Warning: " + tn + " was incorrectly registered after it was needed instead of before. Consider re-ordering.");
            }
        }

        MakeReport(registry_hits, "Type registry missed hits", 20);
        Console.WriteLine();
        //TODO: this count is now wrong
        Console.WriteLine(registered_types.Count + " types generated/seen in " + namespaces.Length + " namespaces; " + warnings_ignored + " types ignored");
        Console.WriteLine();
    }
 private void AppendArgumentList(CodeWriter cw, ImmutableArray <IParameterSymbol> parameters, Func <IParameterSymbol, string> ParamPrinter) =>
 cw.Append(string.Join(", ", parameters.Select(ParamPrinter)));
 protected override void WriteBody(CodeWriter writer)
 {
     SourceWriterExtensions.WriteMethodStringOverloadBody(writer, method, opt, false);
 }
Example #40
0
 public void ToDialect(CodeWriter writer)
 {
     writer.append("{");
     this.expression.ToDialect(writer);
     writer.append("}");
 }
        private async Task WriteSerializeMethod(
            CodeWriter writer,
            IInputClassDescriptor descriptor)
        {
            await writer.WriteIndentAsync().ConfigureAwait(false);

            if (_languageVersion == LanguageVersion.CSharp_8_0)
            {
                await writer.WriteAsync("public object? Serialize(object? value)")
                .ConfigureAwait(false);
            }
            else
            {
                await writer.WriteAsync("public object Serialize(object value)")
                .ConfigureAwait(false);
            }
            await writer.WriteLineAsync().ConfigureAwait(false);

            await writer.WriteIndentAsync().ConfigureAwait(false);

            await writer.WriteAsync('{').ConfigureAwait(false);

            await writer.WriteLineAsync().ConfigureAwait(false);

            using (writer.IncreaseIndent())
            {
                await writer.WriteIndentedLineAsync(
                    "if (!_needsInitialization)")
                .ConfigureAwait(false);

                await writer.WriteIndentedLineAsync("{")
                .ConfigureAwait(false);

                using (writer.IncreaseIndent())
                {
                    await writer.WriteIndentedLineAsync(
                        "throw new InvalidOperationException(")
                    .ConfigureAwait(false);

                    using (writer.IncreaseIndent())
                    {
                        await writer.WriteIndentedLineAsync(
                            "$\"The serializer for type `{Name}` has not been initialized.\");")
                        .ConfigureAwait(false);

                        ;
                    }
                }

                await writer.WriteIndentedLineAsync("}")
                .ConfigureAwait(false);

                await writer.WriteLineAsync().ConfigureAwait(false);

                await WriteNonNullHandling(writer).ConfigureAwait(false);

                await writer.WriteIndentAsync().ConfigureAwait(false);

                await writer.WriteAsync($"var input = ({descriptor.Name})value;")
                .ConfigureAwait(false);

                await writer.WriteLineAsync().ConfigureAwait(false);

                await writer.WriteIndentAsync().ConfigureAwait(false);

                if (_languageVersion == LanguageVersion.CSharp_8_0)
                {
                    await writer.WriteAsync("var map = new Dictionary<string, object?>();")
                    .ConfigureAwait(false);
                }
                else
                {
                    await writer.WriteAsync("var map = new Dictionary<string, object>();")
                    .ConfigureAwait(false);
                }
                await writer.WriteLineAsync().ConfigureAwait(false);

                await writer.WriteLineAsync().ConfigureAwait(false);

                foreach (IInputFieldDescriptor field in descriptor.Fields)
                {
                    string typeName = field.InputObjectType is null
                        ? field.Type.NamedType().Name.Value
                        : field.InputObjectType.Name;

                    IType  type           = field.Type.IsNonNullType() ? field.Type.InnerType() : field.Type;
                    string serializerName = SerializerNameUtils.CreateSerializerName(type);

                    await writer.WriteIndentedLineAsync(
                        $"if (input.{GetPropertyName(field.Name)}.HasValue)")
                    .ConfigureAwait(false);

                    await writer.WriteIndentedLineAsync("{");

                    using (writer.IncreaseIndent())
                    {
                        await writer.WriteIndentAsync().ConfigureAwait(false);

                        await writer.WriteAsync($"map.Add(\"{field.Field.Name}\", ")
                        .ConfigureAwait(false);

                        await writer.WriteAsync($"{serializerName}(").ConfigureAwait(false);

                        await writer.WriteAsync($"input.{GetPropertyName(field.Name)}.Value));")
                        .ConfigureAwait(false);

                        await writer.WriteLineAsync().ConfigureAwait(false);
                    }

                    await writer.WriteIndentedLineAsync("}");

                    await writer.WriteLineAsync().ConfigureAwait(false);
                }

                await writer.WriteIndentAsync().ConfigureAwait(false);

                await writer.WriteAsync("return map;").ConfigureAwait(false);

                await writer.WriteLineAsync().ConfigureAwait(false);
            }

            await writer.WriteIndentAsync().ConfigureAwait(false);

            await writer.WriteAsync('}').ConfigureAwait(false);

            await writer.WriteLineAsync().ConfigureAwait(false);

            await writer.WriteLineAsync().ConfigureAwait(false);

            await WriteTypeSerializerMethodsAsync(writer, descriptor).ConfigureAwait(false);
        }
Example #42
0
 protected override void AsTextStartArguments(CodeWriter writer, RenderFlags flags)
 {
     writer.Write(ParseTokenStart);
 }
        /// <summary>
        ///   Creates a deterministic or nondeterministic fault effect body.
        /// </summary>
        private BlockSyntax CreateBody(IMethodSymbol method, BlockSyntax originalBody, SyntaxNode baseEffect)
        {
            var lineAdjustedOriginalBody = originalBody.AppendLineDirective(-1).PrependLineDirective(originalBody.GetLineNumber());
            var componentType            = _typeLookup[method.ContainingType.BaseType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)];
            var faultEffectType          = _typeLookup[method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)];
            var faults         = _faults[componentType];
            var baseStatements = !method.ReturnsVoid
                                ? new[] { Syntax.ReturnStatement(baseEffect) }
                                : new[] { Syntax.ExpressionStatement(baseEffect), Syntax.ReturnStatement() };

            IMethodSymbol methodSymbol;
            BlockSyntax   body = null;

            if (_methodLookup.TryGetValue(method.OverriddenMethod.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), out methodSymbol))
            {
                var priorityFaults    = faults.Where(fault => fault.GetPriority(Compilation) == method.ContainingType.GetPriority(Compilation)).ToArray();
                var overridingEffects = priorityFaults.Where(f => f.GetMembers().OfType <IMethodSymbol>().Any(m => m.Overrides(methodSymbol))).ToArray();
                var overrideCount     = overridingEffects.Length;

                if (overrideCount > 1)
                {
                    var fieldName   = _faultChoiceFields[Tuple.Create(methodSymbol, priorityFaults[0].GetPriority(Compilation))];
                    var effectIndex = Array.IndexOf(priorityFaults, faultEffectType);
                    var choiceField = Syntax.MemberAccessExpression(Syntax.ThisExpression(), fieldName);

                    var levelCondition = Syntax.ValueNotEqualsExpression(choiceField, Syntax.LiteralExpression(effectIndex));
                    var ifStatement    = Syntax.IfStatement(levelCondition, baseStatements).NormalizeWhitespace().WithTrailingNewLines(1);

                    if (overridingEffects.Last().Equals(faultEffectType))
                    {
                        var levelChoiceVariable = "levelChoice".ToSynthesized();
                        var levelCountVariable  = "levelCount".ToSynthesized();

                        var writer = new CodeWriter();
                        writer.AppendLine("unsafe");
                        writer.AppendBlockStatement(() =>
                        {
                            writer.AppendLine($"var {levelChoiceVariable} = stackalloc int[{overrideCount}];");
                            writer.AppendLine($"var {levelCountVariable} = 0;");

                            for (var i = 0; i < overrideCount; ++i)
                            {
                                var effectType = overridingEffects[i].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
                                var index      = Array.IndexOf(priorityFaults, overridingEffects[i]);

                                writer.AppendLine($"if ({_tryActivate}((({effectType})this).{"fault".ToSynthesized()}))");
                                writer.IncreaseIndent();
                                writer.AppendLine($"{levelChoiceVariable}[{levelCountVariable}++] = {index};");
                                writer.DecreaseIndent();
                                writer.NewLine();
                            }

                            writer.AppendLine($"{fieldName} = {levelCountVariable} == 0 ? - 1 : {levelChoiceVariable}[ChooseIndex({levelCountVariable})];");
                        });

                        var selectionStatement = SyntaxFactory.ParseStatement(writer.ToString());
                        body = SyntaxFactory.Block(selectionStatement, (StatementSyntax)ifStatement, lineAdjustedOriginalBody);
                    }
                    else
                    {
                        body = SyntaxFactory.Block((StatementSyntax)ifStatement, lineAdjustedOriginalBody);
                    }
                }
            }

            if (body == null)
            {
                var writer = new CodeWriter();
                writer.AppendLine($"if (!{_tryActivate}(this.{"fault".ToSynthesized()}))");
                writer.AppendBlockStatement(() =>
                {
                    // Optimization: If we're normalizing a non-void returning method without ref/out parameters and
                    // the fault effect simply returns a constant value of primitive type, we generate code to check whether the non-fault
                    // value for the case that the fault is not activated (which is always the first case) actually differs
                    // from the constant value returned by the fault effect when the fault is activated. If both values are
                    // the same, the activation of the fault will have no effect, so we can undo it, reducing the number
                    // of transitions that have to be checked
                    var signatureAllowsOptimization =
                        !method.ReturnsVoid && CanBeCompared(method.ReturnType) && method.Parameters.All(parameter => parameter.RefKind == RefKind.None);
                    var faultEffectReturn = originalBody.Statements.Count == 1 ? originalBody.Statements[0] as ReturnStatementSyntax : null;
                    var isConstantValue   = faultEffectReturn != null && SemanticModel.GetConstantValue(faultEffectReturn.Expression).HasValue;

                    if (signatureAllowsOptimization && isConstantValue)
                    {
                        writer.AppendLine($"var {"tmp".ToSynthesized()} = {baseEffect.ToFullString()};");
                        writer.AppendLine($"if ({"tmp".ToSynthesized()} == {faultEffectReturn.Expression.ToFullString()})");
                        writer.AppendBlockStatement(() => { writer.AppendLine($"{_undoActivation}(this.{"fault".ToSynthesized()});"); });
                        writer.AppendLine($"return {"tmp".ToSynthesized()};");
                    }
                    else
                    {
                        foreach (var statement in baseStatements)
                        {
                            writer.AppendLine(statement.NormalizeWhitespace().ToFullString());
                        }
                    }
                });

                writer.NewLine();
                body = SyntaxFactory.Block(SyntaxFactory.ParseStatement(writer.ToString()), lineAdjustedOriginalBody);
            }

            return(body.PrependLineDirective(-1));
        }
        private async Task <string> WriteTypeSerializerMethodAsync(
            CodeWriter writer,
            IType type,
            ISet <string> generatedMethods)
        {
            IType  actualType     = type.IsNonNullType() ? type.InnerType() : type;
            string serializerName = SerializerNameUtils.CreateSerializerName(actualType);

            if (!generatedMethods.Add(serializerName))
            {
                return(serializerName);
            }

            if (actualType.IsListType())
            {
                IType elementType = type.ElementType();

                string itemSerializer = await WriteTypeSerializerMethodAsync(
                    writer, elementType, generatedMethods)
                                        .ConfigureAwait(false);

                await writer.WriteLineAsync().ConfigureAwait(false);

                await WriteTypeSerializerMethodHeaderAsync(writer, serializerName)
                .ConfigureAwait(false);

                await writer.WriteIndentedLineAsync("{").ConfigureAwait(false);

                using (writer.IncreaseIndent())
                {
                    if (!type.IsNonNullType())
                    {
                        await WriteNonNullHandling(writer).ConfigureAwait(false);

                        await writer.WriteLineAsync().ConfigureAwait(false);
                    }

                    await writer.WriteIndentedLineAsync(
                        "IList source = (IList)value;")
                    .ConfigureAwait(false);

                    if (_languageVersion == LanguageVersion.CSharp_8_0)
                    {
                        await writer.WriteIndentedLineAsync(
                            "object?[] result = new object?[source.Count];")
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        await writer.WriteIndentedLineAsync(
                            "object[] result = new object[source.Count];")
                        .ConfigureAwait(false);
                    }

                    await writer.WriteIndentedLineAsync(
                        "for(int i = 0; i < source.Count; i++)")
                    .ConfigureAwait(false);

                    await writer.WriteIndentedLineAsync("{").ConfigureAwait(false);

                    using (writer.IncreaseIndent())
                    {
                        await writer.WriteIndentedLineAsync(
                            $"result[i] = {itemSerializer}(source[i]);")
                        .ConfigureAwait(false);
                    }
                    await writer.WriteIndentedLineAsync("}").ConfigureAwait(false);

                    await writer.WriteIndentedLineAsync("return result;").ConfigureAwait(false);
                }
                await writer.WriteIndentedLineAsync("}").ConfigureAwait(false);
            }
            else
            {
                await WriteTypeSerializerMethodHeaderAsync(writer, serializerName)
                .ConfigureAwait(false);

                await writer.WriteIndentedLineAsync("{").ConfigureAwait(false);

                using (writer.IncreaseIndent())
                {
                    if (!type.IsNonNullType())
                    {
                        await WriteNonNullHandling(writer).ConfigureAwait(false);

                        await writer.WriteLineAsync().ConfigureAwait(false);
                    }

                    await writer.WriteIndentAsync().ConfigureAwait(false);

                    await writer.WriteAsync(
                        "return _")
                    .ConfigureAwait(false);

                    await writer.WriteAsync(GetFieldName(actualType.NamedType().Name))
                    .ConfigureAwait(false);

                    await writer.WriteAsync("Serializer!.Serialize(value);").ConfigureAwait(false);

                    await writer.WriteLineAsync().ConfigureAwait(false);
                }
                await writer.WriteIndentedLineAsync("}").ConfigureAwait(false);
            }

            return(serializerName);
        }
Example #45
0
        public override void WriteTo(CodeWriter writer)
        {
            if (Mask)
            {
                writer.AddCommentLine(CommentOnStart);
                using (writer.NewBlock())
                {
                    Block.WriteTo(writer);
                }
                writer.AddCommentLine(CommentOnEnd);
                return;
            }

            var         hasVar          = Var != null;
            var         varPrefix       = C.AllocTempVar();
            var         varForIndex     = $"{varPrefix}_index";
            var         varForEnd       = $"{varPrefix}_end";
            var         varForStep      = $"{varPrefix}_step";
            var         varForIsNegStep = $"{varPrefix}_isNegStep";
            var         typeName        = $"decltype({varForIndex})";
            CppTypeName expectedType    = null;

            writer.NewLine();
            if (hasVar)
            {
                expectedType = Var.GetResultType();
                typeName     = expectedType.ToString();
                writer.Write(typeName);
                writer.Write(" ");
            }
            else
            {
                writer.Write("auto ");
            }
            writer.Write(varForIndex);
            writer.Write(" = ");
            Start.WriteToWithCast(writer, expectedType);
            writer.Write(";");

            writer.NewLine();
            writer.Write(typeName);
            writer.Write(" ");
            writer.Write(varForEnd);
            writer.Write(" = ");
            End.WriteToWithCast(writer, expectedType);
            writer.Write(";");

            writer.NewLine();
            writer.Write(typeName);
            writer.Write(" ");
            writer.Write(varForStep);
            writer.Write(" = ");
            Step.WriteToWithCast(writer, expectedType);
            writer.Write(";");

            writer.NewLine();
            writer.Write("bool ");
            writer.Write(varForIsNegStep);
            writer.Write(" = ");
            writer.Write(varForStep);
            writer.Write(" <= 0;");

            writer.NewLine();
            writer.Write("for (");
            if (hasVar)
            {
                C.WriteLetExpression(writer, Var, () =>
                {
                    writer.Write(varForIndex);
                });
            }

            writer.Write("; ");

            writer.Write(varForIsNegStep);
            writer.Write(" ? ");
            writer.Write(varForIndex);
            writer.Write(" >= ");
            writer.Write(varForEnd);
            writer.Write(" : ");
            writer.Write(varForIndex);
            writer.Write(" <= ");
            writer.Write(varForEnd);

            writer.Write("; ");

            if (hasVar)
            {
                C.WriteLetExpression(writer, Var, () =>
                {
                    writer.Write(varForIndex);
                    writer.Write(" += ");
                    writer.Write(varForStep);
                });
            }
            else
            {
                writer.Write(varForIndex);
                writer.Write(" += ");
                writer.Write(varForStep);
            }

            writer.Write(")");
            using (writer.NewBlock())
            {
                Block.WriteTo(writer);
            }
        }
Example #46
0
 private void WriteSummaryAndAttributes <T>(CodeWriter code, T info)
     where T : ServiceElementWithAttributesInfo, IServiceHasSummary
 {
     WriteSummary(code, info.Summary);
     WriteAttributes(code, info.Attributes);
 }
Example #47
0
        internal static void ComputeSpace(CodeWriter writer, Node node, ref int bodyWords, ref int pointerWords)
        {
            //if([email protected] != 0 || [email protected] != 0)
            //{
            //    if ([email protected] > bodyWords)
            //        bodyWords = [email protected];
            //    if ([email protected] > pointerWords)
            //        pointerWords = [email protected];
            //    return;
            //}
            int bodyEnd = 0;

            if ([email protected] != 0)
            {
                bodyEnd = (int)(([email protected] + 1) * 16);
            }
            if ([email protected]())
            {
                foreach (var field in node.@struct.@fields)
                {
                    if (field.Union == Field.Unions.slot)
                    {
                        var slot = field.slot;
                        int len  = slot.type.GetFieldLength();

                        var relatedType = slot.type.Union == Type.Unions.@struct ? writer.Lookup([email protected]) : default(Node);
                        if (relatedType.IsValid())
                        {
                            if (relatedType.IsGroup())
                            {
                                ComputeSpace(writer, relatedType, ref bodyWords, ref pointerWords);
                            }
                        }
                        else if (len == 0)
                        {
                        }
                        else if (len == Type.LEN_POINTER)
                        {
                            int end = checked ((int)slot.offset + 1);
                            if (end > pointerWords)
                            {
                                pointerWords = end;
                            }
                        }
                        else
                        {
                            int end = checked (len * (int)(slot.offset + 1));
                            if (end > bodyEnd)
                            {
                                bodyEnd = end;
                            }
                        }
                    }
                }
            }
            foreach (var child in writer.NodesByParentScope(node.id))
            {
                if (child.IsGroup())
                {
                    ComputeSpace(writer, child, ref bodyWords, ref pointerWords);
                }
            }
            var localBodyWords = (bodyEnd + 63) / 64;

            if (localBodyWords > bodyWords)
            {
                bodyWords = localBodyWords;
            }
        }
Example #48
0
        public void GenerateCustomModel(CodeWriter writer)
        {
            writer.BeginFile().BeginNamespace(writer.Namespace);

            ulong fileId = this.requestedFiles[0].id;
            var   inFile = new HashSet <ulong>();

            var nested = new HashSet <ulong>();

            foreach (var node in this.nodes)
            {
                if (node.Union == Node.Unions.file)
                {
                    continue;
                }
                if (node.scopeId == fileId)
                {
                    inFile.Add(node.id);
                }
                var children = node.nestedNodes;
                if (children.IsValid())
                {
                    foreach (var child in children)
                    {
                        if (child.id != 0)
                        {
                            nested.Add(child.id);
                        }
                    }
                }
            }
            foreach (var node in this.nodes) //.OrderBy(x => writer.LocalName(x.displayName, false)))
            {
                if (node.Union == Node.Unions.file)
                {
                    continue;
                }
                var union = new Stack <UnionStub>();
                if (node.id != 0 && !nested.Contains(node.id) && inFile.Contains(node.id))
                {
                    writer.WriteNode(node, union);
                }
            }

            //if (writer.NeedsSerializer)
            //{
            //    writer.BeginClass(true, false, writer.Serializer, typeof(TypeModel));

            //    List<Node> generateSerializers = new List<Node>(this.nodes.Count());
            //    List<string> fieldNames = new List<string>();
            //    var uniques = new HashSet<ulong>();
            //    foreach (var node in this.nodes)
            //    {
            //        if (!uniques.Add(node.id))
            //        {
            //            throw new InvalidOperationException("Duplicate id: " + node.id + " / " + node.UniqueName() + " on " + node.displayName);
            //        }
            //        if (node.Union == Node.Unions.@struct && !node.IsGroup())
            //        {
            //            generateSerializers.Add(node);
            //            fieldNames.Add(CodeWriter.PrivatePrefix + "f_" + node.UniqueName());
            //        }
            //    }

            //    writer.DeclareFields(fieldNames, typeof(ITypeSerializer));

            //    var method = typeof(TypeModel).GetMethod("GetSerializer", getSerializerSignature);
            //    writer.BeginOverride(method);

            //    foreach (var node in generateSerializers)
            //    {
            //        writer.WriteSerializerTest(CodeWriter.PrivatePrefix + "f_" + node.UniqueName(), node, CodeWriter.PrivatePrefix + "s_" + node.UniqueName());
            //    }
            //    writer.CallBase(method);
            //    writer.EndOverride();

            //    foreach (var node in generateSerializers)
            //    {
            //        writer.WriteCustomSerializerClass(node, CodeWriter.PrivatePrefix + "s_" + node.UniqueName(), node.CustomSerializerName());
            //    }

            //    writer.BeginClass(false, true, BaseTypeName, null);
            //    foreach (var node in generateSerializers)
            //    {
            //        writer.WriteCustomReaderMethod(node);
            //    }
            //    writer.EndClass();

            //    writer.EndClass();
            //}
            writer.EndNamespace().EndFile();
        }
Example #49
0
    static void NamespaceGen(string given_ns, Type[] types)
    {
        //ns = types[0].Namespace;
        ns = given_ns;

        Hindex = new CodeWriter(target_dir + NsToFlat(ns).ToLower() + ".h");
        Hdecls = new CodeWriter(target_dir + NsToFlat(ns).ToLower() + "types.h");
        Cindex = new CodeWriter(target_dir + NsToFlat(ns).ToLower() + ".c");

        string Hindex_id = "__" + NsToFlat(ns).ToUpper() + "_H__";

        Hindex.WriteLine("#ifndef " + Hindex_id);
        Hindex.WriteLine("#define " + Hindex_id);
        Hindex.WriteLine();

        string Hdecls_id = "__" + NsToFlat(ns).ToUpper() + "_DECLS_H__";

        Hdecls.WriteLine("#ifndef " + Hdecls_id);
        Hdecls.WriteLine("#define " + Hdecls_id);
        Hdecls.WriteLine();

        Cindex.WriteLine("#include <glib.h>");
        Cindex.WriteLine("#include <glib-object.h>");
        Cindex.WriteLine("#include <mono/jit/jit.h>");
        Cindex.WriteLine();
        Cindex.WriteLine("#include <mono/metadata/object.h>");
        Cindex.WriteLine("#include <mono/metadata/debug-helpers.h>");
        Cindex.WriteLine("#include <mono/metadata/appdomain.h>");
        Cindex.WriteLine();
        Cindex.WriteLine("#ifdef CILC_BUNDLE");
        Cindex.WriteLine("#include \"bundle.h\"");
        Cindex.WriteLine("#endif");
        Cindex.WriteLine();

        Cindex.WriteLine("MonoDomain *" + NsToC(ns) + "_get_mono_domain (void)");
        Cindex.WriteLine("{");
        Cindex.WriteLine("static MonoDomain *domain = NULL;");
        Cindex.WriteLine("if (domain != NULL) return domain;");
        Cindex.WriteLine("mono_config_parse (NULL);");
        Cindex.WriteLine("domain = mono_jit_init (\"cilc\");");
        Cindex.WriteLine();
        Cindex.WriteLine("#ifdef CILC_BUNDLE");
        Cindex.WriteLine("mono_register_bundled_assemblies (bundled);");
        Cindex.WriteLine("#endif");
        Cindex.WriteLine();

        Cindex.WriteLine("return domain;");
        Cindex.WriteLine("}");
        Cindex.WriteLine();

        Cindex.WriteLine("MonoAssembly *" + NsToC(ns) + "_get_mono_assembly (void)");
        Cindex.WriteLine("{");
        Cindex.WriteLine("static MonoAssembly *assembly = NULL;");
        Cindex.WriteLine("if (assembly != NULL) return assembly;");
        Cindex.WriteLine("assembly = mono_domain_assembly_open (" + NsToC(ns) + "_get_mono_domain (), \"" + dllname + "\");");
        Cindex.WriteLine();

        Cindex.WriteLine("return assembly;");
        Cindex.WriteLine("}");
        Cindex.WriteLine();


        Cindex.WriteLine("MonoObject *" + NsToC(ns) + "_cilc_glib_gobject_get_mobject (GObject *_handle)");
        Cindex.WriteLine("{");
        //FIXME: instantiate monobject if it doesn't exist
        Cindex.WriteLine("return g_object_get_data (G_OBJECT (" + "_handle" + "), \"mono-object\");");
        Cindex.WriteLine("}");

        Cindex.WriteLine("gpointer " + NsToC(ns) + "_cilc_glib_mobject_get_gobject (MonoObject *_mono_object)");
        Cindex.WriteLine("{");
        Cindex.WriteLine("static MonoAssembly *_mono_assembly = NULL;");
        Cindex.WriteLine("static MonoMethod *_mono_method = NULL;");
        Cindex.WriteLine("static MonoClass *_mono_class = NULL;");
        Cindex.WriteLine("gpointer *retval;");
        Cindex.WriteLine();
        Cindex.WriteLine("if (_mono_assembly == NULL) {");
        Cindex.WriteLine("_mono_assembly = mono_domain_assembly_open (" + NsToC(ns) + "_get_mono_domain (), \"" + "glib-sharp" + "\");");
        Cindex.WriteLine("}");
        Cindex.WriteLine("if (_mono_class == NULL) {");
        Cindex.WriteLine("_mono_class = (MonoClass*) mono_class_from_name ((MonoImage*) mono_assembly_get_image (_mono_assembly), \"GLib\", \"Object\");");
        Cindex.WriteLine("}");
        Cindex.WriteLine("if (_mono_method == NULL) {");
        Cindex.WriteLine("MonoMethodDesc *_mono_method_desc = mono_method_desc_new (\":get_Handle()\", FALSE);");
        Cindex.WriteLine("_mono_method = mono_method_desc_search_in_class (_mono_method_desc, _mono_class);");
        Cindex.WriteLine("}");
        Cindex.WriteLine();
        Cindex.WriteLine("retval = (gpointer *) mono_object_unbox (mono_runtime_invoke (_mono_method, _mono_object, NULL, NULL));");
        Cindex.WriteLine("return (gpointer ) *retval;");
        Cindex.WriteLine("}");
        Cindex.WriteLine();


        Console.Write("Generating sources in " + ns);
        foreach (Type t in types)
        {
            TypeGen(t);
            Console.Write(".");
        }

        Console.WriteLine();

        Hindex.WriteLine();
        Hindex.WriteLine("#endif /* " + Hindex_id + " */");

        Hdecls.WriteLine();
        Hdecls.WriteLine("#endif /* " + Hdecls_id + " */");

        Cindex.Close();
        Hindex.Close();
        Hdecls.Close();
    }
Example #50
0
        public override void WriteTo(CodeWriter writer)
        {
            if (Mask)
            {
                writer.AddCommentLine(CommentOnStart);
                using (writer.NewBlock())
                {
                    Block.WriteTo(writer);
                }
                writer.AddCommentLine(CommentOnEnd);
                return;
            }
            var hasVar      = Var != null;
            var varPrefix   = C.AllocTempVar();
            var varForCount = $"{varPrefix}_count";
            var varForIndex = $"{varPrefix}_index";
            var typeName    = $"decltype({varForCount})";

            writer.AddCommentLine(CommentOnStart);

            writer.NewLine();
            if (hasVar)
            {
                typeName = Var.GetResultType().ToString();
                writer.Write(typeName);
                writer.Write(" ");
            }
            else
            {
                writer.Write("auto ");
            }
            writer.Write(varForCount);
            writer.Write(" = ");
            Count.WriteTo(writer);
            writer.Write(";");

            writer.NewLine();
            writer.Write(typeName);
            writer.Write(" ");
            writer.Write(varForIndex);
            writer.Write(" = 1");
            writer.Write(";");

            writer.NewLine();
            writer.Write("for (");

            if (hasVar)
            {
                C.WriteLetExpression(writer, Var, () =>
                {
                    writer.Write(varForIndex);
                });
            }

            writer.Write("; ");

            writer.Write(varForIndex);
            writer.Write(" <= ");
            writer.Write(varForCount);

            writer.Write("; ");

            if (hasVar)
            {
                C.WriteLetExpression(writer, Var, () =>
                {
                    writer.Write("++");
                    writer.Write(varForIndex);
                });
            }
            else
            {
                writer.Write(varForIndex);
                writer.Write("++");
            }

            writer.Write(")");
            using (writer.NewBlock())
            {
                Block.WriteTo(writer);
            }

            writer.AddCommentLine(CommentOnEnd);
        }
Example #51
0
        protected override void ToODialect(CodeWriter writer)
        {
            bool hasBody = true;             // always one

            ToODialect(writer, hasBody);
        }
        public static string Generate(UnityComponentDetails componentDetails, string qualifiedNamespace)
        {
            var componentNamespace = $"global::{qualifiedNamespace}.{componentDetails.ComponentName}";

            Logger.Trace($"Generating {qualifiedNamespace}.{componentDetails.ComponentName}.ComponentReplicator internal class.");

            return(CodeWriter.Populate(cgw =>
            {
                cgw.UsingDirectives(
                    "System",
                    "System.Collections.Generic",
                    "UnityEngine",
                    "UnityEngine.Profiling",
                    "Unity.Mathematics",
                    "Unity.Entities",
                    "Unity.Collections",
                    "Improbable.Gdk.Core",
                    "Improbable.Gdk.Core.CodegenAdapters"
                    );

                cgw.Namespace(qualifiedNamespace, ns =>
                {
                    ns.Type($"public partial class {componentDetails.ComponentName}", partial =>
                    {
                        partial.Type("internal class ComponentReplicator : IComponentReplicationHandler", replicator =>
                        {
                            replicator.Line($@"
public uint ComponentId => {componentDetails.ComponentId};

public EntityQueryDesc ComponentUpdateQuery => new EntityQueryDesc
{{
    All = new[]
    {{
        ComponentType.ReadWrite<{componentNamespace}.Component>(),
        ComponentType.ReadWrite<{componentNamespace}.ComponentAuthority>(),
        ComponentType.ReadOnly<SpatialEntityId>()
    }},
}};
");
                            replicator.Method(@"
public void SendUpdates(
    NativeArray<ArchetypeChunk> chunkArray,
    ComponentSystemBase system,
    EntityManager entityManager,
    ComponentUpdateSystem componentUpdateSystem)
", m =>
                            {
                                m.ProfilerStart(componentDetails.ComponentName);

                                m.Line(new[]
                                {
                                    "var spatialOSEntityType = system.GetArchetypeChunkComponentType<SpatialEntityId>(true);",
                                    $"var componentType = system.GetArchetypeChunkComponentType<{componentNamespace}.Component>();",
                                    "var authorityType = system.GetArchetypeChunkSharedComponentType<ComponentAuthority>();"
                                });

                                m.Loop("foreach (var chunk in chunkArray)", outerLoop =>
                                {
                                    outerLoop.Line(new[]
                                    {
                                        "var entityIdArray = chunk.GetNativeArray(spatialOSEntityType);",
                                        "var componentArray = chunk.GetNativeArray(componentType);",
                                        "var authorityIndex = chunk.GetSharedComponentIndex(authorityType);",
                                    });

                                    outerLoop.If("!entityManager.GetSharedComponentData<ComponentAuthority>(authorityIndex).HasAuthority", () => new[]
                                    {
                                        "continue;"
                                    });

                                    outerLoop.Loop("for (var i = 0; i < componentArray.Length; i++)", innerLoop =>
                                    {
                                        innerLoop.Line("var data = componentArray[i];");

                                        innerLoop.If("data.IsDataDirty()", componentDirtyThen =>
                                        {
                                            componentDirtyThen.Line("Update update = new Update();");
                                            for (var i = 0; i < componentDetails.FieldDetails.Count; i++)
                                            {
                                                var fieldDetails = componentDetails.FieldDetails[i];
                                                componentDirtyThen.If($"data.IsDataDirty({i})", () => new[]
                                                {
                                                    $"update.{fieldDetails.PascalCaseName} = data.{fieldDetails.PascalCaseName};"
                                                });
                                            }

                                            componentDirtyThen.Line(new[]
                                            {
                                                "componentUpdateSystem.SendUpdate(in update, entityIdArray[i].EntityId);",
                                                "data.MarkDataClean();",
                                                "componentArray[i] = data;"
                                            });
                                        });
                                    });
                                });

                                m.ProfilerEnd();
                            });
                        });
                    });
                });
            }).Format());
        }
Example #53
0
 protected override void ToEDialect(CodeWriter writer)
 {
     protoToEDialect(writer, false, true);
     bindingsToEDialect(writer);
     methodsToEDialect(writer);
 }
 protected abstract string WriteProcedureBodyMethodCall(CodeWriter writer, DbLinq.Schema.Dbml.Function procedure, GenerationContext context);
        private void GenerateManageMethodSuperHead(CodeWriter cw, Method method)
        {
            var param = string.Join(", ", method.InputTypes.Select(v => v.GetTypeCppOgiginal()));

            cw.WriteLine($"{method.ReturnType.GetTypeCppOgiginal()} _Supper__{method.Name}({param});");
        }
        protected override void GenerateCs(Class Class)
        {
            var cw = new CodeWriter();

            GenerateFileHeader(cw);
            GenerateReSharperDisablesCsharp(cw);

            cw.WriteLine("using System;");
            cw.WriteLine("using System.Runtime.InteropServices;");
            cw.WriteLine();

            GenerateSourceInfo(cw, Class);

            cw.WriteLine("namespace UnrealEngine");
            cw.OpenBlock();

            var manageClassName = "Manage" + Class.BaseName;

            cw.WriteLine($"[ManageType(\"{manageClassName}\")]");
            cw.WriteLine($"public partial class {manageClassName} : {Class.Name}, IManageWrapper");
            cw.OpenBlock();

            cw.WriteLine($"public {manageClassName}(IntPtr adress)");
            cw.WriteLine("\t: base(adress)");
            cw.OpenBlock();
            cw.CloseBlock();
            cw.WriteLine();

            var cwDllImport     = new CodeWriter(cw);
            var cwExternMethods = new CodeWriter(cw);

            foreach (var method in _virtualMethods)
            {
                GenerateMethodDllImport(cwDllImport, Class, method);
                GenerateManageMethodCs(cwExternMethods, Class, method);
            }

            if (!cwDllImport.IsEmpty())
            {
                cw.WriteLine("#region DLLInmport");
                cw.Write(cwDllImport);
                cw.WriteLine("#endregion");
                cw.WriteLine();
            }

            if (!cwExternMethods.IsEmpty())
            {
                cw.WriteLine("#region Methods");
                cw.Write(cwExternMethods);
                cw.WriteLine("#endregion");
                cw.WriteLine();
            }

            cw.WriteLine($"public static implicit operator IntPtr({manageClassName} self)");
            cw.OpenBlock();
            cw.WriteLine("return self?.NativePointer ?? IntPtr.Zero;");
            cw.CloseBlock();
            cw.WriteLine();
            cw.WriteLine($"public static implicit operator {manageClassName}(ObjectPointerDescription PtrDesc)");
            cw.OpenBlock();
            cw.WriteLine($"return NativeManager.GetWrapper<{manageClassName}>(PtrDesc);");
            cw.CloseBlock();

            cw.CloseBlock();
            cw.CloseBlock();

            cw.SaveToFile(Path.Combine(PathOutputCs, manageClassName + ".cs"));
        }
Example #57
0
 public static void WriteCodeGenAttribute(CodeWriter code, string generatorName)
 {
     code.WriteLine($"[System.CodeDom.Compiler.GeneratedCode(\"{generatorName}\", \"\")]");
 }
Example #58
0
 protected override void AsTextName(CodeWriter writer, RenderFlags flags)
 {
     _expression.AsText(writer, flags);
     UpdateLineCol(writer, flags);
 }
Example #59
0
        protected override void Generate(
            CodeWriter writer,
            EntityIdFactoryDescriptor descriptor,
            out string fileName,
            out string?path)
        {
            fileName = descriptor.Name;
            path     = State;

            ClassBuilder classBuilder = ClassBuilder
                                        .New()
                                        .SetAccessModifier(AccessModifier.Public)
                                        .AddImplements(TypeNames.IEntityIdSerializer)
                                        .SetName(fileName);

            classBuilder
            .AddField(_options)
            .SetStatic()
            .SetReadOnly()
            .SetType(TypeNames.JsonWriterOptions)
            .SetValue(CodeBlockBuilder
                      .New()
                      .AddCode(MethodCallBuilder
                               .Inline()
                               .SetNew()
                               .SetMethodName(TypeNames.JsonWriterOptions))
                      .AddCode(CodeInlineBuilder.From("{ Indented = false }")));

            classBuilder
            .AddMethod("Parse")
            .SetAccessModifier(AccessModifier.Public)
            .SetReturnType(TypeNames.EntityId)
            .AddParameter(_obj, x => x.SetType(TypeNames.JsonElement))
            .AddCode(ParseEntityIdBody(descriptor));

            classBuilder
            .AddMethod("Format")
            .SetAccessModifier(AccessModifier.Public)
            .SetReturnType(TypeNames.String)
            .AddParameter(_entityId, x => x.SetType(TypeNames.EntityId))
            .AddCode(FormatEntityIdBody(descriptor));

            foreach (var entity in descriptor.Entities)
            {
                classBuilder
                .AddMethod($"Parse{entity.Name}EntityId")
                .SetAccessModifier(AccessModifier.Private)
                .SetReturnType(TypeNames.EntityId)
                .AddParameter(_obj, x => x.SetType(TypeNames.JsonElement))
                .AddParameter(_type, x => x.SetType(TypeNames.String))
                .AddCode(ParseSpecificEntityIdBody(entity));

                classBuilder
                .AddMethod($"Format{entity.Name}EntityId")
                .SetAccessModifier(AccessModifier.Private)
                .SetReturnType(TypeNames.String)
                .AddParameter(_entityId, x => x.SetType(TypeNames.EntityId))
                .AddCode(FormatSpecificEntityIdBody(entity));
            }

            CodeFileBuilder
            .New()
            .SetNamespace(descriptor.Namespace)
            .AddType(classBuilder)
            .Build(writer);
        }
Example #60
0
 public static void WriteObsoletePragma(CodeWriter code)
 {
     code.WriteLine("#pragma warning disable 612 // member is obsolete");
 }