-
Notifications
You must be signed in to change notification settings - Fork 482
/
Copy pathInstanceBuilder.cs
233 lines (198 loc) · 10.4 KB
/
InstanceBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using CommandLine.Infrastructure;
using CSharpx;
using RailwaySharp.ErrorHandling;
namespace CommandLine.Core
{
static class InstanceBuilder
{
public static ParserResult<T> Build<T>(
Maybe<Func<T>> factory,
Func<IEnumerable<string>, IEnumerable<OptionSpecification>, Result<IEnumerable<Token>, Error>> tokenizer,
IEnumerable<string> arguments,
StringComparer nameComparer,
bool ignoreValueCase,
CultureInfo parsingCulture,
bool autoHelp,
bool autoVersion,
IEnumerable<ErrorType> nonFatalErrors)
{
return Build(
factory,
tokenizer,
arguments,
nameComparer,
ignoreValueCase,
parsingCulture,
autoHelp,
autoVersion,
false,
nonFatalErrors);
}
public static ParserResult<T> Build<T>(
Maybe<Func<T>> factory,
Func<IEnumerable<string>, IEnumerable<OptionSpecification>, Result<IEnumerable<Token>, Error>> tokenizer,
IEnumerable<string> arguments,
StringComparer nameComparer,
bool ignoreValueCase,
CultureInfo parsingCulture,
bool autoHelp,
bool autoVersion,
bool allowMultiInstance,
IEnumerable<ErrorType> nonFatalErrors) {
var typeInfo = factory.MapValueOrDefault(f => f().GetType(), typeof(T));
var specProps = typeInfo.GetSpecifications(pi => SpecificationProperty.Create(
Specification.FromProperty(pi), pi, Maybe.Nothing<object>()))
.Memoize();
var specs = from pt in specProps select pt.Specification;
var optionSpecs = specs
.ThrowingValidate(SpecificationGuards.Lookup)
.OfType<OptionSpecification>()
.Memoize();
Func<T> makeDefaultImmutable = () => ReflectionHelper.CreateDefaultImmutableInstance<T>((from p in specProps select p.Specification.ConversionType).ToArray());
Func<T> makeDefault =
typeof(T).IsMutable()
? () => factory.MapValueOrDefault(f => f(), () => typeof(T).HasParameterlessConstructor() ? Activator.CreateInstance<T>() : makeDefaultImmutable())
: makeDefaultImmutable;
Func<IEnumerable<Error>, ParserResult<T>> notParsed =
errs => new NotParsed<T>(makeDefault().GetType().ToTypeInfo(), errs);
var argumentsList = arguments.Memoize();
Func<ParserResult<T>> buildUp = () =>
{
var tokenizerResult = tokenizer(argumentsList, optionSpecs);
var tokens = tokenizerResult.SucceededWith().Memoize();
var partitions = TokenPartitioner.Partition(
tokens,
name => TypeLookup.FindTypeDescriptorAndSibling(name, optionSpecs, nameComparer));
var optionsPartition = partitions.Item1.Memoize();
var valuesPartition = partitions.Item2.Memoize();
var errorsPartition = partitions.Item3.Memoize();
var optionSpecPropsResult =
OptionMapper.MapValues(
(from pt in specProps where pt.Specification.IsOption() select pt),
optionsPartition,
(vals, type, isScalar, isFlag) => TypeConverter.ChangeType(vals, type, isScalar, isFlag, parsingCulture, ignoreValueCase),
nameComparer);
var valueSpecPropsResult =
ValueMapper.MapValues(
(from pt in specProps where pt.Specification.IsValue() orderby ((ValueSpecification)pt.Specification).Index select pt),
valuesPartition,
(vals, type, isScalar) => TypeConverter.ChangeType(vals, type, isScalar, false, parsingCulture, ignoreValueCase));
var missingValueErrors = from token in errorsPartition
select
new MissingValueOptionError(
optionSpecs.Single(o => token.Text.MatchName(o.ShortName, o.LongName, nameComparer))
.FromOptionSpecification());
var specPropsWithValue =
optionSpecPropsResult.SucceededWith().Concat(valueSpecPropsResult.SucceededWith()).Memoize();
var setPropertyErrors = new List<Error>();
//build the instance, determining if the type is mutable or not.
T instance;
if (typeInfo.IsMutable() && (!factory.IsNothing() || typeInfo.HasParameterlessConstructor()))
{
instance = BuildMutable(factory, specPropsWithValue, setPropertyErrors);
}
else
{
instance = BuildImmutable(typeInfo, factory, specProps, specPropsWithValue, setPropertyErrors);
}
var validationErrors = specPropsWithValue.Validate(SpecificationPropertyRules.Lookup(tokens, allowMultiInstance));
var allErrors =
tokenizerResult.SuccessMessages()
.Concat(missingValueErrors)
.Concat(optionSpecPropsResult.SuccessMessages())
.Concat(valueSpecPropsResult.SuccessMessages())
.Concat(validationErrors)
.Concat(setPropertyErrors)
.Memoize();
var warnings = from e in allErrors where nonFatalErrors.Contains(e.Tag) select e;
return allErrors.Except(warnings).ToParserResult(instance);
};
var preprocessorErrors = (
argumentsList.Any()
? arguments.Preprocess(PreprocessorGuards.Lookup(nameComparer, autoHelp, autoVersion))
: Enumerable.Empty<Error>()
).Memoize();
var result = argumentsList.Any()
? preprocessorErrors.Any()
? notParsed(preprocessorErrors)
: buildUp()
: buildUp();
return result;
}
private static T BuildMutable<T>(Maybe<Func<T>> factory, IEnumerable<SpecificationProperty> specPropsWithValue, List<Error> setPropertyErrors )
{
var mutable = factory.MapValueOrDefault(f => f(), () => Activator.CreateInstance<T>());
setPropertyErrors.AddRange(
mutable.SetProperties(
specPropsWithValue,
sp => sp.Value.IsJust(),
sp => sp.Value.FromJustOrFail()
)
);
setPropertyErrors.AddRange(
mutable.SetProperties(
specPropsWithValue,
sp => sp.Value.IsNothing() && sp.Specification.DefaultValue.IsJust(),
sp => sp.Specification.DefaultValue.FromJustOrFail()
)
);
setPropertyErrors.AddRange(
mutable.SetProperties(
specPropsWithValue,
sp => sp.Value.IsNothing()
&& sp.Specification.TargetType == TargetType.Sequence
&& sp.Specification.DefaultValue.MatchNothing(),
sp => sp.Property.PropertyType.GetTypeInfo().GetGenericArguments().Single().CreateEmptyArray()
)
);
return mutable;
}
private static T BuildImmutable<T>(Type typeInfo, Maybe<Func<T>> factory, IEnumerable<SpecificationProperty> specProps, IEnumerable<SpecificationProperty> specPropsWithValue, List<Error> setPropertyErrors)
{
var ctor = typeInfo.GetTypeInfo().GetConstructor(
specProps.Select(sp => sp.Property.PropertyType).ToArray()
);
if(ctor == null)
{
throw new InvalidOperationException($"Type {typeInfo.FullName} appears to be immutable, but no constructor found to accept values.");
}
try
{
var values =
(from prms in ctor.GetParameters()
join sp in specPropsWithValue on prms.Name.ToLower() equals sp.Property.Name.ToLower() into spv
from sp in spv.DefaultIfEmpty()
select
sp == null
? specProps.First(s => String.Equals(s.Property.Name, prms.Name, StringComparison.CurrentCultureIgnoreCase))
.Property.PropertyType.GetDefaultValue()
: sp.Value.GetValueOrDefault(
sp.Specification.DefaultValue.GetValueOrDefault(
sp.Specification.ConversionType.CreateDefaultForImmutable()))).ToArray();
var immutable = (T)ctor.Invoke(values);
return immutable;
}
catch (Exception)
{
var ctorArgs = specPropsWithValue
.Select(x => x.Property.Name.ToLowerInvariant()).ToArray();
throw GetException(ctorArgs);
}
Exception GetException(string[] s)
{
var ctorSyntax = s != null ? " Constructor Parameters can be ordered as: " + $"'({string.Join(", ", s)})'" : string.Empty;
var msg =
$"Type {typeInfo.FullName} appears to be Immutable with invalid constructor. Check that constructor arguments have the same name and order of their underlying Type. {ctorSyntax}";
InvalidOperationException invalidOperationException = new InvalidOperationException(msg);
return invalidOperationException;
}
}
}
}