示例#1
0
        private void AddGenOutputFile()
        {
            var writer = new CSharpWriter();

            writer.WriteLine();
            writer.WriteLine("namespace JitsuGen.Output");
            using (writer.Curly())
            {
                writer.WriteLine("public static class GenOutput");
                using (writer.Curly())
                {
                    writer.WriteLine($"public static void FillDomain({writer.UseType(typeof(IGenDomain))} genDomain)");
                    using (writer.Curly())
                    {
                        foreach (var impl in implementations)
                        {
                            writer.WriteLine($"genDomain.RegisterGeneratedType(typeof({writer.UseType(impl.Key)}), typeof({impl.Value}));");
                        }
                    }
                }
            }
            writer.Builder.Insert(0, writer.GetUsingsString());
            AddFile(new GeneratedFileInfo
            {
                Path      = "GenOutput.cs",
                TypesUsed = writer.GetUsedTypes(),
                Content   = writer.Builder.ToString()
            });
        }
示例#2
0
 public override void GenRuleTestBody(CSharpWriter csw, RuleCompiler cmp, string member)
 {
     csw.WriteLine("{0} res = {1}();", GetResultType(), ParseFuncName);
     csw.WriteLine("if (res == null) return false;");
     csw.WriteLine("args.{0} = res;", member);
     csw.WriteLine("return true;");
 }
示例#3
0
        public void GenNodeClass(CSharpWriter csw)
        {
            if (Rule.ClassName != null)
            {
                csw.Begin("public partial class {0}", Rule.ClassName);
            }
            else
            {
                csw.Begin("public class {0} : SqlNode", Rule.GetResultType());
            }
            GenVarMembers(csw);
            Rule.Chain.WriteSqlNodeMembers(csw, this);
            csw.Begin("public override void GenerateSql(ISqlDumper dmp)");
            Rule.Chain.WriteGenSqlBody(csw, this);
            csw.End(); // GenerateSql
            csw.Begin("public override void EnumSymbols(ISymbolEnumerator en)");
            foreach (var vd in Vars)
            {
                switch (vd.TypeGroup)
                {
                case VariableTypeGroup.SubNode:
                    csw.WriteLine("{0}.EnumSymbols(en);", vd.Name);
                    break;

                case VariableTypeGroup.SymbolPos:
                    csw.WriteLine("en.EnumSymbol({0}, this);", vd.Name);
                    break;
                }
            }
            csw.End(); // EnumSymbols
            csw.End(); // class
        }
示例#4
0
 public override void GenRuleTestBody(CSharpWriter csw, RuleCompiler cmp, string member)
 {
     csw.WriteLine("{0} node = {1}({2});", TypeName, FuncName, CallArgs.CreateDelimitedText(", "));
     csw.WriteLine("if (node == null) return false;");
     csw.WriteLine("args.{0} = node;", member);
     csw.WriteLine("return true;");
 }
示例#5
0
 public override void WriteParserMembers(CSharpWriter csw, RuleCompiler cmp)
 {
     WriteParseMethodHeader(csw, cmp);
     csw.Begin("if (IsTerminal(\"{0}\"))", Symbol);
     csw.WriteLine("args.{0} = CurrentOriginal;", TerminalPosName);
     csw.WriteLine("NextToken();");
     csw.WriteLine("return true;");
     csw.End();
     csw.WriteLine("return false;");
     csw.End(); // method
 }
示例#6
0
 private void GenVarMembers(CSharpWriter csw)
 {
     foreach (var vd in Vars)
     {
         csw.WriteLine("public {0} {1};", vd.Type, vd.Name);
     }
 }
示例#7
0
        public void WriteTo(CSharpContext context, CSharpPackage package, CSharpWriter writer)
        {
            using (var bodyWriter = new CSharpWriter())
            {
                // render body first, so usings are resolved
                using (bodyWriter.WriteIndentedBlock(prefix: $"namespace {CSharpHelpers.CombineNamespaces(package.Namespace, this.RelativeNamespace)} "))
                {
                    foreach (var fragment in Fragments)
                    {
                        fragment.WriteTo(context, package, this, bodyWriter);
                    }
                }

                bodyWriter.Flush();

                // render usings
                if (Usings.Count > 0)
                {
                    foreach (var @using in Usings)
                    {
                        writer.WriteIndented($"using {@using};");
                    }

                    writer.WriteLine();
                }

                // render body
                bodyWriter.WriteTo(writer);
            }
        }
示例#8
0
        public void Generate(CSharpWriter stream, Nodes.UmlEnumerationNode enumNode)
        {
            stream.WriteSummary(enumNode.Documentation);
            if (enumNode.Tags.Any(r => r.Name == "Flags"))
            {
                stream.WriteCodeLine("[Flags]");
            }
            stream.WriteCodeLine($"{CSharpHelper.ConvertVisibility(enumNode.Visibility)} enum {enumNode.Name}");
            using (var enumScope = stream.CreateIndentScope())
            {
                var litCount = enumNode.Literals.Count;
                for (var i = 0; i < litCount; i++)
                {
                    var lit          = enumNode.Literals[i];
                    var litDelimiter = litCount > i + 1 ? "," : string.Empty;

                    stream.WriteSummary(lit.Documentation);
                    var valueTag = lit.Tags.FirstOrDefault(r => r.Name == "Value");
                    if (valueTag != null)
                    {
                        stream.WriteCodeLine($"{lit.Name} = {valueTag.Value}{litDelimiter}");
                        stream.WriteLine(); // This is only for beauty output
                    }
                    else
                    {
                        stream.WriteCodeLine($"{lit.Name}{litDelimiter}");
                    }
                }
            }
        }
示例#9
0
 internal void WriteParserMembers(CSharpWriter csw, RuleCompiler cmp)
 {
     foreach (RuleItem item in Items)
     {
         item.WriteParserMembers(csw, cmp);
     }
     csw.Begin("public bool {0}({1} args)", ParseFuncName, cmp.Rule.ArgsClassName);
     csw.WriteLine("var beginMark = MarkPosition();");
     foreach (RuleItem item in Items)
     {
         csw.Begin("if (!{0}(args))", item.ParseFuncName);
         csw.WriteLine("GoToMark(beginMark);");
         csw.WriteLine("return false;");
         csw.End();
     }
     csw.WriteLine("return true;");
     csw.End();
 }
示例#10
0
 public override void WriteSqlNodeMembers(CSharpWriter csw, RuleCompiler cmp)
 {
     base.WriteSqlNodeMembers(csw, cmp);
     foreach (var chain in Chains)
     {
         chain.WriteSqlNodeMembers(csw, cmp);
     }
     csw.WriteLine("public enum {0} {{ {1} }}", EnumTypeName, EnumElems.CreateDelimitedText(", "));
 }
示例#11
0
 public override void WriteGenSqlBody(CSharpWriter csw, RuleCompiler cmp)
 {
     if (!Mandatory)
     {
         csw.Begin("if ({0})", IsVariable);
     }
     csw.Begin("switch ({0})", EnumVarName);
     for (int i = 0; i < Chains.Count; i++)
     {
         csw.WriteLine("case {0}.{1}:", EnumTypeName, EnumElems[i]);
         csw.Inc();
         Chains[i].WriteGenSqlBody(csw, cmp);
         csw.WriteLine("break;");
         csw.Dec();
     }
     csw.End(); // switch
     if (!Mandatory)
     {
         csw.End();             // if ($IsVariable)
     }
 }
示例#12
0
        public override void WriteParserMembers(CSharpWriter csw, RuleCompiler cmp)
        {
            foreach (var chain in Chains)
            {
                chain.WriteParserMembers(csw, cmp);
            }
            WriteParseMethodHeader(csw, cmp);
            int chindex = 0;

            foreach (var chain in Chains)
            {
                csw.Begin("if ({0}(args))", chain.ParseFuncName);
                csw.WriteLine("args.{0} = {1}.{2}.{3};", EnumVarName, cmp.Rule.GetResultType(), EnumTypeName, EnumElems[chindex]);
                if (!Mandatory)
                {
                    csw.WriteLine("args.{0} = true;", IsVariable);
                }
                csw.WriteLine("return true;");
                csw.End();
                chindex++;
            }
            if (Mandatory)
            {
                csw.WriteLine("return false;");
            }
            else
            {
                csw.WriteLine("args.{0} = false;", IsVariable);
                csw.WriteLine("return true;");
            }
            csw.End(); // method
        }
示例#13
0
        public void Generate(CSharpWriter stream, Nodes.UmlInterfaceNode interfaceNode)
        {
            stream.WriteSummary(interfaceNode.Documentation);
            var baseNames       = interfaceNode.GetGeneralBaseNodes().Select(r => r.Name).ToArray();
            var baseDeclaration = baseNames.Length == 0 ? string.Empty : $" : {string.Join(", ", baseNames)}";

            stream.WriteCodeLine($"{CSharpHelper.ConvertVisibility(interfaceNode.Visibility)} interface {interfaceNode.Name}{baseDeclaration}");
            using (var interScope = stream.CreateIndentScope())
            {
                if (interfaceNode.Attributes != null)
                {
                    for (var attrIndex = 0; attrIndex < interfaceNode.Attributes.Count; attrIndex++)
                    {
                        if (attrIndex > 0)
                        {
                            stream.WriteLine();
                        }
                        WriteAttributeAsProperty(stream, interfaceNode.Attributes[attrIndex]);
                    }
                }
            }
        }
示例#14
0
 public void GenParserMethods(CSharpWriter csw)
 {
     Rule.Chain.WriteParserMembers(csw, this);
     csw.Method(Rule.GetResultType(), Rule.ParseFuncName);
     csw.WriteLine("var args = new {0}();", Rule.ArgsClassName);
     csw.WriteLine("bool ok = {0}(args);", Rule.Chain.ParseFuncName);
     csw.Begin("if (ok)");
     csw.WriteLine("var res = new {0}();", Rule.GetResultType());
     foreach (var vd in Vars)
     {
         csw.WriteLine("res.{0} = args.{0};", vd.Name);
         if (vd.TypeGroup == VariableTypeGroup.SubNode)
         {
             csw.WriteLine("if (res.{0} != null) res.{0}.Parent = res;", vd.Name);
         }
     }
     csw.WriteLine("return res;");
     csw.End(); // if (ok)
     csw.WriteLine("return null;");
     csw.End(); // method
 }
示例#15
0
        static void Main(string[] args)
        {
            //var secs = (new DateTime(2009, 1, 1) - new DateTime(1970, 1, 1)).TotalSeconds;
            string inf  = args[0];
            string outf = args[1];
            string ns   = args[2];
            string cls  = args[3];

            using (StreamReader sr = new StreamReader(inf))
            {
                string         data   = sr.ReadToEnd();
                GramParser     parser = new GramParser(new GramTokenizer(new StringReader(data), new StringSliceProvider(data)));
                RuleCollection rules  = parser.ParseFile();
                ParserCompiler pc     = new ParserCompiler(rules);
                rules.Compile(pc);
                using (StreamWriter sw = new StreamWriter(outf))
                {
                    CSharpWriter csw = new CSharpWriter(sw);
                    csw.WriteLine("using DatAdmin;");
                    rules.GenCode(csw, ns, cls);
                }
            }
        }
        public void GenerateFor(IFileGeneratingContext context, Type type)
        {
            if (!type.IsInterface)
            {
                throw new ArgumentException("VerboseWrapperGenerator only works with interfaces.");
            }
            var className = "_verbose_" + type.Name;


            var writer = new CSharpWriter();

            writer.WriteLine();
            writer.WriteLine($"namespace {type.Namespace}");
            using (writer.Curly())
            {
                var interfaceName = writer.UseType(type);
                writer.WriteLine($"public class {className} : {interfaceName}");
                using (writer.Curly())
                {
                    writer.WriteLine($"private {interfaceName} real;");
                    writer.WriteLine();
                    writer.WriteLine($"public {className}({interfaceName} real)");
                    using (writer.Curly())
                        writer.WriteLine("this.real = real;");
                    writer.WriteLine();

                    foreach (var propertyInfo in type.GetProperties())
                    {
                        var writeGetter = propertyInfo.GetMethod != null
                            ? (Action <CSharpWriter>)(w =>
                        {
                            w.WriteLine($"{writer.UseType(typeof(Console))}.WriteLine($\"Getting {interfaceName}.{propertyInfo.Name}\");");
                            w.WriteLine($"return real.{propertyInfo.Name}; ");
                        })
                            : null;
                        var writeSetter = propertyInfo.SetMethod != null
                            ? (Action <CSharpWriter>)(w =>
                        {
                            w.WriteLine($"{writer.UseType(typeof(Console))}.WriteLine($\"Setting {interfaceName}.{propertyInfo.Name}\");");
                            w.WriteLine($"real.{propertyInfo.Name} = value;");
                        })
                            : null;
                        writer.WriteProperty("public", writer.UseType(propertyInfo.PropertyType), propertyInfo.Name, writeGetter, writeSetter);
                        writer.WriteLine();
                    }

                    foreach (var methodInfo in type.GetMethods())
                    {
                        if (methodInfo.IsSpecialName)
                        {
                            continue;
                        }

                        writer.WriteMethodDeclaration("public", methodInfo);
                        using (writer.Curly())
                        {
                            writer.WriteLine($"{writer.UseType(typeof(Console))}.WriteLine($\"Invoking {interfaceName}.{methodInfo.Name}()\");");
                            var paramString      = string.Join(", ", methodInfo.GetParameters().Select(x => x.Name));
                            var invocationString = $"real.{methodInfo.Name}({paramString});";
                            if (methodInfo.ReturnType == typeof(void))
                            {
                                writer.WriteLine(invocationString);
                            }
                            else
                            {
                                writer.WriteLine($"return {invocationString}");
                            }
                        }
                        writer.WriteLine();
                    }
                }
            }
            writer.Builder.Insert(0, writer.GetUsingsString());
            var path    = Path.Combine(type.Namespace.Replace(".", "\\"), className + ".cs");
            var content = writer.Builder.ToString();

            context.AddFile(new GeneratedFileInfo
            {
                Path      = path,
                Content   = content,
                TypesUsed = writer.GetUsedTypes(),
                Template  = type,
                ImplementationFullName = $"{type.Namespace}.{className}"
            });
        }
示例#17
0
 public override void WriteGenSqlBody(CSharpWriter csw, RuleCompiler cmp)
 {
     csw.WriteLine("dmp.Put(\"{0}\");", Format);
 }
示例#18
0
 public override void WriteGenSqlBody(CSharpWriter csw, RuleCompiler cmp)
 {
     csw.WriteLine("dmp.Put(\"&s%:k\", {0}, \"{1}\");", TerminalPosName, Symbol);
 }
示例#19
0
        public void Generate(CSharpWriter stream, Nodes.UmlClassNode classNode, bool asPartial = true)
        {
            stream.WriteSummary(classNode.Documentation);
            var baseClass      = classNode.BaseClass;
            var implInterfaces = classNode.GetInterfaceRealizationNodes().ToList();

            var baseNames = new List <string>();

            if (baseClass != null)
            {
                baseNames.Add(baseClass.Name);
            }
            baseNames.AddRange(implInterfaces.Select(r => r.Name));

            var baseDeclaration = baseNames.Count == 0 ? string.Empty : $" : {string.Join(", ", baseNames)}";

            var partialDefinition = asPartial ? " partial" : string.Empty;

            stream.WriteCodeLine($"{CSharpHelper.ConvertVisibility(classNode.Visibility)}{partialDefinition} class {classNode.Name}{baseDeclaration}");
            using (var interScope = stream.CreateIndentScope())
            {
                var autoInitializeConstructorNodes = new List <INode>();

                if (classNode.Attributes != null)
                {
                    for (var attrIndex = 0; attrIndex < classNode.Attributes.Count; attrIndex++)
                    {
                        if (attrIndex > 0)
                        {
                            stream.WriteLine();
                        }
                        var attr = classNode.Attributes[attrIndex];
                        WriteAttributeAsProperty(stream, attr);
                        if (attr.IsReadOnly)
                        {
                            autoInitializeConstructorNodes.Add(attr);
                        }
                    }

                    foreach (var assocEndNode in classNode.GetAssociationEnds(false, true))
                    {
                        stream.WriteLine();
                        WriteAssociationEndProperty(stream, assocEndNode);
                        if (assocEndNode.IsReadOnly)
                        {
                            autoInitializeConstructorNodes.Add(assocEndNode);
                        }
                    }
                }
                if (autoInitializeConstructorNodes.Any())
                {
                    stream.WriteLine();
                    stream.WriteCodeLine($"public {classNode.Name}()");
                    using (var ctorScope = stream.CreateIndentScope())
                    {
                        foreach (var autoNode in autoInitializeConstructorNodes)
                        {
                            stream.WriteCodeLine($"{autoNode.Name} = default;");
                        }
                    }
                }
            }
        }
示例#20
0
        protected override void DoRun(IJobRunEnv env)
        {
            using (StreamWriter sw = new StreamWriter(File))
            {
                CSharpWriter csw = new CSharpWriter(sw);
                csw.WriteLine("// ***********************************************************************");
                csw.WriteLine("// This code was generated by DatAdmin DB MODEL Plugin, please do not edit");
                csw.WriteLine("// ***********************************************************************");
                csw.WriteLine("using System.Data.Common;");
                csw.Begin("namespace {0}", NamespaceName);
                csw.Begin("public static class {0}", ClassName);

                csw.WriteLine("public static string DBVERSION = {0};", CSharpWriter.StringLiteral(m_versionDb.Versions.Last().Name));

                csw.Begin("private static void ExecuteNonQuery(DbConnection conn, DbTransaction tran, string sql)");
                csw.Begin("using (DbCommand cmd = conn.CreateCommand())");
                csw.WriteLine("cmd.CommandText = sql;");
                csw.WriteLine("cmd.Transaction = tran;");
                csw.WriteLine("cmd.ExecuteNonQuery();");
                csw.End(); // using
                csw.End(); // function

                csw.Begin("public static string GetVersion(DbConnection conn, DbTransaction tran)");
                csw.Begin("try");
                csw.Begin("using (DbCommand cmd = conn.CreateCommand())");
                csw.WriteLine("cmd.Transaction = tran;");
                csw.WriteLine("cmd.CommandText = {0};", CSharpWriter.StringLiteral(m_versionDb.m_props.GetVersionSql));
                csw.WriteLine("return cmd.ExecuteScalar().ToString();");
                csw.End(); // using
                csw.End(); // try
                csw.Begin("catch");
                csw.WriteLine("return null;");
                csw.End(); // catch
                csw.End(); // function

                int vindex = 0;
                foreach (var vd in m_versionDb.Versions)
                {
                    csw.WriteLine("// update to version {0}", vd.Name);
                    csw.Begin("private static void UpdateToVersion_{0}(DbConnection conn, DbTransaction tran)", vindex);
                    foreach (string sql in vd.GetAlterSqls())
                    {
                        csw.WriteLine("ExecuteNonQuery(conn, tran, {0});", CSharpWriter.StringLiteral(sql));
                    }
                    csw.End();
                    vindex++;
                }

                csw.Begin("public static void UpdateDb(DbConnection conn)");
                if (UseTransaction)
                {
                    csw.Begin("using (DbTransaction tran = conn.BeginTransaction())");
                    csw.Begin("try");
                }
                else
                {
                    csw.WriteLine("DbTransaction tran = null;");
                }
                for (int i = 0; i < m_versionDb.Versions.Count; i++)
                {
                    if (i == 0)
                    {
                        csw.WriteLine("if (GetVersion(conn, tran) == null) UpdateToVersion_0(conn, tran);");
                    }
                    else
                    {
                        csw.WriteLine("if (GetVersion(conn, tran) == {0}) UpdateToVersion_{1}(conn, tran);", CSharpWriter.StringLiteral(m_versionDb.Versions[i - 1].Name), i);
                    }
                }
                if (UseTransaction)
                {
                    csw.End(); // try
                    csw.Begin("catch");
                    csw.WriteLine("tran.Rollback();");
                    csw.WriteLine("throw;");
                    csw.End(); // catch
                    csw.WriteLine("tran.Commit();");
                    csw.End(); // using
                }
                csw.End();     // function Run

                csw.Begin("public static void CheckVersion(DbConnection conn)");
                csw.WriteLine("string realversion = GetVersion(conn, null);");
                csw.Begin("if (realversion != DBVERSION)");
                csw.WriteLine("throw new Exception(String.Format(\"Bad version of database, code_version={0}, db_version={1}\", DBVERSION, realversion));");
                csw.End(); // if
                csw.End(); //  CheckVersion

                csw.End(); // class
                csw.End(); // namespace
            }
        }
示例#21
0
 public override void WriteParserMembers(CSharpWriter csw, RuleCompiler cmp)
 {
     WriteParseMethodHeader(csw, cmp);
     csw.WriteLine("return true;");
     csw.End(); // method
 }
示例#22
0
 public override void WriteGenSqlBody(CSharpWriter csw, RuleCompiler cmp)
 {
     csw.WriteLine("{0}.GenerateSql(dmp);", MemberNodeName);
 }
示例#23
0
        public void GenerateFor(IFileGeneratingContext context, Type type)
        {
            var writer      = new CSharpWriter();
            var amClass     = type;
            var amClassName = writer.UseType(type);
            var desc        = new AmObjectTypeDescription(amClass, bindingTypeDescriptors);

            var className = "_am_" + desc.Name;

            writer.WriteLine();
            writer.WriteLine($"namespace JitsuGen.Output.{type.Namespace}");
            using (writer.Curly())
            {
                writer.WriteLine($"public class {className} : {amClassName}");
                using (writer.Curly())
                {
                    foreach (var bindingDesc in desc.Bindings)
                    {
                        writer.WriteLine($"private {writer.UseType(bindingDesc.MakeBindingType(amClass))} _{bindingDesc.Property.Name};");
                    }
                    writer.WriteLine();

                    foreach (var bindingDesc in desc.Bindings)
                    {
                        var getterString = bindingDesc.BuildGetterString($"_{bindingDesc.Property.Name}");
                        var setterString = bindingDesc.BuildSetterString($"_{bindingDesc.Property.Name}");
                        writer.WriteProperty("public override", writer.UseType(bindingDesc.Property.PropertyType), bindingDesc.Property.Name,
                                             getterString != null ? (Action <CSharpWriter>)(w => w.WriteLine(getterString)) : null,
                                             setterString != null ? (Action <CSharpWriter>)(w => w.WriteLine(setterString)) : null);
                        writer.WriteLine();
                    }

                    var baseCtor          = amClass.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance).Single();
                    var ctorParametersStr = string.Join(", ", baseCtor.GetParameters().Select(x => $"{writer.UseType(x.ParameterType)} {x.Name}"));
                    var ctorArgsStr       = string.Join(", ", baseCtor.GetParameters().Select(x => x.Name));
                    writer.WriteLine($"public {className}({ctorParametersStr})");
                    writer.WriteLine($": base({ctorArgsStr})");
                    using (writer.Curly())
                    { }
                    writer.WriteLine();

                    writer.WriteLine($"protected override {writer.UseType(typeof(List<IAmBinding>))} AmInitBindings()");
                    using (writer.Curly())
                    {
                        writer.WriteLine($"var list = new {writer.UseType(typeof(List<IAmBinding>))}();");
                        foreach (var bindingDesc in desc.Bindings)
                        {
                            var flagTypeStr = writer.UseType(typeof(AmBindingFlags));
                            var flagsStr    = string.Join(" | ", EnumerateFlags(bindingDesc.Flags).Select(x => $"{flagTypeStr}.{x}"));
                            writer.WriteLine($"_{bindingDesc.Property.Name} = new {writer.UseType(bindingDesc.MakeBindingType(amClass))}(this, \"{bindingDesc.Property.Name}\", {flagsStr});");
                            writer.WriteLine($"list.Add(_{bindingDesc.Property.Name});");
                        }
                        writer.WriteLine("return list;");
                    }
                }
            }
            writer.Builder.Insert(0, writer.GetUsingsString());
            var path    = Path.Combine(type.Namespace.Replace(".", "\\"), className + ".cs");
            var content = writer.Builder.ToString();

            context.AddFile(new GeneratedFileInfo
            {
                Path      = path,
                Content   = content,
                TypesUsed = writer.GetUsedTypes(),
                Template  = type,
                ImplementationFullName = $"{type.Namespace}.{className}"
            });
        }