xronos /Microsoft.Scripting/Actions/Calls/MethodCandidate.cs

Language C# Lines 308
MD5 Hash 70a8bf82b85e3d89b15298c664b9fc34 Estimated Cost $5,405 (why?)
Repository https://bitbucket.org/stefanrusek/xronos View Raw File
  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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A 
 * copy of the license can be found in the License.html file at the root of this distribution. If 
 * you cannot locate the  Microsoft Public License, please send an email to 
 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

#if CODEPLEX_40
using System;
#else
using System; using Microsoft;
#endif
using System.Collections.Generic;
using System.Diagnostics;
#if CODEPLEX_40
using System.Dynamic;
#else
using Microsoft.Scripting;
#endif
using System.Text;
using Microsoft.Contracts;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Generation;

namespace Microsoft.Scripting.Actions.Calls {
    /// <summary>
    /// MethodCandidate represents the different possible ways of calling a method or a set of method overloads.
    /// A single method can result in multiple MethodCandidates. Some reasons include:
    /// - Every optional parameter or parameter with a default value will result in a candidate
    /// - The presence of ref and out parameters will add a candidate for languages which want to return the updated values as return values.
    /// - ArgumentKind.List and ArgumentKind.Dictionary can result in a new candidate per invocation since the list might be different every time.
    ///
    /// Each MethodCandidate represents the parameter type for the candidate using ParameterWrapper.
    /// 
    /// Contrast this with MethodTarget which represents the real physical invocation of a method
    /// </summary>
    class MethodCandidate {
        private MethodTarget _target;
        private List<ParameterWrapper> _parameters;
        private NarrowingLevel _narrowingLevel;

        internal MethodCandidate(MethodCandidate previous, NarrowingLevel narrowingLevel) {
            this._target = previous.Target;
            this._parameters = previous._parameters;
            _narrowingLevel = narrowingLevel;
        }

        internal MethodCandidate(MethodTarget target, List<ParameterWrapper> parameters) {
            Debug.Assert(target != null);

            _target = target;
            _parameters = parameters;
            _narrowingLevel = NarrowingLevel.None;
            parameters.TrimExcess();
        }

        public MethodTarget Target {
            get { return _target; }
        }

        public NarrowingLevel NarrowingLevel {
            get {
                return _narrowingLevel;
            }
        }

        [Confined]
        public override string ToString() {
            return string.Format("MethodCandidate({0})", Target);
        }

        internal bool IsApplicable(Type[] types, NarrowingLevel narrowingLevel, List<ConversionResult> conversionResults) {
            // attempt to convert each parameter
            bool res = true;
            for (int i = 0; i < types.Length; i++) {
                bool success = _parameters[i].HasConversionFrom(types[i], narrowingLevel);

                conversionResults.Add(new ConversionResult(types[i], _parameters[i].Type, i, !success));

                res &= success;
            }

            return res;
        }

        internal bool IsApplicable(DynamicMetaObject[] objects, NarrowingLevel narrowingLevel, List<ConversionResult> conversionResults) {
            // attempt to convert each parameter
            bool res = true;
            for (int i = 0; i < objects.Length; i++) {
                /*if (objects[i].NeedsDeferral) {
                    conversionResults.Add(new ConversionResult(typeof(Dynamic), _parameters[i].Type, i, false));
                } else*/ {
                    bool success = _parameters[i].HasConversionFrom(objects[i].GetLimitType(), narrowingLevel);

                    conversionResults.Add(new ConversionResult(objects[i].GetLimitType(), _parameters[i].Type, i, !success));

                    res &= success;
                }
            }

            return res;
        }

        internal static Candidate GetPreferredCandidate(MethodCandidate one, MethodCandidate two, CallTypes callType, Type[] actualTypes) {
            Candidate cmpParams = ParameterWrapper.GetPreferredParameters(one.Parameters, two.Parameters, actualTypes);
            if (cmpParams.Chosen()) {
                return cmpParams;
            }

            Candidate ret = MethodTarget.CompareEquivalentParameters(one.Target, two.Target);
            if (ret.Chosen()) {
                return ret;
            }

            if (CompilerHelpers.IsStatic(one.Target.Method) && !CompilerHelpers.IsStatic(two.Target.Method)) {
                return callType == CallTypes.ImplicitInstance ? Candidate.Two : Candidate.One;
            } else if (!CompilerHelpers.IsStatic(one.Target.Method) && CompilerHelpers.IsStatic(two.Target.Method)) {
                return callType == CallTypes.ImplicitInstance ? Candidate.One : Candidate.Two;
            }

            return Candidate.Equivalent;
        }

        internal static Candidate GetPreferredCandidate(MethodCandidate one, MethodCandidate two, CallTypes callType, DynamicMetaObject[] actualTypes) {
            Candidate cmpParams = ParameterWrapper.GetPreferredParameters(one.Parameters, two.Parameters, actualTypes);
            if (cmpParams.Chosen()) {
                return cmpParams;
            }

            Candidate ret = MethodTarget.CompareEquivalentParameters(one.Target, two.Target);
            if (ret.Chosen()) {
                return ret;
            }

            if (CompilerHelpers.IsStatic(one.Target.Method) && !CompilerHelpers.IsStatic(two.Target.Method)) {
                return callType == CallTypes.ImplicitInstance ? Candidate.Two : Candidate.One;
            } else if (!CompilerHelpers.IsStatic(one.Target.Method) && CompilerHelpers.IsStatic(two.Target.Method)) {
                return callType == CallTypes.ImplicitInstance ? Candidate.One : Candidate.Two;
            }

            return Candidate.Equivalent;
        }


        /// <summary>
        /// Builds a new MethodCandidate which takes count arguments and the provided list of keyword arguments.
        /// 
        /// The basic idea here is to figure out which parameters map to params or a dictionary params and
        /// fill in those spots w/ extra ParameterWrapper's.  
        /// </summary>
        internal MethodCandidate MakeParamsExtended(ActionBinder binder, int count, string[] names) {
            Debug.Assert(BinderHelpers.IsParamsMethod(_target.Method));

            List<ParameterWrapper> newParameters = new List<ParameterWrapper>(count);
            
            // keep track of which kw args map to a real argument, and which ones
            // map to the params dictionary.
            List<string> unusedNames = new List<string>(names);
            List<int> unusedNameIndexes = new List<int>();
            for (int i = 0; i < unusedNames.Count; i++) {
                unusedNameIndexes.Add(i);
            }

            // if we don't have a param array we'll have a param dict which is type object
            ParameterWrapper paramsArrayParameter = null, paramsDictParameter = null;
            int paramsArrayIndex = -1, paramsDictIndex = -1;

            for (int i = 0; i < _parameters.Count; i++) {
                ParameterWrapper parameter = _parameters[i];

                if (parameter.IsParamsDict) {
                    paramsDictParameter = parameter;
                    paramsDictIndex = i;
                } else if (parameter.IsParamsArray) {
                    paramsArrayParameter = parameter;
                    paramsArrayIndex = i;
                } else {
                    int j = unusedNames.IndexOf(parameter.Name);
                    if (j != -1) {
                        unusedNames.RemoveAt(j);
                        unusedNameIndexes.RemoveAt(j);
                    }
                    newParameters.Add(parameter);
                }
            }

            if (paramsArrayIndex != -1) {
                Type elementType = paramsArrayParameter.Type.GetElementType();
                bool nonNullItems = CompilerHelpers.ProhibitsNullItems(paramsArrayParameter.ParameterInfo);

                while (newParameters.Count < (count - unusedNames.Count)) {
                    ParameterWrapper param = new ParameterWrapper(binder, paramsArrayParameter.ParameterInfo, elementType, null, nonNullItems, false, false);
                    newParameters.Insert(System.Math.Min(paramsArrayIndex, newParameters.Count), param);
                }
            }

            if (paramsDictIndex != -1) {
                Type elementType = paramsDictParameter.Type.GetElementType();
                bool nonNullItems = CompilerHelpers.ProhibitsNullItems(paramsDictParameter.ParameterInfo);
                
                foreach (string si in unusedNames) {
                    newParameters.Add(new ParameterWrapper(binder, paramsDictParameter.ParameterInfo, typeof(object), si, nonNullItems, false, false));
                }
            } else if (unusedNames.Count != 0) {
                // unbound kw args and no where to put them, can't call...
                // TODO: We could do better here because this results in an incorrect arg # error message.
                return null;
            }

            // if we have too many or too few args we also can't call
            if (count != newParameters.Count) {
                return null;
            }

            return new MethodCandidate(_target.MakeParamsExtended(count, unusedNames.ToArray(), unusedNameIndexes.ToArray()), newParameters);
        }

        internal string ToSignatureString(string name, CallTypes callType) {
            StringBuilder buf = new StringBuilder(name);
            buf.Append("(");
            bool isFirstArg = true;
            int i = 0;
            if (callType == CallTypes.ImplicitInstance) i = 1;
            for (; i < _parameters.Count; i++) {
                if (isFirstArg) isFirstArg = false;
                else buf.Append(", ");
                buf.Append(_parameters[i].ToSignatureString());
            }
            buf.Append(")");
            return buf.ToString(); //@todo add helper info for more interesting signatures
        }

        internal IList<ParameterWrapper> Parameters {
            get {
                return _parameters;
            }
        }

        internal bool HasParamsDictionary() {
            foreach (ParameterWrapper pw in _parameters) {
                // can't bind to methods that are params dictionaries, only to their extended forms.
                if (pw.IsParamsDict) return true;
            }
            return false;
        }

        internal bool TryGetNormalizedArguments<T>(T[] argTypes, string[] names, out T[] args, out CallFailure failure) {
            if (names.Length == 0) {
                // no named arguments, success!
                args = argTypes;
                failure = null;
                return true;
            }

            T[] res = new T[argTypes.Length];
            Array.Copy(argTypes, res, argTypes.Length - names.Length);
            List<string> unboundNames = null;
            List<string> duppedNames = null;

            for (int i = 0; i < names.Length; i++) {
                bool found = false;
                for (int j = 0; j < _parameters.Count; j++) {
                    if (_parameters[j].Name == names[i]) {
                        found = true;

                        if (res[j] != null) {
                            if (duppedNames == null) duppedNames = new List<string>();
                            duppedNames.Add(names[i]);
                        } else {
                            res[j] = argTypes[i + argTypes.Length - names.Length];
                        }
                        break;
                    }
                }

                if (!found) {
                    if (unboundNames == null) unboundNames = new List<string>();
                    unboundNames.Add(names[i]);
                }
            }

            if (unboundNames != null) {
                failure = new CallFailure(Target, unboundNames.ToArray(), true);
                args = null;
                return false;
            } else if (duppedNames != null) {
                failure = new CallFailure(Target, duppedNames.ToArray(), false);
                args = null;
                return false;
            }

            failure = null;
            args = res;
            return true;
        }
    }

}
Back to Top