-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy pathInstanceBuilder.cs
259 lines (221 loc) · 11.8 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
// 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 CommandLine.Infrastructure;
using CSharpx;
using RailwaySharp.ErrorHandling;
using System.Reflection;
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,
false,
autoVersion,
false,
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 autoHelpShortName,
bool autoVersion,
bool autoVersionShortName,
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 autoSpecs = AddAutoSpecs(specs, nameComparer, autoHelp, autoHelpShortName, autoVersion, autoVersionShortName);
var optionSpecs = autoSpecs
.ThrowingValidate(SpecificationGuards.Lookup)
.OfType<OptionSpecification>()
.Memoize();
Func<T> makeDefault = () =>
typeof(T).IsMutable()
? factory.MapValueOrDefault(f => f(), () => Activator.CreateInstance<T>())
: ReflectionHelper.CreateDefaultImmutableInstance<T>(
(from p in specProps select p.Specification.ConversionType).ToArray());
Func<IEnumerable<Error>, ParserResult<T>> notParsed =
errs => new NotParsed<T>(makeDefault().GetType().ToTypeInfo(), errs);
var argumentsList = arguments.Memoize();
var tokenizerResult = tokenizer(argumentsList, optionSpecs);
var tokens = tokenizerResult.SucceededWith().Memoize();
Func<ParserResult<T>> buildUp = () =>
{
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) => TypeConverter.ChangeType(vals, type, isScalar, 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, 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() == true)
{
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 = (
tokens.Any()
? tokens.Preprocess(PreprocessorGuards.Lookup(nameComparer, autoHelp, autoHelpShortName, autoVersion, autoVersionShortName))
: Enumerable.Empty<Error>()
).Memoize();
var result = argumentsList.Any()
? preprocessorErrors.Any()
? notParsed(preprocessorErrors)
: buildUp()
: buildUp();
return result;
}
private static IEnumerable<Specification> AddAutoSpecs(IEnumerable<Specification> specs, StringComparer nameComparer, bool autoHelp, bool autoHelpShortName, bool autoVersion, bool autoVersionShortName)
{
var optionSpecs = specs.OfType<OptionSpecification>().Memoize();
bool useHelpShortName = autoHelpShortName && !(optionSpecs.Any(spec => nameComparer.Equals(spec.ShortName, "h")));
bool useVersionShortName = autoVersionShortName && !(optionSpecs.Any(spec => nameComparer.Equals(spec.ShortName, "V"))); // Uppercase V
bool addAutoHelp = autoHelp && !(optionSpecs.Any(spec => nameComparer.Equals(spec.LongName, "help")));
bool addAutoVersion = autoVersion && !(optionSpecs.Any(spec => nameComparer.Equals(spec.LongName, "version")));
var autoSpecs = new List<OptionSpecification>(2);
if (addAutoHelp)
{
autoSpecs.Add(OptionSpecification.NewSwitch(useHelpShortName ? "h" : String.Empty, "help", false, "Display this help screen.", String.Empty));
}
if (addAutoVersion)
{
autoSpecs.Add(OptionSpecification.NewSwitch(useVersionShortName ? "V" : String.Empty, "version", false, "Display version information.", String.Empty));
}
return specs.Concat(autoSpecs);
}
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;
}
}
}
}