public void TestandoOConstrutor() { // Arrange var methodInfo = this.GetType().GetMethod("UmMetodoParaSerTestadoQueRecebeUmParametro_"); // Act var method = new MethodSpec(methodInfo); // Assert Assert.AreSame(methodInfo, method.MethodInfo); }
public void MethodPatternNameTeste() { // Arrange var methodInfo = this.GetType().GetMethod("UmMetodoParaSerTestadoQueRecebeUmParametro_"); // Act var method = new MethodSpec(methodInfo); // Assert Assert.AreEqual("Um Metodo Para Ser Testado Que Recebe Um Parametro(.*)", method.MethodPatternName); }
public void GetConvertAttributesTest() { // Arrange var methodInfo = this.GetType().GetMethod("UmMetodoParaSerTestadoQueRecebeUmParametro_"); // Act var method = new MethodSpec(methodInfo); // Assert Assert.AreEqual(0, method.ConvertAttributeCollection.Count); }
public void GetParametersTest() { // Arrange var methodInfo = this.GetType().GetMethod("UmMetodoParaSerTestadoQueRecebeUmParametro_"); // Act var method = new MethodSpec(methodInfo); // Assert Assert.AreEqual(1, method.ParameterCollection.Count); Assert.AreEqual(typeof(string), method.ParameterCollection[0].ParameterType); }
/// <summary> /// Estrai os parâmetros encontrados na string. /// </summary> /// <param name="str"></param> /// <param name="methodSpec"></param> /// <returns></returns> public static List<object> ExtractParameters(this string str, MethodSpec methodSpec) { var strParList = new List<string>(); var matches = Regex.Matches(str.RemoveAccents(), methodSpec.MethodPatternName.RemoveAccents(), RegexOptions.IgnoreCase); if (matches.Count > 0) { if (matches[0].Groups.Count > 1) { for (var i = 1; i < matches[0].Groups.Count; i++) { var substring = str.Substring(matches[0].Groups[i].Index, matches[0].Groups[i].Value.Length); strParList.Add(substring.Trim()); } } var customConvert = methodSpec.ConvertAttributeCollection.ToList().Select(t => t.ConvertClass).ToList(); return strParList.Select((t, i) => Parameter.Create(t, methodSpec.ParameterCollection[i]).TryConvert(customConvert)).ToList(); } return new List<object>(); ; }
public void Emit(OpCode opcode, MethodSpec method, MetaType[] vargs) { // TODO MemberCache: This should mutate too ig.EmitCall(opcode, (MethodInfo)method.GetMetaInfo(), vargs); }
Expression LiftResult(ResolveContext ec, Expression res_expr) { TypeExpr lifted_type; // // Avoid double conversion // if (left_unwrap == null || IsLeftNullLifted || left_unwrap.Type != left.Type || (left_unwrap != null && IsRightNullLifted)) { lifted_type = new NullableType(left.Type, loc); lifted_type = lifted_type.ResolveAsTypeTerminal(ec, false); if (lifted_type == null) { return(null); } if (left is UserCast || left is TypeCast) { left.Type = lifted_type.Type; } else { left = EmptyCast.Create(left, lifted_type.Type); } } if (left != right && (right_unwrap == null || IsRightNullLifted || right_unwrap.Type != right.Type || (right_unwrap != null && IsLeftNullLifted))) { lifted_type = new NullableType(right.Type, loc); lifted_type = lifted_type.ResolveAsTypeTerminal(ec, false); if (lifted_type == null) { return(null); } var r = right; if (r is ReducedExpression) { r = ((ReducedExpression)r).OriginalExpression; } if (r is UserCast || r is TypeCast) { r.Type = lifted_type.Type; } else { right = EmptyCast.Create(right, lifted_type.Type); } } if ((Oper & Operator.ComparisonMask) == 0) { lifted_type = new NullableType(res_expr.Type, loc); lifted_type = lifted_type.ResolveAsTypeTerminal(ec, false); if (lifted_type == null) { return(null); } wrap_ctor = NullableInfo.GetConstructor(lifted_type.Type); type = res_expr.Type = lifted_type.Type; } if (IsLeftNullLifted) { left = LiftedNull.Create(right.Type, left.Location); // // Special case for bool?, the result depends on both null right side and left side value // if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType(type).BuiltinType == BuiltinTypeSpec.Type.Bool) { return(res_expr); } if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0) { return(LiftedNull.CreateFromExpression(ec, res_expr)); } // // Value types and null comparison // if (right_unwrap == null || (Oper & Operator.RelationalMask) != 0) { return(CreateNullConstant(ec, right_orig)); } } if (IsRightNullLifted) { right = LiftedNull.Create(left.Type, right.Location); // // Special case for bool?, the result depends on both null right side and left side value // if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType(type).BuiltinType == BuiltinTypeSpec.Type.Bool) { return(res_expr); } if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0) { return(LiftedNull.CreateFromExpression(ec, res_expr)); } // // Value types and null comparison // if (left_unwrap == null || (Oper & Operator.RelationalMask) != 0) { return(CreateNullConstant(ec, left_orig)); } } return(res_expr); }
public RequestMsg_IWebMessageSystem_UpdateMailboxMessagePublication(TypeSpec contract, MethodSpec method, bool oneWay, Guid?instance) : base(contract, method, oneWay, instance) { }
/// <summary> /// Verifies that any pending abstract methods or interface methods /// were implemented. /// </summary> public bool VerifyPendingMethods(Report Report) { int top = pending_implementations.Length; bool errors = false; int i; for (i = 0; i < top; i++) { TypeSpec type = pending_implementations [i].type; bool base_implements_type = type.IsInterface && container.BaseType != null && container.BaseType.ImplementsInterface(type, false); for (int j = 0; j < pending_implementations [i].methods.Count; ++j) { var mi = pending_implementations[i].methods[j]; if (mi == null) { continue; } if (type.IsInterface) { var need_proxy = pending_implementations [i].need_proxy [j]; if (need_proxy != null) { DefineProxy(type, need_proxy, mi); continue; } if (pending_implementations [i].optional) { continue; } MethodSpec candidate = null; if (base_implements_type || BaseImplements(type, mi, out candidate)) { continue; } if (candidate == null) { MethodData md = pending_implementations [i].found [j]; if (md != null) { candidate = md.method.Spec; } } Report.SymbolRelatedToPreviousError(mi); if (candidate != null) { Report.SymbolRelatedToPreviousError(candidate); if (candidate.IsStatic) { Report.Error(736, container.Location, "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' is static", container.GetSignatureForError(), mi.GetSignatureForError(), TypeManager.CSharpSignature(candidate)); } else if ((candidate.Modifiers & Modifiers.PUBLIC) == 0) { Report.Error(737, container.Location, "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' in not public", container.GetSignatureForError(), mi.GetSignatureForError(), candidate.GetSignatureForError()); } else { Report.Error(738, container.Location, "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' return type `{3}' does not match interface member return type `{4}'", container.GetSignatureForError(), mi.GetSignatureForError(), TypeManager.CSharpSignature(candidate), TypeManager.CSharpName(candidate.ReturnType), TypeManager.CSharpName(mi.ReturnType)); } } else { Report.Error(535, container.Location, "`{0}' does not implement interface member `{1}'", container.GetSignatureForError(), mi.GetSignatureForError()); } } else { Report.SymbolRelatedToPreviousError(mi); Report.Error(534, container.Location, "`{0}' does not implement inherited abstract member `{1}'", container.GetSignatureForError(), mi.GetSignatureForError()); } errors = true; } } return(errors); }
/// <remarks> /// If a method in Type `t' (or null to look in all interfaces /// and the base abstract class) with name `Name', return type `ret_type' and /// arguments `args' implements an interface, this method will /// return the MethodInfo that this method implements. /// /// If `name' is null, we operate solely on the method's signature. This is for /// instance used when implementing indexers. /// /// The `Operation op' controls whether to lookup, clear the pending bit, or clear /// all the methods with the given signature. /// /// The `MethodInfo need_proxy' is used when we're implementing an interface's /// indexer in a class. If the new indexer's IndexerName does not match the one /// that was used in the interface, then we always need to create a proxy for it. /// /// </remarks> public MethodSpec InterfaceMethod(MemberName name, TypeSpec iType, MethodData method, Operation op, out MethodSpec ambiguousCandidate) { ambiguousCandidate = null; if (pending_implementations == null) { return(null); } TypeSpec ret_type = method.method.ReturnType; ParametersCompiled args = method.method.ParameterInfo; bool is_indexer = method.method is Indexer.SetIndexerMethod || method.method is Indexer.GetIndexerMethod; MethodSpec m; foreach (TypeAndMethods tm in pending_implementations) { if (!(iType == null || tm.type == iType)) { continue; } int method_count = tm.methods.Count; for (int i = 0; i < method_count; i++) { m = tm.methods [i]; if (m == null) { continue; } if (is_indexer) { if (!m.IsAccessor || m.Parameters.IsEmpty) { continue; } } else { if (name.Name != m.Name) { continue; } if (m.Arity != name.Arity) { continue; } } if (!TypeSpecComparer.Override.IsEqual(m.Parameters, args)) { continue; } if (!TypeSpecComparer.Override.IsEqual(m.ReturnType, ret_type)) { tm.found[i] = method; continue; } // // `need_proxy' is not null when we're implementing an // interface indexer and this is Clear(One/All) operation. // // If `name' is null, then we do a match solely based on the // signature and not on the name (this is done in the Lookup // for an interface indexer). // if (op != Operation.Lookup) { if (m.IsAccessor != method.method.IsAccessor) { continue; } // If `t != null', then this is an explicitly interface // implementation and we can always clear the method. // `need_proxy' is not null if we're implementing an // interface indexer. In this case, we need to create // a proxy if the implementation's IndexerName doesn't // match the IndexerName in the interface. if (m.DeclaringType.IsInterface && iType == null && name.Name != m.Name) // TODO: This is very expensive comparison { tm.need_proxy[i] = method.method.Spec; } else { tm.methods[i] = null; } } else { tm.found [i] = method; } if (op == Operation.Lookup && name.Left != null && ambiguousCandidate == null) { ambiguousCandidate = m; continue; } // // Lookups and ClearOne return // if (op != Operation.ClearAll) { return(m); } } // If a specific type was requested, we can stop now. if (tm.type == iType) { break; } } m = ambiguousCandidate; ambiguousCandidate = null; return(m); }
protected override bool DoDefineMembers() { PredefinedType builder_type; PredefinedMember <MethodSpec> bf; PredefinedMember <MethodSpec> bs; PredefinedMember <MethodSpec> sr; PredefinedMember <MethodSpec> se; PredefinedMember <MethodSpec> sm; bool has_task_return_type = false; var pred_members = Module.PredefinedMembers; if (return_type.Kind == MemberKind.Void) { builder_type = Module.PredefinedTypes.AsyncVoidMethodBuilder; bf = pred_members.AsyncVoidMethodBuilderCreate; bs = pred_members.AsyncVoidMethodBuilderStart; sr = pred_members.AsyncVoidMethodBuilderSetResult; se = pred_members.AsyncVoidMethodBuilderSetException; sm = pred_members.AsyncVoidMethodBuilderSetStateMachine; } else if (return_type == Module.PredefinedTypes.Task.TypeSpec) { builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilder; bf = pred_members.AsyncTaskMethodBuilderCreate; bs = pred_members.AsyncTaskMethodBuilderStart; sr = pred_members.AsyncTaskMethodBuilderSetResult; se = pred_members.AsyncTaskMethodBuilderSetException; sm = pred_members.AsyncTaskMethodBuilderSetStateMachine; task = pred_members.AsyncTaskMethodBuilderTask.Get(); } else { builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilderGeneric; bf = pred_members.AsyncTaskMethodBuilderGenericCreate; bs = pred_members.AsyncTaskMethodBuilderGenericStart; sr = pred_members.AsyncTaskMethodBuilderGenericSetResult; se = pred_members.AsyncTaskMethodBuilderGenericSetException; sm = pred_members.AsyncTaskMethodBuilderGenericSetStateMachine; task = pred_members.AsyncTaskMethodBuilderGenericTask.Get(); has_task_return_type = true; } set_result = sr.Get(); set_exception = se.Get(); builder_factory = bf.Get(); builder_start = bs.Get(); var istate_machine = Module.PredefinedTypes.IAsyncStateMachine; var set_statemachine = sm.Get(); if (!builder_type.Define() || !istate_machine.Define() || set_result == null || builder_factory == null || set_exception == null || set_statemachine == null || builder_start == null || !Module.PredefinedTypes.INotifyCompletion.Define()) { Report.Error(1993, Location, "Cannot find compiler required types for asynchronous functions support. Are you targeting the wrong framework version?"); return(base.DoDefineMembers()); } var bt = builder_type.TypeSpec; // // Inflate generic Task types // if (has_task_return_type) { var task_return_type = return_type.TypeArguments; if (mutator != null) { task_return_type = mutator.Mutate(task_return_type); } bt = bt.MakeGenericType(Module, task_return_type); set_result = MemberCache.GetMember(bt, set_result); set_exception = MemberCache.GetMember(bt, set_exception); set_statemachine = MemberCache.GetMember(bt, set_statemachine); if (task != null) { task = MemberCache.GetMember(bt, task); } } builder = AddCompilerGeneratedField("$builder", new TypeExpression(bt, Location)); var set_state_machine = new Method(this, new TypeExpression(Compiler.BuiltinTypes.Void, Location), Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PUBLIC, new MemberName("SetStateMachine"), ParametersCompiled.CreateFullyResolved( new Parameter(new TypeExpression(istate_machine.TypeSpec, Location), "stateMachine", Parameter.Modifier.NONE, null, Location), istate_machine.TypeSpec), null); ToplevelBlock block = new ToplevelBlock(Compiler, set_state_machine.ParameterInfo, Location); block.IsCompilerGenerated = true; set_state_machine.Block = block; Members.Add(set_state_machine); if (!base.DoDefineMembers()) { return(false); } // // Fabricates SetStateMachine method // // public void SetStateMachine (IAsyncStateMachine stateMachine) // { // $builder.SetStateMachine (stateMachine); // } // var mg = MethodGroupExpr.CreatePredefined(set_statemachine, bt, Location); mg.InstanceExpression = new FieldExpr(builder, Location); var param_reference = block.GetParameterReference(0, Location); param_reference.Type = istate_machine.TypeSpec; param_reference.eclass = ExprClass.Variable; var args = new Arguments(1); args.Add(new Argument(param_reference)); set_state_machine.Block.AddStatement(new StatementExpression(new Invocation(mg, args))); if (has_task_return_type) { HoistedReturnValue = TemporaryVariableReference.Create(bt.TypeArguments [0], StateMachineMethod.Block, Location); } return(true); }
public MethodSpecOptions(MethodSpec ms) { this.Method = ms.Method; this.Instantiation = ms.Instantiation; this.CustomAttributes.AddRange(ms.CustomAttributes); }
/// <inheritdoc/> protected override uint AddMethodSpec(MethodSpec ms) { if (ms == null) { Error("MethodSpec is null"); return 0; } uint rid; if (methodSpecInfos.TryGetRid(ms, out rid)) return rid; var row = new RawMethodSpecRow(AddMethodDefOrRef(ms.Method), GetSignature(ms.Instantiation)); rid = tablesHeap.MethodSpecTable.Add(row); methodSpecInfos.Add(ms, rid); AddCustomAttributes(Table.MethodSpec, rid, ms); return rid; }
/// <inheritdoc/> public override uint GetRid(MethodSpec ms) { uint rid; methodSpecInfos.TryGetRid(ms, out rid); return rid; }
public void AddAssemblyAttribute(MethodSpec ctor, byte[] data) { assembly.SetCustomAttribute(ctor, data); }
Expression LiftResult (ResolveContext ec, Expression res_expr) { TypeExpr lifted_type; // // Avoid double conversion // if (left_unwrap == null || left_null_lifted || !TypeManager.IsEqual (left_unwrap.Type, left.Type) || (left_unwrap != null && right_null_lifted)) { lifted_type = new NullableType (left.Type, loc); lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false); if (lifted_type == null) return null; if (left is UserCast || left is TypeCast) left.Type = lifted_type.Type; else left = EmptyCast.Create (left, lifted_type.Type); } if (left != right && (right_unwrap == null || right_null_lifted || !TypeManager.IsEqual (right_unwrap.Type, right.Type) || (right_unwrap != null && left_null_lifted))) { lifted_type = new NullableType (right.Type, loc); lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false); if (lifted_type == null) return null; if (right is UserCast || right is TypeCast) right.Type = lifted_type.Type; else right = EmptyCast.Create (right, lifted_type.Type); } if ((Oper & Operator.ComparisonMask) == 0) { lifted_type = new NullableType (res_expr.Type, loc); lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false); if (lifted_type == null) return null; wrap_ctor = NullableInfo.GetConstructor (lifted_type.Type); type = res_expr.Type = lifted_type.Type; } if (left_null_lifted) { left = LiftedNull.Create (right.Type, left.Location); if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0) return LiftedNull.CreateFromExpression (ec, res_expr); // // Value types and null comparison // if (right_unwrap == null || (Oper & Operator.RelationalMask) != 0) return CreateNullConstant (ec, right_orig).Resolve (ec); } if (right_null_lifted) { right = LiftedNull.Create (left.Type, right.Location); if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0) return LiftedNull.CreateFromExpression (ec, res_expr); // // Value types and null comparison // if (left_unwrap == null || (Oper & Operator.RelationalMask) != 0) return CreateNullConstant (ec, left_orig); } return res_expr; }
public override bool Resolve(BlockContext bc) { if (bc.CurrentBlock is Linq.QueryBlock) { bc.Report.Error(1995, loc, "The `await' operator may only be used in a query expression within the first collection expression of the initial `from' clause or within the collection expression of a `join' clause"); return(false); } if (!base.Resolve(bc)) { return(false); } Arguments args = new Arguments(0); type = expr.Type; // // The await expression is of dynamic type // if (type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { result_type = type; expr = new Invocation(new MemberAccess(expr, "GetAwaiter"), args).Resolve(bc); return(true); } // // Check whether the expression is awaitable // Expression ama = new AwaitableMemberAccess(expr).Resolve(bc); if (ama == null) { return(false); } var errors_printer = new SessionReportPrinter(); var old = bc.Report.SetPrinter(errors_printer); ama = new Invocation(ama, args).Resolve(bc); bc.Report.SetPrinter(old); if (errors_printer.ErrorsCount > 0 || !MemberAccess.IsValidDotExpression(ama.Type)) { bc.Report.Error(1986, expr.Location, "The `await' operand type `{0}' must have suitable GetAwaiter method", expr.Type.GetSignatureForError()); return(false); } var awaiter_type = ama.Type; expr = ama; // // Predefined: bool IsCompleted { get; } // is_completed = MemberCache.FindMember(awaiter_type, MemberFilter.Property("IsCompleted", bc.Module.Compiler.BuiltinTypes.Bool), BindingRestriction.InstanceOnly) as PropertySpec; if (is_completed == null || !is_completed.HasGet) { Error_WrongAwaiterPattern(bc, awaiter_type); return(false); } // // Predefined: GetResult () // // The method return type is also result type of await expression // get_result = MemberCache.FindMember(awaiter_type, MemberFilter.Method("GetResult", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.InstanceOnly) as MethodSpec; if (get_result == null) { Error_WrongAwaiterPattern(bc, awaiter_type); return(false); } // // Predefined: INotifyCompletion.OnCompleted (System.Action) // var nc = bc.Module.PredefinedTypes.INotifyCompletion; if (nc.Define() && !awaiter_type.ImplementsInterface(nc.TypeSpec, false)) { bc.Report.Error(4027, loc, "The awaiter type `{0}' must implement interface `{1}'", awaiter_type.GetSignatureForError(), nc.GetSignatureForError()); return(false); } result_type = get_result.ReturnType; return(true); }
private MethodInfo ResolveMethod(Cci.IMethodReference methodRef) { var methodDef = (Cci.IMethodDefinition)methodRef.AsDefinition(_context); // A method ref to a varargs method is always resolved as an entry in the method // ref table, never in the method def table, *even if the method is locally declared.* // (We could in theory resolve it as a method def if there were no extra arguments, // but in practice we do not.) if (methodDef != null && IsLocal(methodRef.GetContainingType(_context)) && !methodRef.AcceptsExtraArguments) { return _methodBuilders[methodDef]; } MethodBase methodBase; if (_methodRefs.TryGetValue(methodRef, out methodBase)) { return (MethodInfo)methodBase; } MethodInfo result; Cci.ISpecializedMethodReference specializedRef = methodRef.AsSpecializedMethodReference; Cci.IGenericMethodInstanceReference genericRef = methodRef.AsGenericMethodInstanceReference; if (specializedRef != null && IsLocal(specializedRef.UnspecializedVersion.GetContainingType(_context))) { // get declaring type (TypeBuilder or TypeBuilderInstantiation since it's defined in the module being built): Type type = ResolveType(specializedRef.GetContainingType(_context)); MethodBuilder methodBuilder = _methodBuilders[(Cci.IMethodDefinition)specializedRef.UnspecializedVersion.AsDefinition(_context)]; MethodInfo methodOnTypeBuilder = TypeBuilder.GetMethod(type, methodBuilder); if (genericRef != null) { Type[] typeArgs = genericRef.GetGenericArguments(_context).Select(arg => ResolveType(arg)).ToArray(); result = methodOnTypeBuilder.MakeGenericMethod(typeArgs); } else { result = methodOnTypeBuilder; } } else if (genericRef != null) { MethodInfo genericMethod = ResolveMethod(genericRef.GetGenericMethod(_context)); Type[] typeArgs = genericRef.GetGenericArguments(_context).Select((arg) => ResolveType(arg)).ToArray(); if (genericMethod is MethodRef) { result = new MethodSpec(genericMethod, typeArgs); } else { result = genericMethod.MakeGenericMethod(typeArgs); } } else { result = MakeMethodRef(methodRef, specializedRef, isConstructor: false); } _methodRefs.Add(methodRef, result); return result; }
public static string FullDelegateDesc(MethodSpec invoke_method) { return(TypeManager.GetFullNameSignature(invoke_method).Replace(".Invoke", "")); }
public MosaMethod LoadGenericMethodInstance(MethodSpec methodSpec, GenericArgumentResolver resolver) { return(LoadGenericMethodInstance(methodSpec.Method, methodSpec.GenericInstMethodSig.GenericArguments, resolver)); }
public bool NoExactMatch(ResolveContext ec, MethodSpec method) { var pd = method.Parameters; TypeSpec source_type = pd.ExtensionMethodType; if (source_type != null) { Argument a = arguments [0]; if (TypeManager.IsGenericType (source_type) && TypeManager.ContainsGenericParameters (source_type)) { TypeInferenceContext tic = new TypeInferenceContext (source_type.TypeArguments); tic.OutputTypeInference (ec, a.Expr, source_type); if (tic.FixAllTypes (ec)) { source_type = source_type.GetDefinition ().MakeGenericType (tic.InferredTypeArguments); } } if (!Convert.ImplicitConversionExists (ec, a.Expr, source_type)) { ec.Report.Error (1936, loc, "An implementation of `{0}' query expression pattern for source type `{1}' could not be found", mg.Name, TypeManager.CSharpName (a.Type)); return true; } } if (!method.IsGeneric) return false; if (mg.Name == "SelectMany") { ec.Report.Error (1943, loc, "An expression type is incorrect in a subsequent `from' clause in a query expression with source type `{0}'", arguments [0].GetSignatureForError ()); } else { ec.Report.Error (1942, loc, "An expression type in `{0}' clause is incorrect. Type inference failed in the call to `{1}'", mg.Name.ToLower (), mg.Name); } return true; }
public MyCallResult(Block block, int callEndIndex, int methodId, MethodSpec gim) : base(block, callEndIndex) { this.methodId = methodId; this.gim = gim; }
/// <summary> /// This function tells whether one of our base classes implements /// the given method (which turns out, it is valid to have an interface /// implementation in a base /// </summary> bool BaseImplements(TypeSpec iface_type, MethodSpec mi, out MethodSpec base_method) { base_method = null; var base_type = container.BaseType; // // Setup filter with no return type to give better error message // about mismatch at return type when the check bellow rejects them // var parameters = mi.Parameters; while (true) { var candidates = MemberCache.FindMembers(base_type, mi.Name, false); if (candidates == null) { return(false); } MethodSpec similar_candidate = null; foreach (var candidate in candidates) { if (candidate.Kind != MemberKind.Method) { continue; } if (candidate.Arity != mi.Arity) { continue; } var candidate_param = ((MethodSpec)candidate).Parameters; if (!TypeSpecComparer.Override.IsSame(parameters.Types, candidate_param.Types)) { continue; } bool modifiers_match = true; for (int i = 0; i < parameters.Count; ++i) { // // First check exact ref/out match // const Parameter.Modifier ref_out = Parameter.Modifier.REF | Parameter.Modifier.OUT; if ((parameters.FixedParameters[i].ModFlags & ref_out) == (candidate_param.FixedParameters[i].ModFlags & ref_out)) { continue; } modifiers_match = false; // // Different in ref/out only // if ((parameters.FixedParameters[i].ModFlags & candidate_param.FixedParameters[i].ModFlags & Parameter.Modifier.ISBYREF) != 0) { if (similar_candidate == null) { if (!candidate.IsPublic) { break; } if (!TypeSpecComparer.Override.IsEqual(mi.ReturnType, ((MethodSpec)candidate).ReturnType)) { break; } // It's used for ref/out ambiguity overload check similar_candidate = (MethodSpec)candidate; } continue; } similar_candidate = null; break; } if (!modifiers_match) { continue; } // // From this point on the candidate is used for detailed error reporting // because it's very close match to what we are looking for // base_method = (MethodSpec)candidate; if (!candidate.IsPublic) { return(false); } if (!TypeSpecComparer.Override.IsEqual(mi.ReturnType, base_method.ReturnType)) { return(false); } } if (base_method != null) { if (similar_candidate != null) { Report.SymbolRelatedToPreviousError(similar_candidate); Report.SymbolRelatedToPreviousError(mi); Report.SymbolRelatedToPreviousError(container); Report.Warning(1956, 1, ((MemberCore)base_method.MemberDefinition).Location, "The interface method `{0}' implementation is ambiguous between following methods: `{1}' and `{2}' in type `{3}'", mi.GetSignatureForError(), base_method.GetSignatureForError(), similar_candidate.GetSignatureForError(), container.GetSignatureForError()); } break; } base_type = candidates[0].DeclaringType.BaseType; if (base_type == null) { return(false); } } if (!base_method.IsVirtual) { #if STATIC var base_builder = base_method.GetMetaInfo() as MethodBuilder; if (base_builder != null) { // // We can avoid creating a proxy if base_method can be marked 'final virtual'. This can // be done for all methods from compiled assembly // base_builder.__SetAttributes(base_builder.Attributes | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.NewSlot); return(true); } #endif DefineProxy(iface_type, base_method, mi); } return(true); }
public void Emit(EmitContext ec, MethodSpec method, Arguments Arguments, Location loc) { EmitPredefined(ec, method, Arguments, loc); }
public void SetCustomAttribute(MethodSpec ctor, byte[] data) { FieldBuilder.SetCustomAttribute((ConstructorInfo)ctor.GetMetaInfo(), data); }
public Expression TryInline(ResolveContext rc) { if (!(Expr is Invocation)) { return(Expr); } invocation = (Expr as Invocation); if (invocation.MethodGroup.BestCandidate == null) { return(Expr); } methodSpec = invocation.MethodGroup.BestCandidate; if (!(methodSpec.MemberDefinition is MethodCore)) { return(Expr); } method = methodSpec.MemberDefinition as MemberCore; methodData = method as IMethodData; if (methodData.IsInlinable) { return(Expr); } TypeSpec returnType = methodData.ReturnType; ToplevelBlock block = methodData.Block; if (block.Parameters.Count > 0 || block.TopBlock.NamesCount > 0 && block.TopBlock.LabelsCount > 0) { return(Expr); } if (returnType != rc.BuiltinTypes.Void && block.Statements.Count == 1 && block.Statements [0] is Return) { inlineExpr = ((Return)block.Statements [0]).Expr.Clone(new CloneContext()); } else if (returnType == rc.BuiltinTypes.Void) { Block newBlock = new Block(rc.CurrentBlock, block.StartLocation, block.EndLocation); foreach (var st in block.Statements) { newBlock.AddStatement(st.Clone(new CloneContext())); } // inlineExpr = newBlock; } this.rc = rc; this.inlineFailed = false; Expression ret; inlineExpr.Accept(this); ret = inlineExpr; if (inlineFailed) { return(Expr); } return(ret); }
public Tabels(PEFile p) { //Init this.r = p.MetadataReader; //Read all of the tabels ModuleTabel = new List <Module>(); TypeRefTabel = new List <TypeRef>(); TypeDefTabel = new List <TypeDef>(); FieldTabel = new List <Field>(); MethodTabel = new List <Method>(); ParmTabel = new List <Param>(); InterfaceImplTable = new List <InterfaceImpl>(); MemberRefTabelRow = new List <MemberRef>(); ConstantTabel = new List <Constant>(); CustomAttributeTabel = new List <CustomAttribute>(); FieldMarshalTabel = new List <FieldMarshal>(); DeclSecurityTabel = new List <DeclSecurity>(); ClassLayoutTabel = new List <ClassLayout>(); FieldLayoutTabel = new List <FieldLayout>(); StandAloneSigTabel = new List <StandAloneSig>(); EventMapTabel = new List <EventMap>(); EventTabel = new List <Event>(); PropertyMapTabel = new List <PropertyMap>(); PropertyTabel = new List <PropertyTabel>(); MethodSemanticsTabel = new List <MethodSemantics>(); MethodImplTabel = new List <MethodImpl>(); ModuleRefTabel = new List <ModuleRef>(); TypeSpecTabel = new List <TypeSpec>(); ImplMapTabel = new List <ImplMap>(); FieldRVATabel = new List <FieldRVA>(); AssemblyTabel = new List <Assembly>(); AssemblyRefTabel = new List <AssemblyRef>(); FileTable = new List <File>(); ExportedTypeTable = new List <ExportedType>(); ManifestResourceTable = new List <ManifestResource>(); NestedClassTable = new List <NestedClass>(); GenericParamTable = new List <GenericParam>(); MethodSpecTable = new List <MethodSpec>(); int a = 0; //Read module Tabel (if any) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.Module) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new Module(); m.Read(r); ModuleTabel.Add(m); } a++; } //Read TypeRef Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.TypeRef) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new TypeRef(); m.Read(r); TypeRefTabel.Add(m); } a++; } //Read TypeDef Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.TypeDef) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new TypeDef(); m.Read(r); TypeDefTabel.Add(m); } a++; } //Read Field Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.Field) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new Field(); m.Read(r); FieldTabel.Add(m); } a++; } //Read Method tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.Method) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new Method(); m.Read(r); MethodTabel.Add(m); } a++; } //Read Parm Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.Param) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new Param(); m.Read(r); ParmTabel.Add(m); } a++; } //Read interfaceimpl Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.InterfaceImpl) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new InterfaceImpl(); m.Read(r); InterfaceImplTable.Add(m); } a++; } //Read MemberRef tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.MemberRef) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new MemberRef(); m.Read(r); MemberRefTabelRow.Add(m); } a++; } //Read Constant tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.Constant) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new Constant(); m.Read(r); ConstantTabel.Add(m); } a++; } //Read CustomAttribute tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.CustomAttribute) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new CustomAttribute(); m.Read(r); CustomAttributeTabel.Add(m); } a++; } //Read FieldMarshal tabel (Please test) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.FieldMarshal) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new FieldMarshal(); m.Read(r); FieldMarshalTabel.Add(m); } a++; } //Read DeclSecurity tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.DeclSecurity) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new DeclSecurity(); m.Read(r); DeclSecurityTabel.Add(m); } a++; } //Read ClassLayout tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.ClassLayout) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new ClassLayout(); m.Read(r); ClassLayoutTabel.Add(m); } a++; } //Read FieldLayout tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.FieldLayout) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new FieldLayout(); m.Read(r); FieldLayoutTabel.Add(m); } a++; } //Read StandAloneSig tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.StandAloneSig) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new StandAloneSig(); m.Read(r); StandAloneSigTabel.Add(m); } a++; } //Read EventMap tabel (please test) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.EventMap) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new EventMap(); m.Read(r); EventMapTabel.Add(m); } a++; } //Read event tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.Event) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new Event(); m.Read(r); EventTabel.Add(m); } a++; } //Read Property Map tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.PropertyMap) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new PropertyMap(); m.Read(r); PropertyMapTabel.Add(m); } a++; } //Read Property tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.Property) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new PropertyTabel(); m.Read(r); PropertyTabel.Add(m); } a++; } //Read MethodSemantics tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.MethodSemantics) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new MethodSemantics(); m.Read(r); MethodSemanticsTabel.Add(m); } a++; } //Read MethodImpl tabel (Please test) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.MethodImpl) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new MethodImpl(); m.Read(r); MethodImplTabel.Add(m); } a++; } //Read ModuleRef tabel (pls test) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.ModuleRef) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new ModuleRef(); m.Read(r); ModuleRefTabel.Add(m); } a++; } //Read TypeSpec tabel (pls test) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.TypeSpec) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new TypeSpec(); m.Read(r); TypeSpecTabel.Add(m); } a++; } //Read ImplMap tabel (pls test) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.ImplMap) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new ImplMap(); m.Read(r); ImplMapTabel.Add(m); } a++; } //Read FieldRVA tabel (pls test) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.FieldRVA) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new FieldRVA(); m.Read(r); FieldRVATabel.Add(m); } a++; } //Read Assembly tabel (pls test) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.Assembly) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new Assembly(); m.Read(r); AssemblyTabel.Add(m); } a++; } //Read ignored tabels (These never should be present!) if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.AssemblyProcessor) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var proc = r.ReadUInt32(); } a++; } if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.AssemblyOS) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { r.BaseStream.Position += 11; //Test please } a++; } //Read AssemblyRef Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.AssemblyRef) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new AssemblyRef(); m.Read(r); AssemblyRefTabel.Add(m); } a++; } //Read AssemblyRefProcessor Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.AssemblyRefProcessor) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { r.BaseStream.Position += 8; //Test please } a++; } //Read AssemblyRefOS Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.AssemblyRefOS) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { r.BaseStream.Position += 16; //Test please } a++; } //Read File Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.File) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new File(); m.Read(r); FileTable.Add(m); } a++; } //Read ExportedType Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.ExportedType) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new ExportedType(); m.Read(r); ExportedTypeTable.Add(m); } a++; } //Read ManifestResource Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.ManifestResource) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new ManifestResource(); m.Read(r); ManifestResourceTable.Add(m); } a++; } //Read NestedClass Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.NestedClass) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new NestedClass(); m.Read(r); NestedClassTable.Add(m); } a++; } //Read GenericParam Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.GenericParam) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new GenericParam(); m.Read(r); GenericParamTable.Add(m); } a++; } //Read MethodSpec Tabel if ((p.ClrMetaDataStreamHeader.TablesFlags & MetadataTableFlags.MethodSpec) != 0) { for (int i = 0; i < p.ClrMetaDataStreamHeader.TableSizes[a]; i++) { var m = new MethodSpec(); m.Read(r); MethodSpecTable.Add(m); } a++; } }
public RequestMsg_ITestContractB_GetNameMar(TypeSpec contract, MethodSpec method, bool oneWay, Guid?instance) : base(contract, method, oneWay, instance) { }
public void EmitPredefined(EmitContext ec, MethodSpec method, Arguments Arguments, Location?loc = null) { Expression instance_copy = null; if (!HasAwaitArguments && ec.HasSet(BuilderContext.Options.AsyncBody)) { HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait(); if (HasAwaitArguments && InstanceExpressionOnStack) { throw new NotSupportedException(); } } OpCode call_op; LocalTemporary lt = null; if (method.IsStatic) { call_op = OpCodes.Call; } else { if (IsVirtualCallRequired(InstanceExpression, method)) { call_op = OpCodes.Callvirt; } else { call_op = OpCodes.Call; } if (HasAwaitArguments) { instance_copy = InstanceExpression.EmitToField(ec); if (Arguments == null) { EmitCallInstance(ec, instance_copy, method.DeclaringType, call_op); } } else if (!InstanceExpressionOnStack) { var instance_on_stack_type = EmitCallInstance(ec, InstanceExpression, method.DeclaringType, call_op); if (DuplicateArguments) { ec.Emit(OpCodes.Dup); if (Arguments != null && Arguments.Count != 0) { lt = new LocalTemporary(instance_on_stack_type); lt.Store(ec); instance_copy = lt; } } } } if (Arguments != null && !InstanceExpressionOnStack) { EmittedArguments = Arguments.Emit(ec, DuplicateArguments, HasAwaitArguments); if (EmittedArguments != null) { if (instance_copy != null) { EmitCallInstance(ec, instance_copy, method.DeclaringType, call_op); if (lt != null) { lt.Release(ec); } } EmittedArguments.Emit(ec); } } if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStruct)) { ec.Emit(OpCodes.Constrained, InstanceExpression.Type); } if (loc != null) { // // Emit explicit sequence point for expressions like Foo.Bar () to help debugger to // break at right place when LHS expression can be stepped-into // ec.MarkCallEntry(loc.Value); } // // Set instance expression to actual result expression. When it contains await it can be // picked up by caller // InstanceExpression = instance_copy; if (method.Parameters.HasArglist) { var varargs_types = GetVarargsTypes(method, Arguments); ec.Emit(call_op, method, varargs_types); return; } // // If you have: // this.DoFoo (); // and DoFoo is not virtual, you can omit the callvirt, // because you don't need the null checking behavior. // ec.Emit(call_op, method); }
public RequestMsg_IJokeContract_SimpleWorkMar(TypeSpec contract, MethodSpec method, bool oneWay, Guid?instance) : base(contract, method, oneWay, instance) { }
public RequestMsg_ILogReceiver_SendLog(TypeSpec contract, MethodSpec method, bool oneWay, Guid?instance) : base(contract, method, oneWay, instance) { }
public RequestMsg_IZoneHostReplicator_PostDynamicHostInfo(TypeSpec contract, MethodSpec method, bool oneWay, Guid?instance) : base(contract, method, oneWay, instance) { }
public void ApplyAttributeBuilder(Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { if (a.IsValidSecurityAttribute()) { a.ExtractSecurityPermissionSet(ctor, ref declarative_security); return; } if (a.Type == pa.AssemblyCulture) { string value = a.GetString(); if (value == null || value.Length == 0) { return; } if (Compiler.Settings.Target == Target.Exe) { a.Error_AttributeEmitError("The executables cannot be satelite assemblies, remove the attribute or keep it empty"); return; } if (value == "neutral") { value = ""; } if (Compiler.Settings.Target == Target.Module) { SetCustomAttribute(ctor, cdata); } else { builder_extra.SetCulture(value, a.Location); } return; } if (a.Type == pa.AssemblyVersion) { string value = a.GetString(); if (value == null || value.Length == 0) { return; } var vinfo = IsValidAssemblyVersion(value, true); if (vinfo == null) { a.Error_AttributeEmitError(string.Format("Specified version `{0}' is not valid", value)); return; } if (Compiler.Settings.Target == Target.Module) { SetCustomAttribute(ctor, cdata); } else { builder_extra.SetVersion(vinfo, a.Location); } return; } if (a.Type == pa.AssemblyAlgorithmId) { const int pos = 2; // skip CA header uint alg = (uint)cdata [pos]; alg |= ((uint)cdata [pos + 1]) << 8; alg |= ((uint)cdata [pos + 2]) << 16; alg |= ((uint)cdata [pos + 3]) << 24; if (Compiler.Settings.Target == Target.Module) { SetCustomAttribute(ctor, cdata); } else { builder_extra.SetAlgorithmId(alg, a.Location); } return; } if (a.Type == pa.AssemblyFlags) { const int pos = 2; // skip CA header uint flags = (uint)cdata[pos]; flags |= ((uint)cdata [pos + 1]) << 8; flags |= ((uint)cdata [pos + 2]) << 16; flags |= ((uint)cdata [pos + 3]) << 24; // Ignore set PublicKey flag if assembly is not strongnamed if ((flags & (uint)AssemblyNameFlags.PublicKey) != 0 && public_key == null) { flags &= ~(uint)AssemblyNameFlags.PublicKey; } if (Compiler.Settings.Target == Target.Module) { SetCustomAttribute(ctor, cdata); } else { builder_extra.SetFlags(flags, a.Location); } return; } if (a.Type == pa.TypeForwarder) { TypeSpec t = a.GetArgumentType(); if (t == null || TypeManager.HasElementType(t)) { Report.Error(735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute"); return; } if (emitted_forwarders == null) { emitted_forwarders = new Dictionary <ITypeDefinition, Attribute> (); } else if (emitted_forwarders.ContainsKey(t.MemberDefinition)) { Report.SymbolRelatedToPreviousError(emitted_forwarders[t.MemberDefinition].Location, null); Report.Error(739, a.Location, "A duplicate type forward of type `{0}'", TypeManager.CSharpName(t)); return; } emitted_forwarders.Add(t.MemberDefinition, a); if (t.MemberDefinition.DeclaringAssembly == this) { Report.SymbolRelatedToPreviousError(t); Report.Error(729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly", TypeManager.CSharpName(t)); return; } if (t.IsNested) { Report.Error(730, a.Location, "Cannot forward type `{0}' because it is a nested type", TypeManager.CSharpName(t)); return; } builder_extra.AddTypeForwarder(t.GetDefinition(), a.Location); return; } if (a.Type == pa.Extension) { a.Error_MisusedExtensionAttribute(); return; } if (a.Type == pa.InternalsVisibleTo) { string assembly_name = a.GetString(); if (assembly_name.Length == 0) { return; } #if STATIC ParsedAssemblyName aname; ParseAssemblyResult r = Fusion.ParseAssemblyName(assembly_name, out aname); if (r != ParseAssemblyResult.OK) { Report.Warning(1700, 3, a.Location, "Assembly reference `{0}' is invalid and cannot be resolved", assembly_name); return; } if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) { Report.Error(1725, a.Location, "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified", assembly_name); return; } if (public_key != null && !aname.HasPublicKey) { Report.Error(1726, a.Location, "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations", assembly_name); return; } #endif } else if (a.Type == pa.RuntimeCompatibility) { wrap_non_exception_throws_custom = true; } else if (a.Type == pa.AssemblyFileVersion) { string value = a.GetString(); if (string.IsNullOrEmpty(value) || IsValidAssemblyVersion(value, false) == null) { Report.Warning(1607, 1, a.Location, "The version number `{0}' specified for `{1}' is invalid", value, a.Name); return; } } SetCustomAttribute(ctor, cdata); }
public static void Write(this ITextOutput writer, MethodSig sig, IMethod method = null) { if (sig == null && method != null) { sig = method.MethodSig; } if (sig == null) { return; } if (sig.ExplicitThis) { writer.Write("instance", TextTokenType.Keyword); writer.WriteSpace(); writer.Write("explicit", TextTokenType.Keyword); writer.WriteSpace(); } else if (sig.HasThis) { writer.Write("instance", TextTokenType.Keyword); writer.WriteSpace(); } sig.RetType.WriteTo(writer, ILNameSyntax.SignatureNoNamedTypeParameters); writer.WriteSpace(); if (method != null) { if (method.DeclaringType != null) { method.DeclaringType.WriteTo(writer, ILNameSyntax.TypeName); writer.Write("::", TextTokenType.Operator); } MethodDef md = method as MethodDef; if (md != null && md.IsCompilerControlled) { writer.WriteReference(Escape(method.Name + "$PST" + method.MDToken.ToInt32().ToString("X8")), method, TextTokenHelper.GetTextTokenType(method)); } else { writer.WriteReference(Escape(method.Name), method, TextTokenHelper.GetTextTokenType(method)); } } MethodSpec gim = method as MethodSpec; if (gim != null && gim.GenericInstMethodSig != null) { writer.Write('<', TextTokenType.Operator); for (int i = 0; i < gim.GenericInstMethodSig.GenericArguments.Count; i++) { if (i > 0) { writer.Write(',', TextTokenType.Operator); writer.WriteSpace(); } gim.GenericInstMethodSig.GenericArguments[i].WriteTo(writer); } writer.Write('>', TextTokenType.Operator); } writer.Write("(", TextTokenType.Operator); var parameters = sig.GetParameters(); for (int i = 0; i < parameters.Count; ++i) { if (i > 0) { writer.Write(',', TextTokenType.Operator); writer.WriteSpace(); } parameters[i].WriteTo(writer, ILNameSyntax.SignatureNoNamedTypeParameters); } writer.Write(")", TextTokenType.Operator); }
public void EmitInitializer(EmitContext ec) { // // Some predefined types are missing // if (builder == null) { return; } var instance = (TemporaryVariableReference)Instance; var builder_field = builder.Spec; if (MemberName.Arity > 0) { builder_field = MemberCache.GetMember(instance.Type, builder_field); } // // Inflated factory method when task is of generic type // if (builder_factory.DeclaringType.IsGeneric) { var task_return_type = return_type.TypeArguments; var bt = builder_factory.DeclaringType.MakeGenericType(Module, task_return_type); builder_factory = MemberCache.GetMember(bt, builder_factory); builder_start = MemberCache.GetMember(bt, builder_start); } // // stateMachine.$builder = AsyncTaskMethodBuilder<{task-type}>.Create(); // instance.AddressOf(ec, AddressOp.Store); ec.Emit(OpCodes.Call, builder_factory); ec.Emit(OpCodes.Stfld, builder_field); // // stateMachine.$builder.Start<{storey-type}>(ref stateMachine); // instance.AddressOf(ec, AddressOp.Store); ec.Emit(OpCodes.Ldflda, builder_field); if (Task != null) { ec.Emit(OpCodes.Dup); } instance.AddressOf(ec, AddressOp.Store); ec.Emit(OpCodes.Call, builder_start.MakeGenericMethod(Module, instance.Type)); // // Emits return stateMachine.$builder.Task; // if (Task != null) { var task_get = Task.Get; if (MemberName.Arity > 0) { task_get = MemberCache.GetMember(builder_field.MemberType, task_get); } var pe_task = new PropertyExpr(Task, Location) { InstanceExpression = EmptyExpression.Null, // Comes from the dup above Getter = task_get }; pe_task.Emit(ec); } }
// // Factory method: if there are pending implementation methods, we return a PendingImplementation // object, otherwise we return null. // // Register method implementations are either abstract methods // flagged as such on the base class or interface methods // static public PendingImplementation GetPendingImplementations(TypeContainer container) { TypeSpec b = container.BaseType; var missing_interfaces = GetMissingInterfaces(container); // // If we are implementing an abstract class, and we are not // ourselves abstract, and there are abstract methods (C# allows // abstract classes that have no abstract methods), then allocate // one slot. // // We also pre-compute the methods. // bool implementing_abstract = ((b != null) && b.IsAbstract && (container.ModFlags & Modifiers.ABSTRACT) == 0); MethodSpec[] abstract_methods = null; if (implementing_abstract) { var am = MemberCache.GetNotImplementedAbstractMethods(b); if (am == null) { implementing_abstract = false; } else { abstract_methods = new MethodSpec[am.Count]; am.CopyTo(abstract_methods, 0); } } int total = missing_interfaces.Length + (implementing_abstract ? 1 : 0); if (total == 0) { return(null); } var pending = new PendingImplementation(container, missing_interfaces, abstract_methods, total); // // check for inherited conflicting methods // foreach (var p in pending.pending_implementations) { // // It can happen for generic interfaces only // if (!p.type.IsGeneric) { continue; } // // CLR does not distinguishes between ref and out // for (int i = 0; i < p.methods.Count; ++i) { MethodSpec compared_method = p.methods[i]; if (compared_method.Parameters.IsEmpty) { continue; } for (int ii = i + 1; ii < p.methods.Count; ++ii) { MethodSpec tested_method = p.methods[ii]; if (compared_method.Name != tested_method.Name) { continue; } if (p.type != tested_method.DeclaringType) { continue; } if (!TypeSpecComparer.Override.IsSame(compared_method.Parameters.Types, tested_method.Parameters.Types)) { continue; } bool exact_match = true; bool ref_only_difference = false; var cp = compared_method.Parameters.FixedParameters; var tp = tested_method.Parameters.FixedParameters; for (int pi = 0; pi < cp.Length; ++pi) { // // First check exact modifiers match // const Parameter.Modifier ref_out = Parameter.Modifier.REF | Parameter.Modifier.OUT; if ((cp[pi].ModFlags & ref_out) == (tp[pi].ModFlags & ref_out)) { continue; } if ((cp[pi].ModFlags & tp[pi].ModFlags & Parameter.Modifier.ISBYREF) != 0) { ref_only_difference = true; continue; } exact_match = false; break; } if (!exact_match || !ref_only_difference) { continue; } pending.Report.SymbolRelatedToPreviousError(compared_method); pending.Report.SymbolRelatedToPreviousError(tested_method); pending.Report.Error(767, container.Location, "Cannot implement interface `{0}' with the specified type parameters because it causes method `{1}' to differ on parameter modifiers only", p.type.GetDefinition().GetSignatureForError(), compared_method.GetSignatureForError()); break; } } } return(pending); }
public static TypeSpec CreateDelegateTypeFromMethodSpec(ResolveContext rc, MethodSpec ms, Location loc) { return(CreateDelegateType(rc, ms.Parameters, ms.ReturnType, loc)); }
/// <summary> /// Whether the specified method is an interface method implementation /// </summary> public MethodSpec IsInterfaceMethod(MemberName name, TypeSpec ifaceType, MethodData method, out MethodSpec ambiguousCandidate) { return(InterfaceMethod(name, ifaceType, method, Operation.Lookup, out ambiguousCandidate)); }
protected override Expression DoResolve(ResolveContext ec) { constructor_method = Delegate.GetConstructor(type); var invoke_method = Delegate.GetInvokeMethod(type); Arguments arguments = CreateDelegateMethodArguments(ec, invoke_method.Parameters, invoke_method.Parameters.Types, loc); method_group = method_group.OverloadResolve(ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate); if (method_group == null) { return(null); } var delegate_method = method_group.BestCandidate; if (delegate_method.DeclaringType.IsNullableType) { ec.Report.Error(1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type", delegate_method.GetSignatureForError()); return(null); } if (!AllowSpecialMethodsInvocation) { Invocation.IsSpecialMethodInvocation(ec, delegate_method, loc); } ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr; if (emg != null) { method_group.InstanceExpression = emg.ExtensionExpression; TypeSpec e_type = emg.ExtensionExpression.Type; if (TypeSpec.IsValueType(e_type)) { ec.Report.Error(1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates", delegate_method.GetSignatureForError(), e_type.GetSignatureForError()); } } TypeSpec rt = delegate_method.ReturnType; if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { rt = ec.BuiltinTypes.Object; } if (!Delegate.IsTypeCovariant(ec, rt, invoke_method.ReturnType)) { Expression ret_expr = new TypeExpression(delegate_method.ReturnType, loc); Error_ConversionFailed(ec, delegate_method, ret_expr); } if (delegate_method.IsConditionallyExcluded(ec, loc)) { ec.Report.SymbolRelatedToPreviousError(delegate_method); MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator; if (m != null && m.IsPartialDefinition) { ec.Report.Error(762, loc, "Cannot create delegate from partial method declaration `{0}'", delegate_method.GetSignatureForError()); } else { ec.Report.Error(1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature(delegate_method)); } } var expr = method_group.InstanceExpression; if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType(expr.Type))) { method_group.InstanceExpression = new BoxedCast(expr, ec.BuiltinTypes.Object); } eclass = ExprClass.Value; return(this); }
public void ImplementMethod(MemberName name, TypeSpec ifaceType, MethodData method, bool clear_one, out MethodSpec ambiguousCandidate) { InterfaceMethod(name, ifaceType, method, clear_one ? Operation.ClearOne : Operation.ClearAll, out ambiguousCandidate); }
Expression LiftResult (ResolveContext ec, Expression res_expr) { TypeExpr lifted_type; // // Avoid double conversion // if (left_unwrap == null || IsLeftNullLifted || left_unwrap.Type != left.Type || (left_unwrap != null && IsRightNullLifted)) { lifted_type = new NullableType (left.Type, loc); lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false); if (lifted_type == null) return null; if (left is UserCast || left is TypeCast) left.Type = lifted_type.Type; else left = EmptyCast.Create (left, lifted_type.Type); } if (left != right && (right_unwrap == null || IsRightNullLifted || right_unwrap.Type != right.Type || (right_unwrap != null && IsLeftNullLifted))) { lifted_type = new NullableType (right.Type, loc); lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false); if (lifted_type == null) return null; var r = right; if (r is ReducedExpression) r = ((ReducedExpression) r).OriginalExpression; if (r is UserCast || r is TypeCast) r.Type = lifted_type.Type; else right = EmptyCast.Create (right, lifted_type.Type); } if ((Oper & Operator.ComparisonMask) == 0) { lifted_type = new NullableType (res_expr.Type, loc); lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false); if (lifted_type == null) return null; wrap_ctor = NullableInfo.GetConstructor (lifted_type.Type); type = res_expr.Type = lifted_type.Type; } if (IsLeftNullLifted) { left = LiftedNull.Create (right.Type, left.Location); // // Special case for bool?, the result depends on both null right side and left side value // if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType (type).BuiltinType == BuiltinTypeSpec.Type.Bool) { return res_expr; } if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0) return LiftedNull.CreateFromExpression (ec, res_expr); // // Value types and null comparison // if (right_unwrap == null || (Oper & Operator.RelationalMask) != 0) return CreateNullConstant (ec, right_orig); } if (IsRightNullLifted) { right = LiftedNull.Create (left.Type, right.Location); // // Special case for bool?, the result depends on both null right side and left side value // if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType (type).BuiltinType == BuiltinTypeSpec.Type.Bool) { return res_expr; } if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0) return LiftedNull.CreateFromExpression (ec, res_expr); // // Value types and null comparison // if (left_unwrap == null || (Oper & Operator.RelationalMask) != 0) return CreateNullConstant (ec, left_orig); } return res_expr; }
public bool AmbiguousCall(ResolveContext ec, MethodSpec ambiguous) { ec.Report.SymbolRelatedToPreviousError (mg.BestCandidate); ec.Report.SymbolRelatedToPreviousError (ambiguous); ec.Report.Error (1940, loc, "Ambiguous implementation of the query pattern `{0}' for source type `{1}'", mg.Name, mg.InstanceExpression.GetSignatureForError ()); return true; }