Exemple #1
0
        private void AddGetCodeItemsMethod()
        {
            if (!apps.Any())
            {
                return;
            }
            var target = MyStruct;
            var optionsToStringCode = new CsCodeWriter();

            for (var index = 0; index < apps.Count; index++)
            {
                if (index > 0)
                {
                    optionsToStringCode.WriteLine();
                }
                var action = apps[index];
                action(optionsToStringCode, target);
            }

            var m = target
                    .AddMethod("GetCodeItems", MyNamespace.GetTypeName <IEnumerable <string> >())
                    .WithBody(optionsToStringCode);

            m.AddParam <OptionPreference>(preferLongNameVariable, ExtensionsClass).ConstValue =
                ExtensionsClass.GetEnumValueCode(OptionPreference.Short);
        }
Exemple #2
0
        public static void Throw <T>(this CsCodeWriter cs, params string[] arguments)
        {
            var exception = new CsArguments(arguments).Create <T>();
            var code      = $"throw {exception};";

            cs.WriteLine(code);
        }
        public void MakeExtensionMethod(CsClass target)
        {
            if (EnumOptions is null)
            {
                return;
            }

            var paramValue = target.GetTypeName(TypeName);

            var writer = CsCodeWriter.Create <ShellEnumOptionsGenerator>();

            writer.Open("switch (value)");
            foreach (var i in EnumOptions.Items)
            {
                var line = $"case {paramValue}.{i.CsValue}: return {i.LinuxValue.CsEncode()};";
                writer.WriteLine(line);
            }

            var notSupportedException = target.GetTypeName <NotSupportedException>();

            writer.WriteLine($"default: throw new {notSupportedException}();");
            writer.Close();

            var parameter = new CsMethodParameter("value", paramValue)
            {
                UseThis = target.IsStatic
            };

            target.AddMethod(extensionMethodName, "string")
            .WithBody(writer)
            .WithStatic()
            .WithParameter(parameter);
        }
        private void Add_Register()
        {
            if (Cfg.PrefixRelations.Count == 0)
            {
                return;
            }
            var cw = new CsCodeWriter();

            foreach (var i in Cfg.PrefixRelations)
            {
                foreach (var u in Cfg.Units)
                {
                    var o  = u.FieldName.Substring(i.My.Length);
                    var p1 = u.FieldName;
                    var p2 = i.OtherUnitContainer + "s." + i.Other + o;
                    var q  = $"dict.AddRelated<{i.MyUnitContainer}, {i.OtherUnitContainer}>({p1}, {p2});";
                    cw.WriteLine(q);
                    q = $"dict.AddRelated<{i.OtherUnitContainer}, {i.MyUnitContainer}>({p2}, {p1});";
                    cw.WriteLine(q);
                }
            }

            Target.AddMethod("Register", "void")
            .WithBody(cw)
            .WithStatic()
            .WithVisibility(Visibilities.Internal)
            .AddParam <UnitRelationsDictionary>("dict", Target);
        }
Exemple #5
0
        public CsCodeWriter ReturnArray()
        {
            var c = new CsCodeWriter();

            CreateArray(c, "return ");
            return(c);
        }
Exemple #6
0
        private void MyStruct_AddWithMethod(CsEnumItem enumItem, bool isFirst)
        {
            if (isFirst)
            {
                var          cw            = new CsCodeWriter();
                const string maskVariable  = "value";
                const string modifiedValue = "current";
                cw.SingleLineIf("add", $"return {modifiedValue} | {maskVariable};",
                                $"return {modifiedValue} & ~{maskVariable};");
                var m = ExtensionsClass
                        .AddMethod(SetOrClearMethod, MyEnumTypeName)
                        .WithBody(cw)
                        .WithStatic();
                m.AddAggressiveInlining(ExtensionsClass);
                m.AddParam(modifiedValue, MyEnumTypeName).UseThis = true;
                m.AddParam(maskVariable, MyEnumTypeName);
                m.AddParam("add", "bool");
            }

            {
                var mask = GetMask(MyEnum, enumItem.EnumName);
                var cw   = CsCodeWriter.Create <SingleTaskEnumsGenerator>();
                cw.WriteLine($"{flagsPropertyName} = {flagsPropertyName}.{SetOrClearMethod}({mask}, value);");
                cw.WriteLine("return this;");
                var m = MyStruct.AddMethod("With" + enumItem.EnumName, OptionsClassName)
                        .WithBody(cw);
                m.AddParam("value", "bool").ConstValue = "true";
                m.Description = enumItem.Description;
            }
        }
Exemple #7
0
 public static CsCodeWriter SingleLineForeach(this CsCodeWriter cs, string variable, string collection, string statement)
 {
     cs.WriteLine($"foreach (var {variable} in {collection})");
     cs.IncIndent();
     cs.WriteLine(statement);
     cs.DecIndent();
     return(cs);
 }
Exemple #8
0
        public static void WriteDescriptionComment(this CsCodeWriter writer, OptionsCollectionValue option)
        {
            var description = option.FullDescription;

            if (string.IsNullOrEmpty(description))
            {
                return;
            }
            writer.WriteLine("// " + description);
        }
Exemple #9
0
        protected void Add_GetHashCode(string expression)
        {
            CodeWriter cw = new CsCodeWriter();

            cw.Open("unchecked");
            cw.WriteLine(ReturnValue(expression));
            cw.Close();
            Target.AddMethod("GetHashCode", "int")
            .WithOverride()
            .WithBody(cw);
        }
Exemple #10
0
        public static CsCodeWriter WithThrowNotImplementedException(this CsCodeWriter cw, string message = null)
        {
            if (string.IsNullOrEmpty(message))
            {
                message = "Not implemented yet";
            }
            message = message.CsEncode();
            var code = $"throw new NotImplementedException({message});";

            cw.WriteLine(code);
            return(cw);
        }
        private void Add_EqualsOverride()
        {
            // equals override
            var cw = new CsCodeWriter();

            cw.WriteLine("if (ReferenceEquals(null, obj)) return false;");
            cw.WriteLine(ReturnValue("obj is " + Target.Name + " tmp && Equals(tmp)"));
            var m = Target.AddMethod("Equals", "bool")
                    .WithOverride()
                    .WithBody(cw);

            m.AddParam("obj", "object");
        }
        private void Add_AllProperty()
        {
            var cw    = new CsCodeWriter();
            var array = new CsArguments(Cfg.Units.Select(q => q.FieldName).ToArray());

            array.CreateArray(cw, "return ");
            Target.AddProperty("All", "IReadOnlyList<UnitDefinition<" + Cfg.Name + "Unit>>")
            .WithIsPropertyReadOnly()
            .WithNoEmitField()
            .WithStatic()
            .WithOwnGetter(cw.Code)
            .Description = $"All known {Cfg.Name.FirstLower()} units";
        }
        public void WriteCode(CsCodeWriter cw)
        {
            if (!string.IsNullOrEmpty(_input.Comment))
            {
                var lines = _input.Comment.Split('\r', '\n').Where(a => !string.IsNullOrWhiteSpace(a));
                foreach (var i in lines)
                {
                    cw.WriteLine("// " + i);
                }
            }

            if (_input.Throw)
            {
                cw.WriteLine("// " + _input.OperatorParameters.DebugIs);
                cw.WriteLine("throw new " + nameof(NotImplementedException) + "();");
                return;
            }

            var right = OperatorParameters.RightMethodArgumentName;
            var left  = OperatorParameters.LeftMethodArgumentName;

            foreach (var i in _input.Vars)
            {
                cw.WriteAssign(i.Name, i.Code, true);
            }
            if (!string.IsNullOrEmpty(RightValue))
            {
                right += "Converted";
                cw.WriteAssign(right, RightValue, true);
            }

            if (string.IsNullOrEmpty(_input.UseReturnExpression))
            {
                var value = string.IsNullOrEmpty(_input.UseValueExpression)
                    ? $"{left}.Value {OperatorParameters.Oper} {right}.Value"
                    : _input.UseValueExpression;
                if (!string.IsNullOrEmpty(_input.ResultMultiplication))
                {
                    value += " * " + _input.ResultMultiplication;
                }
                cw.WriteAssign("value", value, true);

                var code = new CsArguments("value", ResultUnit).Create(OperatorParameters.Result.Value.ValueTypeName);
                cw.WriteReturn(code);
            }
            else
            {
                cw.WriteReturn(_input.UseReturnExpression);
            }
        }
Exemple #14
0
        private string Extensions_CheckConflictsCode(EnumsGeneratorItem item)
        {
            var conflicts = item.Options.IncompatibleValues.Where(a => a != null).ToArray();

            if (conflicts.Length == 0)
            {
                return(null);
            }
            var code = new CsCodeWriter();
            // check conflicts
            var optionToItem = item.Options.GetMap();

            var filter = new CodeVariable("flagsFilter");

            var duplicates = new HashSet <string>();

            foreach (var conflict in conflicts)
            {
                var first        = optionToItem[conflict.Value1];
                var second       = optionToItem[conflict.Value2];
                var argItemNames = new[] { first.GetCsName(), second.GetCsName() };
                if (argItemNames[0] == argItemNames[1])
                {
                    throw new Exception("Both options means the same");
                }

                if (!duplicates.Add(argItemNames[0] + "," + argItemNames[1]))
                {
                    continue;
                }

                filter.Expression = GetMask(MyEnum, argItemNames);
                var errorMessage = string.Format("options {0} can't be used together",
                                                 string.Join(" and ", first.AnyWithMinus, second.AnyWithMinus))
                                   .CsEncode();

                code.WriteLine(filter.GetCodeAndMarkAsDeclared());
                code.SingleLineIf($"({valueVariable} & {filter.Name}) == {filter.Name}",
                                  "throw new Exception(" + errorMessage + ");");
            }

            var m = ExtensionsClass
                    .AddMethod("CheckConflicts", "void")
                    .WithStatic()
                    .WithBody(code);

            m.AddParam(valueVariable, MyEnum.Name).UseThis = true;
            return(m.Name);
        }
Exemple #15
0
        protected void Add_EqualsUniversal(string compareType, bool nullable, OverridingType overridingType,
                                           string compareCode)
        {
            var cw = new CsCodeWriter();

            if (nullable)
            {
                cw.SingleLineIf("other is null", ReturnValue("false"));
            }
            cw.WriteLine(ReturnValue(compareCode));
            var m = Target.AddMethod("Equals", "bool")
                    .WithBody(cw);

            m.Overriding = overridingType;
            m.AddParam("other", compareType);
        }
Exemple #16
0
        public static CsCodeWriter Create(Type callerType, [CallerLineNumber] int lineNumber = 0,
                                          [CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null
                                          )
        {
            var location = new SourceCodeLocation(lineNumber, memberName, filePath)
                           .WithGeneratorClass(callerType);
            var code = new CsCodeWriter
            {
                Location = location
            };

            location = new SourceCodeLocation(0, memberName, filePath)
                       .WithGeneratorClass(callerType);

            code.WriteLine("// generator : " + location);
            return(code);
        }
        private void Add_AlternateConstructor()
        {
            var f    = GenInfo.FirstPropertyName.FirstLower();
            var s    = GenInfo.SecondPropertyName.FirstLower();
            var cw   = new CsCodeWriter();
            var code = new CsArguments(f, s).Create(GenInfo.Result.Unit);

            cw.WriteLine("{0} = {1};", ValuePropName, ValuePropName.FirstLower());
            cw.WriteLine("{0} = {1};", UnitPropName, code);

            var m = Target.AddConstructor()
                    .WithBody(cw);

            m.AddParam(ValuePropName.FirstLower(), ValuePropertyType);
            m.AddParam(f, GenInfo.First.Unit.GetTypename());
            m.AddParam(s, GenInfo.Second.Unit.GetTypename());
        }
Exemple #18
0
        protected override void GenerateOne()
        {
            Target.IsStatic = true;

            CsMethod Add1(string itemType, Action <CsCodeWriter> actions)
            {
                var cw = new CsCodeWriter();

                cw.WriteLine();
                cw.SingleLineIf("items is null", ReturnValue(Cfg.UnitTypes.Value + ".Zero"));

                actions(cw);
                var m = Target.AddMethod("Sum", Cfg.UnitTypes.Value.ValueTypeName)
                        .WithStatic()
                        .WithBody(cw);

                m.AddParam("items", MakeGenericType <IEnumerable <int> >(Target, itemType)).UseThis = true;
                return(m);
            }

            Add1(Cfg.UnitTypes.Value.ValueTypeName, cw =>
            {
                cw.WriteLine("var c = items.ToArray();");
                cw.SingleLineIf("c.Length == 0", ReturnValue(Cfg.UnitTypes.Value + ".Zero"));
                cw.SingleLineIf("c.Length == 1", ReturnValue("c[0]"));
                cw.WriteLine("var unit  = c[0].Unit;");
                cw.WriteLine("var value = c.Aggregate(0m, (x, y) => x + y.ConvertTo(unit).Value);");
                cw.WriteLine(ReturnValue($"new {Cfg.UnitTypes.Value}(value, unit)"));
            });

            Add1(Cfg.UnitTypes.Value + "?", cw =>
            {
                var c = "items.Where(a => a != null).Select(a => a.Value).Sum()";
                cw.WriteLine(ReturnValue(c));
            });

            var mm = Add1("T", cw =>
            {
                var c = "items.Select(map).Sum()";
                cw.WriteLine(ReturnValue(c));
            });

            mm.GenericArguments = new CsGenericArguments("T");
            mm.AddParam("map", "Func<T, " + Cfg.UnitTypes.Value + ">");
        }
Exemple #19
0
        public void CreateArray(CsCodeWriter c, string prefix)
        {
            c.Open(prefix + "new []");
            var lastIdx = Arguments.Length - 1;

            for (var index = 0; index <= lastIdx; index++)
            {
                var i = Arguments[index];
                if (index < lastIdx)
                {
                    i += ",";
                }
                c.WriteLine(i);
            }

            c.DecIndent();
            c.WriteLine("};");
        }
        private static bool TryHint(OperatorParams par, CsCodeWriter cw)
        {
            if (!(par.OperatorHints is null))
            {
                var builderInput = par.GetBuilder();
                if (!(builderInput is null))
                {
                    var builder = new OperatorCodeBuilder(builderInput);
                    cw.WriteLine("// scenario with hint");
                    builder.WriteCode(cw);
                    return(true);
                }
            }

            // Console.WriteLine("args.Input" + par.DebugIs);

            return(false);
        }
Exemple #21
0
        private void Add_ReadJson()
        {
            var valueTypeName = Cfg.UnitTypes.Value;
            var cw            = new CsCodeWriter();

            cw.Open("if (reader.ValueType == typeof(string))");
            cw.SingleLineIf($"objectType == typeof({valueTypeName})",
                            ReturnValue($"{valueTypeName}.Parse((string)reader.Value)"));
            cw.Close();
            cw.WriteLine("throw new NotImplementedException();");

            var m = Target.AddMethod("ReadJson", "object", "Reads the JSON representation of the object.")
                    .WithOverride()
                    .WithBody(cw);

            m.AddParam <JsonReader>("reader", Target, "The JsonReader to read from.");
            m.AddParam <Type>("objectType", Target, "Type of the object.");
            m.AddParam <object>("existingValue", Target, "The existing value of object being read.");
            m.AddParam <JsonSerializer>("serializer", Target, "The calling serializer.");
        }
Exemple #22
0
        private void Add_WriteJson()
        {
            var cw = new CsCodeWriter();

            var s = "value.ToString()";

            if (Cfg is ProductUnit pu)
            {
                s = $"(({pu.UnitTypes.Value})value).SerializeToJson()";
            }
            cw.SingleLineIf("value is null",
                            "writer.WriteNull();",
                            "writer.WriteValue(" + s + ");");

            var m = Target.AddMethod("WriteJson", "void")
                    .WithOverride()
                    .WithBody(cw);

            m.AddParam <JsonWriter>("writer", Target);
            m.AddParam <object>("value", Target);
            m.AddParam <JsonSerializer>("serializer", Target);
        }
        private static void AddConstructor(CsClass csStruct, KeysGeneratorDef def)
        {
            var propName = def.ValuePropertyName;
            var argName  = propName.FirstLower();
            var cs       = new CsCodeWriter();

            if (def.WrappedType == WrappedTypes.String)
            {
                var args      = new CsArguments($"nameof({argName})");
                var exception = args.Create(csStruct.GetTypeName <NullReferenceException>());
                cs.SingleLineIf($"{argName} is null", $"throw {exception};");

                exception = args.Create(csStruct.GetTypeName <ArgumentException>());
                cs.SingleLineIf($"{argName}.Length == 0", $"throw {exception};");

                cs.WriteAssign(propName, $"{argName}.Trim()");
            }
            else
            {
                cs.WriteAssign(propName, argName);
            }

            csStruct.AddConstructor()
            .WithParameter(new CsMethodParameter(argName, def.CsWrappedType))
            .WithBody(cs);


            for (var i = 0; i < 2; i++)
            {
                var eq = i == 0;
                var m  = csStruct.AddMethod(eq ? "==" : "!=", "bool", eq ? "Equality operator" : "Inequality operator")
                         .WithBody($"return {(eq ? "" : "!")}left.Equals(right);");

                m.AddParam("left", csStruct.Name, "first value to compare");
                m.AddParam("right", csStruct.Name, "second value to compare");
            }
        }
Exemple #24
0
        protected override void GenerateOne()
        {
            if (ClassicImpl)
            {
                Target.BaseClass = "JsonConverter";
                Add_CanConvert();
                Add_ReadJson();
                Add_WriteJson();
            }
            else
            {
                var tt            = Cfg.UnitTypes;
                var valueTypeName = tt.Value.ValueTypeName;
                Target.BaseClass = new CsArguments(valueTypeName, tt.Unit.TypeName).MakeGenericType("AbstractUnitJsonConverter");
                {
                    var cw = new CsCodeWriter();
                    cw.WriteLine("unit = unit?.Trim();");
                    cw.WriteLine(
                        $"return new {tt.Value}(value, string.IsNullOrEmpty(unit) ? {tt.Value}.BaseUnit : new {tt.Unit}(unit));");

                    var m = Target.AddMethod("Make", valueTypeName)
                            .WithOverride()
                            .WithVisibility(Visibilities.Protected)
                            .WithBody(cw);
                    m.AddParam("value", BasicUnitValuesGenerator.ValuePropertyType);
                    m.AddParam("unit", "string");
                }
                {
                    var m = Target.AddMethod("Parse", valueTypeName)
                            .WithOverride()
                            .WithVisibility(Visibilities.Protected)
                            .WithBodyFromExpression(tt.Value + ".Parse(txt)");
                    m.AddParam("txt", "string");
                }
            }
        }
Exemple #25
0
        protected void Add_Constructor(Col1 col)
        {
            var target = Target;
            var code   = new CsCodeWriter();
            var m      = target.AddConstructor("creates instance of " + target.Name);
            var c      = col.Writer1.Code;

            if (!string.IsNullOrEmpty(c))
            {
                code.WriteLine(c);
            }
            foreach (var i in col.Items)
            {
                var flags = i.CheckingFlags;
                code.CheckArgument(i.ArgName, flags.ConvertToArgChecking(), Target);
                var p = m.AddParam(i.PropertyName.FirstLower(), i.PropertyType, i.Description);
                if ((flags & Flags1.Optional) != 0)
                {
                    p.ConstValue = "null";
                }

                /*if ((flags & Flags1.TrimValue) != 0)
                 * {
                 *  code.WriteLine("{0} = {0}?.Trim();", i.ArgName);
                 *  flags &= ~Flags1.TrimValue;
                 *
                 *  if ((flags & Flags1.NotWhitespace) != 0)
                 *  {
                 *      flags &= ~Flags1.NotWhitespace;
                 *      flags |= Flags1.NotEmpty;
                 *  }
                 * }*/

                /*if ((flags & Flags1.NotNull) != 0)
                 * {
                 *  flags &= ~Flags1.NotNull;
                 *  p.Attributes.Add(CsAttribute.Make<NotNullAttribute>(target));
                 *  var throwCode = new Args($"nameof({i.ArgName})")
                 *      .Throw<NullReferenceException>(target);
                 *  code.SingleLineIf($"{i.ArgName} is null", throwCode);
                 * }*/

                /*if ((flags & Flags1.NotWhitespace) != 0)
                 * {
                 *  flags &= ~(Flags1.NotEmpty | Flags1.NotWhitespace);
                 *  // var m = nameof(string.IsNullOrWhiteSpace);
                 *  var throwCode = new Args($"nameof({i.ArgName})")
                 *      .Throw<ArgumentException>(target);
                 *  code.SingleLineIf($"string.IsNullOrWhiteSpace({i.ArgName})", throwCode);
                 *
                 *  flags &= ~(Flags1.NotNullOrWhitespace | Flags1.NotNullOrEmpty);
                 * }
                 *
                 * if ((flags & Flags1.NotEmpty) != 0)
                 * {
                 *  flags &= ~Flags1.NotEmpty;
                 *  //var m = nameof(string.IsNullOrEmpty);
                 *  var throwCode = new Args($"nameof({i.ArgName})")
                 *      .Throw<ArgumentException>(target);
                 *  code.SingleLineIf($"string.IsNullOrEmpty({i.ArgName})", throwCode);
                 *
                 *  flags &= ~(Flags1.NotNullOrWhitespace | Flags1.NotNullOrEmpty);
                 * }*/

                if ((flags & Flags1.DoNotAssignProperty) == 0)
                {
                    code.WriteAssign(i.PropertyName, i.Expression);
                }
            }

            c = col.Writer2.Code;
            if (!string.IsNullOrEmpty(c))
            {
                code.WriteLine(c);
            }

            m.WithBody(code);
        }
Exemple #26
0
        private void CreateNamedParameters()
        {
            foreach (var option in _item.Options.Values)
            {
                var p = option.Parameter;
                if (string.IsNullOrEmpty(p?.Value) || p.Encoder is null)
                {
                    continue;
                }

                var str = MyStruct;

                var kind = string.IsNullOrEmpty(p.Name)
                    ? ParametrizedOption.OptionValueProcessorKind.SingleValue
                    : ParametrizedOption.OptionValueProcessorKind.Dictionary;
                if (p.IsCollection)
                {
                    kind = ParametrizedOption.OptionValueProcessorKind.List;
                }

                var cre = new ShellEnumOptionsGenerator(_item.EnumName + option.GetCsName() + "Values", MyNamespace,
                                                        p.Encoder?.EnumValues);
                cre.MakeEnumIfNecessary();
                cre.MakeExtensionMethod(ExtensionsClass);

                var propInfo = p.Encoder.GetPropertyTypeName(kind, str, cre.TypeName);

                var prop = str.AddProperty(option.GetCsName(),
                                           propInfo.PropertyType)
                           .WithNoEmitField()
                           .WithMakeAutoImplementIfPossible();
                prop.ConstValue  = propInfo.PropertyInit;
                prop.Description = option.FullDescription;
                {
                    var key           = p.Name?.ToLower();
                    var value         = p.Value.Camelise(true).FirstLower();
                    var setExpression = prop.Name;

                    var methodName = "With" + prop.Name;
                    var cs         = CsCodeWriter.Create <SingleTaskEnumsGenerator>();
                    {
                        switch (kind)
                        {
                        case ParametrizedOption.OptionValueProcessorKind.SingleValue:
                            cs.WriteLine($"{setExpression} = {value};");
                            break;

                        case ParametrizedOption.OptionValueProcessorKind.Dictionary:
                            cs.WriteLine($"{setExpression}[{key}] = {value};");
                            break;

                        case ParametrizedOption.OptionValueProcessorKind.List:
                            cs.WriteLine($"if ({value.CodeHasElements("Length")})");
                            cs.IncIndent();
                            cs.SingleLineForeach("tmp", value, $"{setExpression}.Add(tmp);");
                            cs.DecIndent();
                            methodName = "WithAppend" + prop.Name;
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }
                    }
                    cs.WriteLine("return this;");
                    var fluentMethod = str.AddMethod(methodName, str.Name)
                                       .WithBody(cs);

                    var fmParams = FluentMethodParameters.Get(kind, propInfo);
                    if (fmParams.AddKey)
                    {
                        fluentMethod.AddParam <string>(key, str);
                    }
                    var par = fluentMethod.AddParam(value, fmParams.ValueParameterType2);
                    par.Description          = p.ValueDescription;
                    fluentMethod.Description = prop.Description;
                }

                switch (kind)
                {
                case ParametrizedOption.OptionValueProcessorKind.List:
                {
                    if (cre.HasEnum)
                    {
                        throw new NotSupportedException();
                    }
                    apps.Add((cc, re) =>
                        {
                            cc.WriteDescriptionComment(option);
                            var condition = prop.Name.CodeHasElements();
                            cc.Open($"if ({condition})");
                            {
                                var tmp = prop.Name.FirstLower() + "Item";
                                cc.WriteLine($"yield return {option.AnyWithMinus.CsEncode()};");
                                var input      = new ParametrizedOption.OptionValueProcessorInput(tmp, kind, re);
                                var expression = p.Encoder.Convert(input);
                                cc.SingleLineForeach(tmp, prop.Name, $"yield return {expression};");
                            }
                            cc.Close();
                        });
                }
                break;

                case ParametrizedOption.OptionValueProcessorKind.Dictionary:
                {
                    if (cre.HasEnum)
                    {
                        throw new NotSupportedException();
                    }
                    apps.Add((cc, re) =>
                        {
                            cc.WriteDescriptionComment(option);
                            cc.Open("foreach(var pair in " + prop.Name + ")");
                            cc.WriteLine("yield return " + option.AnyWithMinus.CsEncode() + ';');
                            var input      = new ParametrizedOption.OptionValueProcessorInput("pair.Value", kind, re);
                            var expression = p.Encoder.Convert(input);
                            if (p.IsCollection)
                            {
                                throw new NotSupportedException();
                            }
                            cc.WriteLine($"var value = {expression};");
                            cc.WriteLine("yield return $\"{pair.Key}={value}\";");
                            cc.Close();
                        });
                }
                break;

                case ParametrizedOption.OptionValueProcessorKind.SingleValue:
                {
                    apps.Add((cc, resolver) =>
                        {
                            cc.WriteDescriptionComment(option);
                            var condition = p.Encoder.GetCondition(prop.Name, kind);
                            cc.Open($"if ({condition})");
                            {
                                cc.WriteLine("yield return " + option.AnyWithMinus.CsEncode() + ';');
                                var ex = prop.Name;
                                if (prop.Type.EndsWith("?"))
                                {
                                    ex += ".Value";
                                }
                                var input      = new ParametrizedOption.OptionValueProcessorInput(ex, kind, resolver);
                                var expression = p.Encoder.Convert(input);
                                if (p.IsCollection)
                                {
                                    cc.SingleLineForeach("tmp", expression, "yield return tmp;");
                                }
                                else
                                {
                                    cc.WriteLine($"yield return {expression};");
                                }
                            }
                            cc.Close();
                        });
                }
                break;
                }
            }
        }
Exemple #27
0
        private bool CreateEnumAndConversionMethods()
        {
            var parts = _item.OwnerClasses;
            var conflictsCodeMethod = Extensions_CheckConflictsCode(_item);

            var optionsToStringCode = new CsCodeWriter();

            optionsToStringCode.WriteLine("// generator : " + GetType().Name);
            if (!string.IsNullOrEmpty(conflictsCodeMethod))
            {
                optionsToStringCode.WriteLine($"{conflictsCodeMethod}({valueVariable});");
            }
            var fb = new EnumFlagsBuilder(MyEnum);

            fb.AddFlagsAttribute(MyNamespace);

            var enumSource = from q in _item.Options.Values
                             where string.IsNullOrEmpty(q.Parameter?.Value)
                             select q;
            var generate = false;

            foreach (var option in enumSource)
            {
                generate = true;
                var enumItem = new CsEnumItem(option.GetCsName())
                {
                    Description = option.FullDescription,
                };
                var stringValue = GetStringValue(preferLongNameVariable, option, ExtensionsClass);
                optionsToStringCode.WriteDescriptionComment(option);
                var condition = GetEnumCondition(valueVariable, MyEnum, enumItem);
                optionsToStringCode.SingleLineIf(condition, $"yield return {stringValue};");
                MyStruct_AddWithMethod(enumItem, fb.Value == 1);

                fb.Append(enumItem);

                {
                    apps.Add((w, r) =>
                    {
                        var stringValue = GetStringValue(preferLongNameVariable, option, ExtensionsClass);
                        w.WriteDescriptionComment(option);
                        var condition = GetEnumCondition(flagsPropertyName, MyEnum, enumItem);
                        w.SingleLineIf(condition, $"yield return {stringValue};");
                    });
                }
            }

            if (!generate)
            {
                return(false);
            }
            {
                var m = ExtensionsClass
                        .AddMethod("OptionsToString", MyNamespace.GetTypeName <IEnumerable <string> >())
                        .WithStatic()
                        .WithBody(optionsToStringCode);
                m.AddParam(valueVariable, MyEnumTypeName).UseThis = true;
                m.AddParam <OptionPreference>(preferLongNameVariable, ExtensionsClass).ConstValue =
                    ExtensionsClass.GetEnumValueCode(OptionPreference.Short);
            }

            AddEnumToOutput(parts, MyNamespace, MyEnum);
            return(true);
        }
Exemple #28
0
        public static void CheckArgument(this CsCodeWriter code, string argName, ArgChecking flags,
                                         ITypeNameResolver resolver)
        {
            if (flags == ArgChecking.None)
            {
                return;
            }

            var canBeNull     = true;
            var argNameToRead = argName + "?";

            if ((flags & ArgChecking.NotNull) != 0)
            {
                var throwCode = new CsArguments($"nameof({argName})")
                                .Throw <NullReferenceException>(resolver);
                code.SingleLineIf($"{argName} is null", throwCode);
                canBeNull     = false;
                argNameToRead = argName;
            }

            if ((flags & ArgChecking.TrimValue) != 0)
            {
                code.WriteLine("{0} = {1}.Trim();", argName, argNameToRead);
                flags &= ~ArgChecking.TrimValue;

                if ((flags & ArgChecking.NotWhitespace) != 0)
                {
                    flags &= ~ArgChecking.NotWhitespace;
                    flags |= ArgChecking.NotEmpty;
                }
            }

            if ((flags & ArgChecking.NotNull) != 0 && canBeNull)
            {
                flags &= ~ArgChecking.NotNull;
                //p.Attributes.Add(CsAttribute.Make<NotNullAttribute>(target));
                var throwCode = new CsArguments($"nameof({argName})")
                                .Throw <NullReferenceException>(resolver);
                code.SingleLineIf($"{argName} is null", throwCode);
            }

            if ((flags & ArgChecking.NotWhitespace) != 0)
            {
                flags &= ~(ArgChecking.NotEmpty | ArgChecking.NotWhitespace);
                // var m = nameof(string.IsNullOrWhiteSpace);
                var throwCode = new CsArguments($"nameof({argName})")
                                .Throw <ArgumentException>(resolver);
                code.SingleLineIf($"string.IsNullOrWhiteSpace({argName})", throwCode);

                flags &= ~(ArgChecking.NotNullOrWhitespace | ArgChecking.NotNullOrEmpty);
            }

            if ((flags & ArgChecking.NotEmpty) != 0)
            {
                flags &= ~ArgChecking.NotEmpty;
                var throwCode = new CsArguments($"nameof({argName})")
                                .Throw <ArgumentException>(resolver);
                var condition =
                    canBeNull
                        ? $"string.IsNullOrEmpty({argName})"
                        : $"{argName}.Length == 0";

                code.SingleLineIf(condition, throwCode);
            }
        }
Exemple #29
0
 public static void SingleLineIfReturn(this CsCodeWriter cs, string condition, string result)
 {
     cs.SingleLineIf(condition, "return " + result + ";");
 }