public ToolTipData (ICSharpCode.NRefactory.CSharp.SyntaxTree unit, ICSharpCode.NRefactory.Semantics.ResolveResult result, ICSharpCode.NRefactory.CSharp.AstNode node, CSharpAstResolver file) { this.Unit = unit; this.Result = result; this.Node = node; this.Resolver = file; }
public IMethod ResolveConstructor(ITypeResolveContext context) { CSharpResolver r = new CSharpResolver(context); IType type = attributeType.Resolve(context); int totalArgumentCount = 0; if (positionalArguments != null) totalArgumentCount += positionalArguments.Count; if (namedCtorArguments != null) totalArgumentCount += namedCtorArguments.Count; ResolveResult[] arguments = new ResolveResult[totalArgumentCount]; string[] argumentNames = new string[totalArgumentCount]; int i = 0; if (positionalArguments != null) { while (i < positionalArguments.Count) { IConstantValue cv = positionalArguments[i]; arguments[i] = cv.Resolve(context); i++; } } if (namedCtorArguments != null) { foreach (var pair in namedCtorArguments) { argumentNames[i] = pair.Key; arguments[i] = pair.Value.Resolve(context); i++; } } MemberResolveResult mrr = r.ResolveObjectCreation(type, arguments, argumentNames) as MemberResolveResult; return mrr != null ? mrr.Member as IMethod : null; }
public override IList<ResolveResult> GetArgumentsForCall() { ResolveResult[] results = new ResolveResult[Member.Parameters.Count]; List<ResolveResult> paramsArguments = IsExpandedForm ? new List<ResolveResult>() : null; // map arguments to parameters: for (int i = 0; i < Arguments.Count; i++) { int mappedTo; if (argumentToParameterMap != null) mappedTo = argumentToParameterMap[i]; else mappedTo = IsExpandedForm ? Math.Min(i, results.Length - 1) : i; if (mappedTo >= 0 && mappedTo < results.Length) { if (IsExpandedForm && mappedTo == results.Length - 1) paramsArguments.Add(Arguments[i]); else results[mappedTo] = Arguments[i]; } } if (IsExpandedForm) results[results.Length - 1] = new ArrayCreateResolveResult(Member.Parameters.Last().Type, null, paramsArguments.ToArray()); for (int i = 0; i < results.Length; i++) { if (results[i] == null) { if (Member.Parameters[i].IsOptional) { results[i] = new ConstantResolveResult(Member.Parameters[i].Type, Member.Parameters[i].ConstantValue); } else { results[i] = ErrorResolveResult.UnknownError; } } } return results; }
public ConversionResolveResult(IType targetType, ResolveResult input, Conversion conversion) : base(targetType) { if (input == null) throw new ArgumentNullException("input"); this.Input = input; this.Conversion = conversion; }
public UnaryOperatorResolveResult(IType resultType, UnaryOperatorType op, ResolveResult input) : base(resultType) { if (input == null) throw new ArgumentNullException("input"); this.Operator = op; this.Input = input; }
public void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType) { if (!nodesWithConversions.Add(expression)) throw new InvalidOperationException("Duplicate ProcessConversion() call"); if (!conversion.IsValid && !allowErrors) { Console.WriteLine("Compiler error at " + fileName + ":" + expression.StartLocation + ": Cannot convert from " + result + " to " + targetType); } }
public void Resolved(AstNode node, ResolveResult resolveResult) { if (resolveResult.IsError) { foreach(var error in GetErrorStrings(resolveResult)) { _errors.Add(new ResolveErrors(node.StartLocation, error)); } } }
void TestCast(Type targetType, ResolveResult input, Conversion expectedConversion) { IType type = targetType.ToTypeReference().Resolve(context); ResolveResult rr = resolver.ResolveCast(type, input); AssertType(targetType, rr); Assert.AreEqual(typeof(ConversionResolveResult), rr.GetType()); var crr = (ConversionResolveResult)rr; Assert.AreEqual(expectedConversion, crr.Conversion, "ConversionResolveResult.Conversion"); Assert.AreSame(input, crr.Input, "ConversionResolveResult.Input"); }
void TestCast(Type targetType, ResolveResult input, Conversion expectedConversion) { IType type = compilation.FindType(targetType); ResolveResult rr = resolver.ResolveCast(type, input); AssertType(targetType, rr); Assert.AreEqual(typeof(ConversionResolveResult), rr.GetType()); var crr = (ConversionResolveResult)rr; Assert.AreEqual(expectedConversion, crr.Conversion, "ConversionResolveResult.Conversion"); Assert.AreSame(input, crr.Input, "ConversionResolveResult.Input"); }
static IMember GetMember (ResolveResult result) { if (result is MemberResolveResult) { return ((MemberResolveResult)result).Member; } else if (result is MethodGroupResolveResult) { return ((MethodGroupResolveResult)result).Methods.FirstOrDefault (); } return null; }
void TestOperator(ResolveResult condition, ResolveResult trueExpr, ResolveResult falseExpr, Conversion conditionConv, Conversion trueConv, Conversion falseConv, Type expectedResultType) { var corr = (ConditionalOperatorResolveResult)resolver.ResolveConditional(condition, trueExpr, falseExpr); AssertType(expectedResultType, corr); AssertConversion(corr.Condition, condition, conditionConv, "Condition Conversion"); AssertConversion(corr.True, trueExpr, trueConv, "True Conversion"); AssertConversion(corr.False, falseExpr, falseConv, "False Conversion"); }
public BinaryOperatorResolveResult(IType resultType, ResolveResult lhs, BinaryOperatorType op, ResolveResult rhs) : base(resultType) { if (lhs == null) throw new ArgumentNullException("lhs"); if (rhs == null) throw new ArgumentNullException("rhs"); this.Left = lhs; this.Operator = op; this.Right = rhs; }
public void Resolved(AstNode node, ResolveResult result) { if (!resolvedNodes.Add(node)) throw new InvalidOperationException("Duplicate Resolved() call"); if (CSharpAstResolver.IsUnresolvableNode(node)) throw new InvalidOperationException("Resolved unresolvable node"); if (result.IsError && !allowErrors) { Console.WriteLine("Compiler error at " + fileName + ":" + node.StartLocation + ": " + result); } }
public void ConversionFromDynamic() { // Explicit dynamic conversion is for resolve results only; // otherwise it's an explicit reference / unboxing conversion Assert.AreEqual(C.ExplicitReferenceConversion, ExplicitConversion(typeof(dynamic), typeof(string))); Assert.AreEqual(C.UnboxingConversion, ExplicitConversion(typeof(dynamic), typeof(int))); var dynamicRR = new ResolveResult(SpecialType.Dynamic); Assert.AreEqual(C.ExplicitDynamicConversion, conversions.ExplicitConversion(dynamicRR, compilation.FindType(typeof(string)))); Assert.AreEqual(C.ExplicitDynamicConversion, conversions.ExplicitConversion(dynamicRR, compilation.FindType(typeof(int)))); }
public override ResolveResult Resolve(CSharpResolver resolver) { ResolveResult[] elements = new ResolveResult[arrayElements.Count]; for (int i = 0; i < elements.Length; i++) { elements[i] = arrayElements[i].Resolve(resolver); } if (elementType != null) { return resolver.ResolveArrayCreation(elementType.Resolve(resolver.CurrentTypeResolveContext), 1, null, elements); } else { return resolver.ResolveArrayCreation(null, 1, null, elements); } }
public AwaitResolveResult(IType resultType, ResolveResult getAwaiterInvocation, IType awaiterType, IProperty isCompletedProperty, IMethod onCompletedMethod, IMethod getResultMethod) : base(resultType) { if (awaiterType == null) throw new ArgumentNullException("awaiterType"); if (getAwaiterInvocation == null) throw new ArgumentNullException("getAwaiterInvocation"); this.GetAwaiterInvocation = getAwaiterInvocation; this.AwaiterType = awaiterType; this.IsCompletedProperty = isCompletedProperty; this.OnCompletedMethod = onCompletedMethod; this.GetResultMethod = getResultMethod; }
protected static ISymbol GetSymbol(ResolveResult symbol) { TypeResolveResult trr = symbol as TypeResolveResult; if (trr != null) return trr.Type.GetDefinition(); MemberResolveResult mrr = symbol as MemberResolveResult; if (mrr != null) return mrr.Member.MemberDefinition; LocalResolveResult lrr = symbol as LocalResolveResult; if (lrr != null) return lrr.Variable; return null; }
public virtual void Write(TextWriter writer, ResolveResult result) { var error = result.BestMatch.Errors[0]; writer.WriteLine(error.Message); if (error.Parameter != null) { foreach (var parameter in error.Parameter) { this.WriteParameter(writer, result, parameter); } } }
public virtual void Resolved(AstNode node, ResolveResult result) { if (resolvedNodes.ContainsKey(node)) throw new InvalidOperationException("Duplicate Resolved() call"); resolvedNodes.Add(node, result); if (CSharpAstResolver.IsUnresolvableNode(node)) throw new InvalidOperationException("Resolved unresolvable node"); if (!ParenthesizedExpression.ActsAsParenthesizedExpression(node)) if (!resolveResults.Add(result) && result != ErrorResolveResult.UnknownError) throw new InvalidOperationException("Duplicate resolve result"); if (result.IsError && !allowErrors) { Console.WriteLine("Compiler error at " + fileName + ":" + node.StartLocation + ": " + result); } }
public ArgumentsInfo(IEmitter emitter, Expression expression, ResolveResult rr = null) { this.Emitter = emitter; this.Expression = expression; this.ArgumentsExpressions = new Expression[] { expression }; this.ArgumentsNames = new string[] { "{this}" }; this.ThisArgument = expression; this.CreateNamedExpressions(this.ArgumentsNames, this.ArgumentsExpressions); if (rr is MemberResolveResult) { this.BuildTypedArguments((MemberResolveResult)rr); } }
public LanguageItemWindow (ExtensibleTextEditor ed, Gdk.ModifierType modifierState, ResolveResult result, string errorInformations, IParsedFile unit) { Ambience ambience = AmbienceService.GetAmbience (ed.Document.MimeType); string tooltip = null; if (result is UnknownIdentifierResolveResult) { tooltip = string.Format ("error CS0103: The name `{0}' does not exist in the current context", ((UnknownIdentifierResolveResult)result).Identifier); } else if (result is UnknownMemberResolveResult) { var ur = (UnknownMemberResolveResult)result; if (ur.TargetType.Kind != TypeKind.Unknown) tooltip = string.Format ("error CS0117: `{0}' does not contain a definition for `{1}'", ur.TargetType.FullName, ur.MemberName); } else if (result != null && ed.TextEditorResolverProvider != null) { tooltip = ed.TextEditorResolverProvider.CreateTooltip (unit, result, errorInformations, ambience, modifierState); // TODO: Type sysetm conversion. (btw. this isn't required because the analyzer should provide semantic error messages.) // if (result.ResolveErrors.Count > 0) { // StringBuilder sb = new StringBuilder (); // sb.Append (tooltip); // sb.AppendLine (); // sb.AppendLine (); // sb.AppendLine (GettextCatalog.GetPluralString ("Error:", "Errors:", result.ResolveErrors.Count)); // for (int i = 0; i < result.ResolveErrors.Count; i++) { // sb.Append ('\t'); // sb.Append (result.ResolveErrors[i]); // if (i + 1 < result.ResolveErrors.Count) // sb.AppendLine (); // } // tooltip = sb.ToString (); // } } else { tooltip = errorInformations; } if (string.IsNullOrEmpty (tooltip)|| tooltip == "?") { IsEmpty = true; return; } var label = new MonoDevelop.Components.FixedWidthWrapLabel () { Wrap = Pango.WrapMode.WordChar, Indent = -20, BreakOnCamelCasing = true, BreakOnPunctuation = true, Markup = tooltip, }; this.BorderWidth = 3; Add (label); UpdateFont (label); EnableTransparencyControl = true; }
public CSharpInvocationResolveResult( ResolveResult targetResult, IParameterizedMember member, IList<ResolveResult> arguments, OverloadResolutionErrors overloadResolutionErrors = OverloadResolutionErrors.None, bool isExtensionMethodInvocation = false, bool isExpandedForm = false, bool isDelegateInvocation = false, IList<int> argumentToParameterMap = null) : base(targetResult, member, arguments) { this.OverloadResolutionErrors = overloadResolutionErrors; this.IsExtensionMethodInvocation = isExtensionMethodInvocation; this.IsExpandedForm = isExpandedForm; this.IsDelegateInvocation = isDelegateInvocation; this.argumentToParameterMap = argumentToParameterMap; }
public void Resolved(AstNode node, ResolveResult result) { if (ResolveVisitor.ActsAsParenthesizedExpression(node)) return; MemberResolveResult mrr = result as MemberResolveResult; if (mrr != null) { referenceFound(node, mrr.Member.MemberDefinition); } TypeResolveResult trr = result as TypeResolveResult; if (trr != null) { ITypeDefinition typeDef = trr.Type.GetDefinition(); if (typeDef != null) referenceFound(node, typeDef); } }
public void ResolveResult_throws_on_failures() { var expected = new ResolveFailure(Mock.Of<IResolveBuilder>(), "4242"); var result = new ResolveResult<Int32>() { Results = new[] { 42 }, ResolveFailures = new[] { expected } }; var exc = Assert.Throws<ResolveFailedException>(() => result.ToArray()); var rf = Assert.Single(exc.Failures); Assert.Same(expected, rf); }
public static bool ResolveAt (Document doc, out ResolveResult resolveResult, out AstNode node, CancellationToken token = default (CancellationToken)) { if (doc == null) throw new ArgumentNullException ("doc"); if (!InternalResolveAt (doc, out resolveResult, out node)) { var editor = doc.Editor; if (editor == null) return false; var location = RefactoringService.GetCorrectResolveLocation (doc, editor.Caret.Location); resolveResult = GetHeuristicResult (doc, location, ref node); if (resolveResult == null) return false; } var oce = node as ObjectCreateExpression; if (oce != null) node = oce.Type; return true; }
public CSharpInvocationResolveResult( ResolveResult targetResult, IParameterizedMember member, IList<ResolveResult> arguments, OverloadResolutionErrors overloadResolutionErrors = OverloadResolutionErrors.None, bool isExtensionMethodInvocation = false, bool isExpandedForm = false, bool isDelegateInvocation = false, IList<int> argumentToParameterMap = null, IList<ResolveResult> initializerStatements = null, IType returnTypeOverride = null, bool isConditionallyRemoved = false ) : base(targetResult, member, arguments, initializerStatements, returnTypeOverride, isConditionallyRemoved) { this.OverloadResolutionErrors = overloadResolutionErrors; this.IsExtensionMethodInvocation = isExtensionMethodInvocation; this.IsExpandedForm = isExpandedForm; this.IsDelegateInvocation = isDelegateInvocation; this.argumentToParameterMap = argumentToParameterMap; }
public static object GetItem (MonoDevelop.Ide.Gui.Document doc, out ResolveResult resolveResult) { resolveResult = GetResolveResult (doc); if (resolveResult is LocalResolveResult) return ((LocalResolveResult)resolveResult).Variable; if (resolveResult is MemberResolveResult) return ((MemberResolveResult)resolveResult).Member; if (resolveResult is MethodGroupResolveResult) { var mg = ((MethodGroupResolveResult)resolveResult); var method = mg.Methods.FirstOrDefault (); if (method == null && mg.GetExtensionMethods ().Any ()) method = mg.GetExtensionMethods ().First ().FirstOrDefault (); return method; } if (resolveResult is TypeResolveResult) return resolveResult.Type; if (resolveResult is NamespaceResolveResult) return ((NamespaceResolveResult)resolveResult).Namespace; return null; }
public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, Conversions conversions = null) { if (compilation == null) throw new ArgumentNullException("compilation"); if (arguments == null) throw new ArgumentNullException("arguments"); if (argumentNames == null) argumentNames = new string[arguments.Length]; else if (argumentNames.Length != arguments.Length) throw new ArgumentException("argumentsNames.Length must be equal to arguments.Length"); this.compilation = compilation; this.arguments = arguments; this.argumentNames = argumentNames; // keep explicitlyGivenTypeArguments==null when no type arguments were specified if (typeArguments != null && typeArguments.Length > 0) this.explicitlyGivenTypeArguments = typeArguments; this.conversions = conversions ?? Conversions.Get(compilation); this.AllowExpandingParams = true; }
public static bool ResolveAt (Document doc, out ResolveResult resolveResult, out AstNode node) { var parsedDocument = doc.ParsedDocument; resolveResult = null; node = null; if (parsedDocument == null) return false; var unit = parsedDocument.GetAst<CompilationUnit> (); var parsedFile = parsedDocument.ParsedFile as CSharpParsedFile; if (unit == null || parsedFile == null) return false; try { resolveResult = ResolveAtLocation.Resolve (doc.Compilation, parsedFile, unit, doc.Editor.Caret.Location, out node); if (resolveResult == null || node is Statement) return false; } catch (Exception e) { Console.WriteLine ("Got resolver exception:" + e); return false; } return true; }
static ResolveResult MapToNewContext(ResolveResult rr, ITypeResolveContext newContext) { if (rr is TypeOfResolveResult) { return new TypeOfResolveResult( rr.Type.ToTypeReference().Resolve(newContext), ((TypeOfResolveResult)rr).ReferencedType.ToTypeReference().Resolve(newContext)); } else if (rr is ArrayCreateResolveResult) { ArrayCreateResolveResult acrr = (ArrayCreateResolveResult)rr; return new ArrayCreateResolveResult( acrr.Type.ToTypeReference().Resolve(newContext), MapToNewContext(acrr.SizeArguments, newContext), MapToNewContext(acrr.InitializerElements, newContext)); } else if (rr.IsCompileTimeConstant) { return new ConstantResolveResult( rr.Type.ToTypeReference().Resolve(newContext), rr.ConstantValue ); } else { return new ErrorResolveResult(rr.Type.ToTypeReference().Resolve(newContext)); } }
private void HandleType(ResolveResult resolveOperator, string variable, string op_name, KnownTypeCode typeCode) { if (this.AssignmentExpression.Operator == AssignmentOperatorType.Assign) { if (variable != null) { this.Write(variable); } else { new ExpressionListBlock(this.Emitter, new Expression[] { this.AssignmentExpression.Right }, null, null, 0).Emit(); } return; } var orr = resolveOperator as OperatorResolveResult; var method = orr != null ? orr.UserDefinedOperatorMethod : null; var assigmentType = Helpers.TypeOfAssignment(this.AssignmentExpression.Operator); if (orr != null && method == null) { var name = Helpers.GetBinaryOperatorMethodName(assigmentType); var type = NullableType.IsNullable(orr.Type) ? NullableType.GetUnderlyingType(orr.Type) : orr.Type; method = type.GetMethods(m => m.Name == name, GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault(); } if (method != null) { var inline = this.Emitter.GetInline(method); if (orr.IsLiftedOperator) { this.Write(JS.Types.SYSTEM_NULLABLE + "."); string action = JS.Funcs.Math.LIFT2; this.Write(action); this.WriteOpenParentheses(); this.WriteScript(op_name); this.WriteComma(); if (variable != null) { new ExpressionListBlock(this.Emitter, new Expression[] { this.AssignmentExpression.Left }, null, null, 0).Emit(); } else { new ExpressionListBlock(this.Emitter, new Expression[] { this.AssignmentExpression.Left, this.AssignmentExpression.Right }, null, null, 0).Emit(); } this.AddOveflowFlag(typeCode, op_name); this.WriteCloseParentheses(); } else if (!string.IsNullOrWhiteSpace(inline)) { new InlineArgumentsBlock(this.Emitter, new ArgumentsInfo(this.Emitter, this.AssignmentExpression, orr, method), inline).Emit(); } else if (!this.Emitter.Validator.IsExternalType(method.DeclaringTypeDefinition)) { this.Write(BridgeTypes.ToJsName(method.DeclaringType, this.Emitter)); this.WriteDot(); this.Write(OverloadsCollection.Create(this.Emitter, method).GetOverloadName()); this.WriteOpenParentheses(); if (variable != null) { new ExpressionListBlock(this.Emitter, new Expression[] { this.AssignmentExpression.Left }, null, null, 0).Emit(); this.Write(", " + variable); } else { new ExpressionListBlock(this.Emitter, new Expression[] { this.AssignmentExpression.Left, this.AssignmentExpression.Right }, null, null, 0).Emit(); } this.WriteCloseParentheses(); } } else { if (orr.IsLiftedOperator) { this.Write(JS.Types.SYSTEM_NULLABLE + "."); string action = JS.Funcs.Math.LIFT2; this.Write(action); this.WriteOpenParentheses(); this.WriteScript(op_name); this.WriteComma(); if (variable != null) { new ExpressionListBlock(this.Emitter, new Expression[] { this.AssignmentExpression.Left }, null, null, 0).Emit(); } else { new ExpressionListBlock(this.Emitter, new Expression[] { this.AssignmentExpression.Left, this.AssignmentExpression.Right }, null, null, 0).Emit(); } this.AddOveflowFlag(typeCode, op_name); this.WriteCloseParentheses(); } else { this.AssignmentExpression.Left.AcceptVisitor(this.Emitter); this.WriteDot(); this.Write(op_name); this.WriteOpenParentheses(); this.AssignmentExpression.Right.AcceptVisitor(this.Emitter); this.AddOveflowFlag(typeCode, op_name); this.WriteCloseParentheses(); } } }
private void HandleLong(ResolveResult resolveOperator, string variable, bool isUnsigned) { var assigmentType = Helpers.TypeOfAssignment(this.AssignmentExpression.Operator); string op_name = null; if (this.AssignmentExpression.Operator != AssignmentOperatorType.Assign) { switch (assigmentType) { case BinaryOperatorType.GreaterThan: op_name = JS.Funcs.Math.GT; break; case BinaryOperatorType.GreaterThanOrEqual: op_name = JS.Funcs.Math.GTE; break; case BinaryOperatorType.Equality: op_name = JS.Funcs.Math.EQUALS; break; case BinaryOperatorType.InEquality: op_name = JS.Funcs.Math.NE; break; case BinaryOperatorType.LessThan: op_name = JS.Funcs.Math.LT; break; case BinaryOperatorType.LessThanOrEqual: op_name = JS.Funcs.Math.LTE; break; case BinaryOperatorType.Add: op_name = JS.Funcs.Math.ADD; break; case BinaryOperatorType.Subtract: op_name = JS.Funcs.Math.SUB; break; case BinaryOperatorType.Multiply: op_name = JS.Funcs.Math.MUL; break; case BinaryOperatorType.Divide: op_name = JS.Funcs.Math.DIV; break; case BinaryOperatorType.Modulus: op_name = JS.Funcs.Math.MOD; break; case BinaryOperatorType.BitwiseAnd: op_name = JS.Funcs.Math.AND; break; case BinaryOperatorType.BitwiseOr: op_name = JS.Funcs.Math.OR; break; case BinaryOperatorType.ExclusiveOr: op_name = JS.Funcs.Math.XOR; break; case BinaryOperatorType.ShiftLeft: op_name = JS.Funcs.Math.SHL; break; case BinaryOperatorType.ShiftRight: op_name = isUnsigned ? JS.Funcs.Math.SHRU : JS.Funcs.Math.SHR; break; default: throw new ArgumentOutOfRangeException(); } } this.HandleType(resolveOperator, variable, op_name, isUnsigned ? KnownTypeCode.UInt64 : KnownTypeCode.Int64); }
public static bool CanTransformToExtensionMethodCall(CSharpResolver resolver, IMethod method, IReadOnlyList <IType> typeArguments, ResolveResult target, ResolveResult[] arguments, string[] argumentNames) { if (target is LambdaResolveResult) { return(false); } var rr = resolver.ResolveMemberAccess(target, method.Name, typeArguments, NameLookupMode.InvocationTarget) as MethodGroupResolveResult; if (rr == null) { return(false); } var or = rr.PerformOverloadResolution(resolver.CurrentTypeResolveContext.Compilation, arguments, argumentNames, allowExtensionMethods: true); if (or == null || or.IsAmbiguous) { return(false); } return(method.Equals(or.GetBestCandidateWithSubstitutedTypeArguments()) && CSharpResolver.IsEligibleExtensionMethod(target.Type, method, useTypeInference: false, out _)); }
public override void VisitInvocationExpression(InvocationExpression invocationExpression) { base.VisitInvocationExpression(invocationExpression); var method = invocationExpression.GetSymbol() as IMethod; if (method == null || !method.IsExtensionMethod || !invocationExpression.Arguments.Any()) { return; } IReadOnlyList <IType> typeArguments; MemberReferenceExpression memberRefExpr; switch (invocationExpression.Target) { case MemberReferenceExpression mre: typeArguments = mre.TypeArguments.Any() ? method.TypeArguments : EmptyList <IType> .Instance; memberRefExpr = mre; break; case IdentifierExpression ide: typeArguments = ide.TypeArguments.Any() ? method.TypeArguments : EmptyList <IType> .Instance; memberRefExpr = null; break; default: return; } var firstArgument = invocationExpression.Arguments.First(); if (firstArgument is NamedArgumentExpression) { return; } var target = firstArgument.GetResolveResult(); if (target is ConstantResolveResult crr && crr.ConstantValue == null) { target = new ConversionResolveResult(method.Parameters[0].Type, crr, Conversion.NullLiteralConversion); } ResolveResult[] args = new ResolveResult[invocationExpression.Arguments.Count - 1]; string[] argNames = null; int pos = 0; foreach (var arg in invocationExpression.Arguments.Skip(1)) { if (arg is NamedArgumentExpression nae) { if (argNames == null) { argNames = new string[args.Length]; } argNames[pos] = nae.Name; args[pos] = nae.Expression.GetResolveResult(); } else { args[pos] = arg.GetResolveResult(); } pos++; } if (!CanTransformToExtensionMethodCall(resolver, method, typeArguments, target, args, argNames)) { return; } if (firstArgument is DirectionExpression dirExpr) { if (!context.Settings.RefExtensionMethods || dirExpr.FieldDirection == FieldDirection.Out) { return; } firstArgument = dirExpr.Expression; target = firstArgument.GetResolveResult(); dirExpr.Detach(); } else if (firstArgument is NullReferenceExpression) { Debug.Assert(context.RequiredNamespacesSuperset.Contains(method.Parameters[0].Type.Namespace)); firstArgument = firstArgument.ReplaceWith(expr => new CastExpression(context.TypeSystemAstBuilder.ConvertType(method.Parameters[0].Type), expr.Detach())); } if (invocationExpression.Target is IdentifierExpression identifierExpression) { identifierExpression.Detach(); memberRefExpr = new MemberReferenceExpression(firstArgument.Detach(), method.Name, identifierExpression.TypeArguments.Detach()); invocationExpression.Target = memberRefExpr; } else { memberRefExpr.Target = firstArgument.Detach(); } if (invocationExpression.GetResolveResult() is CSharpInvocationResolveResult irr) { // do not forget to update the CSharpInvocationResolveResult => set IsExtensionMethodInvocation == true invocationExpression.RemoveAnnotations <CSharpInvocationResolveResult>(); var newResolveResult = new CSharpInvocationResolveResult( irr.TargetResult, irr.Member, irr.Arguments, irr.OverloadResolutionErrors, isExtensionMethodInvocation: true, irr.IsExpandedForm, irr.IsDelegateInvocation, irr.GetArgumentToParameterMap(), irr.InitializerStatements); invocationExpression.AddAnnotation(newResolveResult); } }
public ExpressionResolveResult(ResolveResult item1, CSharpResolver item2, CSharpAstResolver item3) { this.Result = item1; this.Resolver = item2; this.AstResolver = item3; }
AstType ConvertTypeHelper(ITypeDefinition typeDef, IList<IType> typeArguments) { Debug.Assert(typeArguments.Count >= typeDef.TypeParameterCount); string keyword = KnownTypeReference.GetCSharpNameByTypeCode(typeDef.KnownTypeCode); if (keyword != null) return new PrimitiveType(keyword); // The number of type parameters belonging to outer classes int outerTypeParameterCount; if (typeDef.DeclaringType != null) outerTypeParameterCount = typeDef.DeclaringType.TypeParameterCount; else outerTypeParameterCount = 0; if (resolver != null) { // Look if there's an alias to the target type if (UseAliases) { for (ResolvedUsingScope usingScope = resolver.CurrentUsingScope; usingScope != null; usingScope = usingScope.Parent) { foreach (var pair in usingScope.UsingAliases) { if (pair.Value is TypeResolveResult) { if (TypeMatches(pair.Value.Type, typeDef, typeArguments)) return new SimpleType(pair.Key); } } } } IList<IType> localTypeArguments; if (typeDef.TypeParameterCount > outerTypeParameterCount) { localTypeArguments = new IType[typeDef.TypeParameterCount - outerTypeParameterCount]; for (int i = 0; i < localTypeArguments.Count; i++) { localTypeArguments[i] = typeArguments[outerTypeParameterCount + i]; } } else { localTypeArguments = EmptyList<IType>.Instance; } ResolveResult rr = resolver.ResolveSimpleName(typeDef.Name, localTypeArguments); TypeResolveResult trr = rr as TypeResolveResult; if (trr != null || (localTypeArguments.Count == 0 && resolver.IsVariableReferenceWithSameType(rr, typeDef.Name, out trr))) { if (!trr.IsError && TypeMatches(trr.Type, typeDef, typeArguments)) { // We can use the short type name SimpleType shortResult = new SimpleType(typeDef.Name); AddTypeArguments(shortResult, typeDef, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount); return shortResult; } } } if (AlwaysUseShortTypeNames) { var shortResult = new SimpleType(typeDef.Name); AddTypeArguments(shortResult, typeDef, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount); return shortResult; } MemberType result = new MemberType(); if (typeDef.DeclaringTypeDefinition != null) { // Handle nested types result.Target = ConvertTypeHelper(typeDef.DeclaringTypeDefinition, typeArguments); } else { // Handle top-level types if (string.IsNullOrEmpty(typeDef.Namespace)) { result.Target = new SimpleType("global"); result.IsDoubleColon = true; } else { result.Target = ConvertNamespace(typeDef.Namespace); } } result.MemberName = typeDef.Name; AddTypeArguments(result, typeDef, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount); return result; }