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; } }
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"); } }
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); }
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); }
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 + ">"); }
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."); }
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 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); }
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); } }
public static void SingleLineIfReturn(this CsCodeWriter cs, string condition, string result) { cs.SingleLineIf(condition, "return " + result + ";"); }