public MethodInvocation(IReference reference, IType type, IMethod method, ISubstitution substitution)
 {
   Reference = reference;
   Type = type;
   Method = method;
   Substitution = substitution;
 }
示例#2
0
        /// <summary>
        /// </summary>
        /// <param name="llvmWriter">
        /// </param>
        /// <param name="objectResult">
        /// </param>
        /// <param name="methodResult">
        /// </param>
        /// <param name="invokeMethod">
        /// </param>
        /// <param name="isStatic">
        /// </param>
        /// <returns>
        /// </returns>
        public static FullyDefinedReference WriteCallInvokeMethod(
            this LlvmWriter llvmWriter, FullyDefinedReference objectResult, FullyDefinedReference methodResult, IMethod invokeMethod, bool isStatic)
        {
            var writer = llvmWriter.Output;

            var method = new SynthesizedInvokeMethod(llvmWriter, objectResult, methodResult, invokeMethod, isStatic);
            var opCodeNope = OpCodePart.CreateNop;

            opCodeNope.OpCodeOperands =
                Enumerable.Range(0, invokeMethod.GetParameters().Count()).Select(p => new OpCodeInt32Part(OpCodesEmit.Ldarg, 0, 0, p + 1)).ToArray();

            foreach (var generatedOperand in opCodeNope.OpCodeOperands)
            {
                llvmWriter.ActualWrite(writer, generatedOperand);
            }

            writer.WriteLine(string.Empty);

            // bitcast object to method
            var opCodeNopeForBitCast = OpCodePart.CreateNop;
            opCodeNopeForBitCast.OpCodeOperands = new[] { OpCodePart.CreateNop };
            opCodeNopeForBitCast.OpCodeOperands[0].Result = methodResult;
            llvmWriter.UnaryOper(writer, opCodeNopeForBitCast, "bitcast", methodResult.Type, options: LlvmWriter.OperandOptions.GenerateResult);
            writer.Write(" to ");
            llvmWriter.WriteMethodPointerType(writer, method);
            writer.WriteLine(string.Empty);

            method.MethodResult = opCodeNopeForBitCast.Result;

            // actual call
            llvmWriter.WriteCall(opCodeNope, method, false, !isStatic, false, objectResult, llvmWriter.tryScopes.Count > 0 ? llvmWriter.tryScopes.Peek() : null);
            writer.WriteLine(string.Empty);

            return opCodeNope.Result;
        }
 protected override CallResult createCallResult(IMethod method, MethodSpec gim, Block block, int callInstrIndex)
 {
     int methodId;
     if (!methodTokenToId.TryGetValue(method.MDToken.ToInt32(), out methodId))
         return null;
     return new MyCallResult(block, callInstrIndex, methodId, gim);
 }
        public StringFormatWriter(ModuleDeclaration module)
        {
            this.module = module;
            ITypeSignature stringType = module.Cache.GetType(typeof(string));

            this.format1Method = module.FindMethod(stringType, "Format",
                method => method.Parameters.Count == 2 &&
                          IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String) &&
                          IntrinsicTypeSignature.Is(method.Parameters[1].ParameterType, IntrinsicType.Object));

            this.format2Method = module.FindMethod(stringType, "Format",
                method => method.Parameters.Count == 3 &&
                          IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String) &&
                          IntrinsicTypeSignature.Is(method.Parameters[1].ParameterType, IntrinsicType.Object) &&
                          IntrinsicTypeSignature.Is(method.Parameters[2].ParameterType, IntrinsicType.Object));

            this.format3Method = module.FindMethod(stringType, "Format",
                method => method.Parameters.Count == 4 &&
                          IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String) &&
                          IntrinsicTypeSignature.Is(method.Parameters[1].ParameterType, IntrinsicType.Object) &&
                          IntrinsicTypeSignature.Is(method.Parameters[2].ParameterType, IntrinsicType.Object) &&
                          IntrinsicTypeSignature.Is(method.Parameters[3].ParameterType, IntrinsicType.Object));

            this.formatArrayMethod = module.FindMethod(stringType, "Format",
                method => method.Parameters.Count == 2 &&
                          IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String) &&
                          method.Parameters[1].ParameterType.BelongsToClassification(TypeClassifications.Array));
        }
		protected override void InitializeMemberCache()
		{
			base.InitializeMemberCache();
			getParam = TypeSystemServices.Map(typeof(BrailBase).GetMethod("GetParameter"));
			tryGetParam = TypeSystemServices.Map(typeof(BrailBase).GetMethod("TryGetParameter"));
			wrapNullValue = TypeSystemServices.Map(typeof(BrailBase).GetMethod("WrapPossilbeNullValue"));
		}
        internal CodeTypeMemberCollection GenerateParameterProperty(IParameter parameter,
            IMethod method,
            CodeTypeDeclaration resourceClass,
            IEnumerable<string> usedNames)
        {
            // Get the name and return type of this parameter.
            string name = parameter.Name;
            CodeTypeReference returnType = ResourceBaseGenerator.GetParameterTypeReference(
                resourceClass, parameter);

            // Generate the property and field.
            CodeTypeMemberCollection newMembers = DecoratorUtil.CreateAutoProperty(
                name, parameter.Description, returnType, usedNames, parameter.IsRequired);

            // Add the KeyAttribute to the property.
            foreach (CodeTypeMember member in newMembers)
            {
                CodeMemberProperty property = member as CodeMemberProperty;
                if (property == null)
                {
                    continue;
                }

                // Declare the RequestParameter attribute.
                CodeTypeReference attributeType = new CodeTypeReference(typeof(RequestParameterAttribute));
                CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(attributeType);
                attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(parameter.Name)));
                property.CustomAttributes.Add(attribute);
            }

            return newMembers;
        }
示例#7
0
		public MemberNode(IMethod method)
		{
			InitMemberNode(method);
			sortOrder = 10;
			Text = AppendReturnType(GetAmbience().Convert(method), method.ReturnType);
			SelectedImageIndex = ImageIndex = ClassBrowserIconService.GetIcon(method).ImageIndex;
		}
 public override void Dispose()
 {
     _asyncResultType = null;
     _asyncResultTypeAsyncDelegateGetter = null;
     _adaptors.Clear();
     base.Dispose();
 }
示例#9
0
		public override void OnMethod(Method node)
		{
			var old = _currentMethod;
			_currentMethod = (IMethod) node.Entity;
			base.OnMethod(node);
			_currentMethod = old;
		}
		public IEnumerable<OpenedFile> GetSourceFiles(out OpenedFile designerCodeFile)
		{
			// get new initialize components
			ParseInformation info = ParserService.ParseFile(this.viewContent.PrimaryFileName, this.viewContent.PrimaryFileContent);
			ICompilationUnit cu = info.CompilationUnit;
			foreach (IClass c in cu.Classes) {
				if (FormsDesignerSecondaryDisplayBinding.BaseClassIsFormOrControl(c)) {
					this.currentClassPart = c;
					this.initializeComponents = FormsDesignerSecondaryDisplayBinding.GetInitializeComponents(c);
					if (this.initializeComponents != null) {
						string designerFileName = this.initializeComponents.DeclaringType.CompilationUnit.FileName;
						if (designerFileName != null) {
							
							designerCodeFile = FileService.GetOrCreateOpenedFile(designerFileName);
							
							CompoundClass compound = c.GetCompoundClass() as CompoundClass;
							if (compound == null) {
								return new [] {designerCodeFile};
							} else {
								return compound.Parts
									.Select(cl => FileService.GetOrCreateOpenedFile(cl.CompilationUnit.FileName))
									.Distinct();
							}
							
						}
					}
				}
			}
			
			throw new FormsDesignerLoadException("Could not find InitializeComponent method in any part of the open class.");
		}
		public OverrideEqualsGetHashCodeMethodsDialog(InsertionContext context, ITextEditor editor, ITextAnchor endAnchor,
		                                              ITextAnchor insertionPosition, ITypeDefinition selectedClass, IMethod selectedMethod, AstNode baseCallNode)
			: base(context, editor, insertionPosition)
		{
			if (selectedClass == null)
				throw new ArgumentNullException("selectedClass");
			
			InitializeComponent();
			
			this.selectedClass = selectedClass;
			this.insertionEndAnchor = endAnchor;
			this.selectedMethod = selectedMethod;
			this.baseCallNode = baseCallNode;
			
			addIEquatable.Content = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddInterface}"),
			                                      "IEquatable<" + selectedClass.Name + ">");
			
			string otherMethod = selectedMethod.Name == "Equals" ? "GetHashCode" : "Equals";
			
			addOtherMethod.Content = StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddOtherMethod}", new StringTagPair("otherMethod", otherMethod));
			
			addIEquatable.IsEnabled = !selectedClass.GetAllBaseTypes().Any(
				type => {
					if (!type.IsParameterized || (type.TypeParameterCount != 1))
						return false;
					if (type.FullName != "System.IEquatable")
						return false;
					return type.TypeArguments.First().FullName == selectedClass.FullName;
				}
			);
		}
示例#12
0
 public DefaultTypeParameter(IMethod method, string name, int index)
 {
     this.method = method;
     this.targetClass = method.DeclaringType;
     this.name = name;
     this.index = index;
 }
示例#13
0
 public DefaultTypeParameter(IMethod method, Type type)
 {
     this.method = method;
     this.targetClass = method.DeclaringType;
     this.name = type.Name;
     this.index = type.GenericParameterPosition;
 }
		/// <summary>
		/// Copy constructor
		/// </summary>
		protected DefaultMethod(IMethod method) : base(method)
		{
			returnTypeAttributes = CopyList(method.ReturnTypeAttributes);
			typeParameters = CopyList(method.TypeParameters);
			parameters = CopyList(method.Parameters);
			this.IsExtensionMethod = method.IsExtensionMethod;
		}
        public virtual int CompareTo(IMethod value)
        {
            int cmp;

            cmp = base.CompareTo((IDecoration)value);

            if (cmp != 0) {
                return cmp;
            }

            if (FullyQualifiedName != null) {
                cmp = FullyQualifiedName.CompareTo(value.FullyQualifiedName);
                if (cmp != 0) {
                    return cmp;
                }
            }

            if (ReturnType != null) {
                cmp = ReturnType.CompareTo(value.ReturnType);
                if (cmp != 0) {
                    return cmp;
                }
            }

            if (Region != null) {
                cmp = Region.CompareTo(value.Region);
                if (cmp != 0) {
                    return cmp;
                }
            }

            return DiffUtility.Compare(Parameters, value.Parameters);
        }
		public IMethodDefOrRef Convert(IMethod methodRef) {
			if (!(methodRef is MemberRef || methodRef is MethodDef) || methodRef.MethodSig == null)
				throw new ApplicationException("Invalid method reference type");
			if (IsInOurModule(methodRef))
				return (IMethodDefOrRef)TryGetMethodDef(methodRef);
			return (IMethodDefOrRef)CreateImporter().Import(methodRef);
		}
		public DelegateDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IType delegateType)
		{
			this.startOffset = startOffset;
//			this.ext = ext;
			this.delegateType = delegateType;
			this.delegateMethod = delegateType.GetDelegateInvokeMethod ();
		}
示例#18
0
		public DelegateDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IType delegateType) : base (ext, startOffset)
		{
			compilation = ext.UnresolvedFileCompilation;
			file = ext.CSharpUnresolvedFile;
			//			this.delegateType = delegateType;
			this.delegateMethod = delegateType.GetDelegateInvokeMethod ();
		}
 public void Reset(IMethod method, ITypeInfo typeInfo)
 {
     this.method = method;
     var containingType = method.GetContainingType();
     TypeName = containingType.GetClrName().FullName;
     Class = typeInfo ?? ((IClass) containingType).AsTypeInfo();
 }
示例#20
0
 public MethodDrop(ITable table, IMethod method)
     : base(method)
 {
     this.table = table;
     this.method = method;
     tableMemberDrop = new TableMemberDrop(table, method);
 }
示例#21
0
		public static ILSpyUnresolvedFile GetSymbols(IMethod method)
		{
			var typeName = DecompiledTypeReference.FromTypeDefinition(method.DeclaringTypeDefinition);
			if (typeName == null) return null;
			SD.Log.DebugFormatted("GetSymbols for: {0}", typeName.ToFileName());
			return SD.ParserService.ParseFile(typeName.ToFileName()) as ILSpyUnresolvedFile;
		}
		public void SetUpFixture()
		{
			string ruby = "class Test\r\n" +
							"\tdef initialize\r\n" +
							"\t\tputs 'test'\r\n" +
							"\tend\r\n" +
							"end";
			
			DefaultProjectContent projectContent = new DefaultProjectContent();
			RubyParser parser = new RubyParser();
			compilationUnit = parser.Parse(projectContent, @"C:\test.rb", ruby);			
			if (compilationUnit.Classes.Count > 0) {
				c = compilationUnit.Classes[0];
				if (c.Methods.Count > 0) {
					method = c.Methods[0];
				}
				
				TextArea textArea = new TextArea();
				document = new TextDocument();
				textArea.Document = document;
				textArea.Document.Text = ruby;
				
				// Get folds.
				ParserFoldingStrategy foldingStrategy = new ParserFoldingStrategy(textArea);
				
				ParseInformation parseInfo = new ParseInformation(compilationUnit);
				foldingStrategy.UpdateFoldings(parseInfo);
				List<FoldingSection> folds = new List<FoldingSection>(foldingStrategy.FoldingManager.AllFoldings);
			
				if (folds.Count > 1) {
					classFold = folds[0];
					methodFold = folds[1];
				}
			}
		}
        internal CodeConstructor CreateRequiredConstructor(CodeTypeDeclaration resourceClass,
                                                           IMethod request,
                                                           bool addOptionalParameters)
        {
            var constructor = new CodeConstructor();
            constructor.Attributes = MemberAttributes.Public;

            // IRequestProvider service
            var serviceArg = new CodeParameterDeclarationExpression(typeof(IRequestProvider), ServiceName);
            constructor.Parameters.Add(serviceArg);

            // : base(service, "path", "HTTPMETHOD")
            constructor.BaseConstructorArgs.Add(
                new CodePropertyReferenceExpression(
                    new CodeVariableReferenceExpression(ServiceName), BaseUriName));
            constructor.BaseConstructorArgs.Add(new CodePrimitiveExpression(request.MediaUpload.Simple.Path));
            constructor.BaseConstructorArgs.Add(new CodePrimitiveExpression(request.HttpMethod));

            // Add all required arguments to the constructor.
            AddBodyParameter(constructor, request);

            // Add common upload arguements.
            constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(StreamParameterName));
            constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(ContentTypeParameterName));

            AddAuthorizationAssignment(constructor);
            AddRequestParameters(resourceClass, request, constructor, addOptionalParameters);

            constructor.Parameters.Add(new CodeParameterDeclarationExpression(
                new CodeTypeReference(typeof(System.IO.Stream)), StreamParameterName));
            constructor.Parameters.Add(new CodeParameterDeclarationExpression(
                new CodeTypeReference(typeof(System.String)), ContentTypeParameterName));

            return constructor;
        }
示例#24
0
		public bool Exists(IMethod method) {
			if (method == null)
				return false;
			if (method.DeclaringType != null && types.Find(method.DeclaringType))
				return true;
			return methods.Find(method);
		}
 public override void DecorateClass(IResource resource,
                           IMethod request,
                           CodeTypeDeclaration requestClass,
                           CodeTypeDeclaration resourceClass)
 {
     requestClass.Members.Add(CreateRequiredConstructor(resourceClass, request, false));
 }
        public bool IsValidTestMethod(IProject project, IClass testClass, IMethod testMethod)
        {
            if (project == null || testClass == null || testMethod == null)
                return false;

            return IsValidTestMethod(project, testClass.GetClrName().FullName, testMethod.ShortName);
        }
示例#27
0
		public ExternalGenericParameter(IReflectionTypeSystemProvider provider, Type type) : base(provider, type)
		{
			if (type.DeclaringMethod != null)
			{
				_declaringMethod = (IMethod)provider.Map(type.DeclaringMethod);
			}
		}
		private MethodScriptSemantics GetMethodSemantics(IMethod m) {
			if (m.IsAccessor) {
				var prop = m.AccessorOwner as IProperty;
				if (prop != null) {
					var psem = _metadataImporter.GetPropertySemantics(prop);
					if (psem.Type != PropertyScriptSemantics.ImplType.GetAndSetMethods)
						throw new InvalidOperationException("Property " + prop.Name + " should be implemented with get/set methods");
					if (m.Equals(prop.Getter))
						return psem.GetMethod;
					else if (m.Equals(prop.Setter))
						return psem.SetMethod;
					else
						throw new Exception(m + " is neither the getter nor the setter for " + prop);
				}

				var evt = m.AccessorOwner as IEvent;
				if (evt != null) {
					var esem = _metadataImporter.GetEventSemantics(evt);
					if (esem.Type != EventScriptSemantics.ImplType.AddAndRemoveMethods)
						throw new InvalidOperationException("Event " + prop.Name + " should be implemented with add/remove methods");
					if (m.Equals(evt.AddAccessor))
						return esem.AddMethod;
					else if (m.Equals(evt.RemoveAccessor))
						return esem.RemoveMethod;
					else
						throw new Exception(m + " is neither the adder nor the remover for " + evt);
				}

				throw new ArgumentException("Invalid accessor owner " + m.AccessorOwner + " on member " + m);
			}
			else
				return _metadataImporter.GetMethodSemantics(m);
		}
        public PropertyNotificationAssets(ModuleDeclaration module)
        {
            if (module == null) throw new ArgumentNullException("module");
            Contract.EndContractBlock();
            //INotifyPropertyChanged Related
            INotifyPropertyChangedTypeSignature = module.FindType(typeof(INotifyPropertyChanged));
            PropertyChangedEventHandlerTypeSignature =
                module.FindType(typeof(INotifyPropertyChanged).GetEvent("PropertyChanged").EventHandlerType);

            PropertyChangedEventHandlerInvokeMethod =
                module.FindMethod(PropertyChangedEventHandlerTypeSignature, "Invoke");

            PropertyChangedEventArgsTypeSignature =
                module.FindType(typeof(PropertyChangedEventArgs));

            PropertyChangedEventArgsConstructor =
                module.FindMethod(PropertyChangedEventArgsTypeSignature, ".ctor");

            //INotifyPropertyChanging Realted
            INotifyPropertyChangingTypeSignature =
                module.FindType(typeof(INotifyPropertyChanging));
            PropertyChangingEventHandlerTypeSignature =
                module.FindType(typeof(INotifyPropertyChanging).GetEvent("PropertyChanging").EventHandlerType);

            PropertyChangingEventHandlerInvokeMethod =
                module.FindMethod(PropertyChangingEventHandlerTypeSignature, "Invoke");

            PropertyChangingEventArgsTypeSignature =
                module.FindType(typeof(PropertyChangingEventArgs));

            PropertyChangingEventArgsConstructor =
                module.FindMethod(PropertyChangingEventArgsTypeSignature, ".ctor");
        }
		void AddSenderAndEventArgsParameters(IMethod method)
		{
			DefaultReturnType returnType = new DefaultReturnType(method.DeclaringType);
			DomRegion region = new DomRegion();
			method.Parameters.Add(new DefaultParameter("sender", returnType, region));
			method.Parameters.Add(new DefaultParameter("e", returnType, region));
		}
示例#31
0
 protected abstract void GetCallInfo(object context, FieldDef field, out IMethod calledMethod, out OpCode callOpcode);
示例#32
0
 protected abstract string GetConstructorString(IMethod constructor, OutputSettings settings);
示例#33
0
 protected abstract string GetMethodString(IMethod method, OutputSettings settings);
示例#34
0
 public static int GetIcon(IMethod method)
 {
     return(MethodIndex + GetModifierOffset(method.Modifiers));
 }
示例#35
0
 bool HasReturnType(IMethod method)
 {
     return(TypeSystemServices.VoidType != method.ReturnType);
 }
示例#36
0
 override public void OnMethod(Method node)
 {
     _current = (IMethod)GetEntity(node);
     Visit(node.Body);
 }
示例#37
0
        public IMethod GetMethod(string name, List <IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false)
        {
            if (methods == null)
            {
                InitializeMethods();
            }
            List <ILMethod> lst;
            IMethod         genericMethod = null;

            if (methods.TryGetValue(name, out lst))
            {
                for (var idx = 0; idx < lst.Count; idx++)
                {
                    var i    = lst[idx];
                    int pCnt = param != null ? param.Count : 0;
                    if (i.ParameterCount == pCnt)
                    {
                        bool match = true;
                        if (genericArguments != null && i.GenericParameterCount == genericArguments.Length && genericMethod == null)
                        {
                            genericMethod = CheckGenericParams(i, param, ref match);
                        }
                        else
                        {
                            match = CheckGenericArguments(i, genericArguments);
                            if (!match)
                            {
                                continue;
                            }
                            for (int j = 0; j < pCnt; j++)
                            {
                                if (param[j] != i.Parameters[j])
                                {
                                    match = false;
                                    break;
                                }
                            }
                            if (match)
                            {
                                match = returnType == null || i.ReturnType == returnType;
                            }
                            if (match)
                            {
                                return(i);
                            }
                        }
                    }
                }
            }
            if (genericArguments != null && genericMethod != null)
            {
                var m = genericMethod.MakeGenericMethod(genericArguments);
                lst.Add((ILMethod)m);
                return(m);
            }
            if (declaredOnly)
            {
                return(null);
            }
            else
            {
                if (BaseType != null)
                {
                    return(BaseType.GetMethod(name, param, genericArguments, returnType, false));
                }
                else
                {
                    return(null);
                }
            }
        }
示例#38
0
        EntityDeclaration ConvertTypeDefinition(ITypeDefinition typeDefinition)
        {
            Modifiers modifiers = Modifiers.None;
            if (this.ShowAccessibility) {
                modifiers |= ModifierFromAccessibility(typeDefinition.Accessibility);
            }
            if (this.ShowModifiers) {
                if (typeDefinition.IsStatic) {
                    modifiers |= Modifiers.Static;
                } else if (typeDefinition.IsAbstract) {
                    modifiers |= Modifiers.Abstract;
                } else if (typeDefinition.IsSealed) {
                    modifiers |= Modifiers.Sealed;
                }
                if (typeDefinition.IsShadowing) {
                    modifiers |= Modifiers.New;
                }
            }

            ClassType classType;
            switch (typeDefinition.Kind) {
                case TypeKind.Struct:
                    classType = ClassType.Struct;
                    modifiers &= ~Modifiers.Sealed;
                    break;
                case TypeKind.Enum:
                    classType = ClassType.Enum;
                    modifiers &= ~Modifiers.Sealed;
                    break;
                case TypeKind.Interface:
                    classType = ClassType.Interface;
                    modifiers &= ~Modifiers.Abstract;
                    break;
                case TypeKind.Delegate:
                    IMethod invoke = typeDefinition.GetDelegateInvokeMethod();
                    if (invoke != null) {
                        return ConvertDelegate(invoke, modifiers);
                    } else {
                        goto default;
                    }
                default:
                    classType = ClassType.Class;
                    break;
            }

            var decl = new TypeDeclaration();
            decl.ClassType = classType;
            decl.Modifiers = modifiers;
            if (ShowAttributes) {
                decl.Attributes.AddRange (typeDefinition.Attributes.Select ((a) => new AttributeSection (ConvertAttribute (a))));
            }
            if (AddResolveResultAnnotations) {
                decl.AddAnnotation(new TypeResolveResult(typeDefinition));
            }
            decl.Name = typeDefinition.Name;

            int outerTypeParameterCount = (typeDefinition.DeclaringTypeDefinition == null) ? 0 : typeDefinition.DeclaringTypeDefinition.TypeParameterCount;

            if (this.ShowTypeParameters) {
                foreach (ITypeParameter tp in typeDefinition.TypeParameters.Skip(outerTypeParameterCount)) {
                    decl.TypeParameters.Add(ConvertTypeParameter(tp));
                }
            }

            if (this.ShowBaseTypes) {
                foreach (IType baseType in typeDefinition.DirectBaseTypes) {
                    if (baseType.IsKnownType (KnownTypeCode.Enum)) {
                        if (!typeDefinition.EnumUnderlyingType.IsKnownType (KnownTypeCode.Int32)) {
                            decl.BaseTypes.Add (ConvertType (typeDefinition.EnumUnderlyingType));
                        }
                    } else if (!baseType.IsKnownType (KnownTypeCode.Object) &&
                         !baseType.IsKnownType (KnownTypeCode.ValueType)) {
                        decl.BaseTypes.Add (ConvertType (baseType));
                    }
                }
            }

            if (this.ShowTypeParameters && this.ShowTypeParameterConstraints) {
                foreach (ITypeParameter tp in typeDefinition.TypeParameters.Skip(outerTypeParameterCount)) {
                    var constraint = ConvertTypeParameterConstraint(tp);
                    if (constraint != null)
                        decl.Constraints.Add(constraint);
                }
            }
            return decl;
        }
示例#39
0
        protected void VisitInvocationExpression()
        {
            InvocationExpression invocationExpression = this.InvocationExpression;
            int pos = this.Emitter.Output.Length;

            if (this.Emitter.IsForbiddenInvocation(invocationExpression))
            {
                throw new EmitterException(invocationExpression, "This method cannot be invoked directly");
            }

            var oldValue = this.Emitter.ReplaceAwaiterByVar;
            var oldAsyncExpressionHandling = this.Emitter.AsyncExpressionHandling;

            if (this.Emitter.IsAsync && !this.Emitter.AsyncExpressionHandling)
            {
                this.WriteAwaiters(invocationExpression);
                this.Emitter.ReplaceAwaiterByVar     = true;
                this.Emitter.AsyncExpressionHandling = true;
            }

            Tuple <bool, bool, string> inlineInfo = this.Emitter.GetInlineCode(invocationExpression);
            var argsInfo = new ArgumentsInfo(this.Emitter, invocationExpression);

            var argsExpressions = argsInfo.ArgumentsExpressions;
            var paramsArg       = argsInfo.ParamsExpression;
            var argsCount       = argsExpressions.Count();

            if (inlineInfo != null)
            {
                bool   isStaticMethod = inlineInfo.Item1;
                bool   isInlineMethod = inlineInfo.Item2;
                string inlineScript   = inlineInfo.Item3;

                if (isInlineMethod)
                {
                    if (invocationExpression.Arguments.Count > 0)
                    {
                        var code             = invocationExpression.Arguments.First();
                        var inlineExpression = code as PrimitiveExpression;

                        if (inlineExpression == null)
                        {
                            throw new EmitterException(invocationExpression, "Only primitive expression can be inlined");
                        }

                        string value = inlineExpression.Value.ToString().Trim();

                        if (value.Length > 0)
                        {
                            value = InlineArgumentsBlock.ReplaceInlineArgs(this, inlineExpression.Value.ToString(), invocationExpression.Arguments.Skip(1).ToArray());
                            this.Write(value);

                            if (value[value.Length - 1] == ';')
                            {
                                this.Emitter.EnableSemicolon = false;
                                this.WriteNewLine();
                            }
                        }
                        else
                        {
                            // Empty string, emit nothing.
                            this.Emitter.EnableSemicolon = false;
                        }

                        this.Emitter.ReplaceAwaiterByVar     = oldValue;
                        this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                        return;
                    }
                }
                else
                {
                    MemberReferenceExpression targetMemberRef = invocationExpression.Target as MemberReferenceExpression;
                    bool isBase = targetMemberRef != null && targetMemberRef.Target is BaseReferenceExpression;

                    if (!String.IsNullOrEmpty(inlineScript) && (isBase || invocationExpression.Target is IdentifierExpression))
                    {
                        argsInfo.ThisArgument = "this";
                        bool noThis = !inlineScript.Contains("{this}");

                        if (!isStaticMethod && noThis)
                        {
                            this.WriteThis();
                            this.WriteDot();
                        }

                        new InlineArgumentsBlock(this.Emitter, argsInfo, inlineScript).Emit();
                        this.Emitter.ReplaceAwaiterByVar     = oldValue;
                        this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                        return;
                    }
                }
            }

            MemberReferenceExpression targetMember = invocationExpression.Target as MemberReferenceExpression;

            ResolveResult targetMemberResolveResult = null;

            if (targetMember != null)
            {
                targetMemberResolveResult = this.Emitter.Resolver.ResolveNode(targetMember.Target, this.Emitter);
            }

            if (targetMember != null)
            {
                var member = this.Emitter.Resolver.ResolveNode(targetMember.Target, this.Emitter);

                //var targetResolve = this.Emitter.Resolver.ResolveNode(targetMember, this.Emitter);
                var targetResolve = this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter);

                if (targetResolve != null)
                {
                    var csharpInvocation = targetResolve as CSharpInvocationResolveResult;

                    InvocationResolveResult invocationResult;
                    bool isExtensionMethodInvocation = false;
                    if (csharpInvocation != null)
                    {
                        if (member != null && member.Type.Kind == TypeKind.Delegate && !csharpInvocation.IsExtensionMethodInvocation)
                        {
                            throw new EmitterException(invocationExpression, "Delegate's methods are not supported. Please use direct delegate invoke.");
                        }

                        if (csharpInvocation.IsExtensionMethodInvocation)
                        {
                            invocationResult            = csharpInvocation;
                            isExtensionMethodInvocation = true;
                            var resolvedMethod = invocationResult.Member as IMethod;
                            if (resolvedMethod != null && resolvedMethod.IsExtensionMethod)
                            {
                                string inline   = this.Emitter.GetInline(resolvedMethod);
                                bool   isNative = this.IsNativeMethod(resolvedMethod);

                                if (string.IsNullOrWhiteSpace(inline) && isNative)
                                {
                                    invocationResult = null;
                                }
                            }
                        }
                        else
                        {
                            invocationResult = null;
                        }

                        if (this.IsEmptyPartialInvoking(csharpInvocation.Member as IMethod))
                        {
                            this.Emitter.SkipSemiColon           = true;
                            this.Emitter.ReplaceAwaiterByVar     = oldValue;
                            this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                            return;
                        }
                    }
                    else
                    {
                        invocationResult = targetResolve as InvocationResolveResult;

                        if (invocationResult != null && this.IsEmptyPartialInvoking(invocationResult.Member as IMethod))
                        {
                            this.Emitter.SkipSemiColon           = true;
                            this.Emitter.ReplaceAwaiterByVar     = oldValue;
                            this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                            return;
                        }
                    }

                    if (invocationResult == null)
                    {
                        invocationResult = this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter) as InvocationResolveResult;
                    }

                    if (invocationResult != null)
                    {
                        var resolvedMethod = invocationResult.Member as IMethod;

                        if (resolvedMethod != null && resolvedMethod.IsExtensionMethod)
                        {
                            string inline   = this.Emitter.GetInline(resolvedMethod);
                            bool   isNative = this.IsNativeMethod(resolvedMethod);

                            if (isExtensionMethodInvocation)
                            {
                                if (!string.IsNullOrWhiteSpace(inline))
                                {
                                    this.Write("");
                                    StringBuilder savedBuilder = this.Emitter.Output;
                                    this.Emitter.Output = new StringBuilder();
                                    this.WriteThisExtension(invocationExpression.Target);
                                    argsInfo.ThisArgument = this.Emitter.Output.ToString();
                                    this.Emitter.Output   = savedBuilder;
                                    new InlineArgumentsBlock(this.Emitter, argsInfo, inline).Emit();
                                }
                                else if (!isNative)
                                {
                                    var    overloads     = OverloadsCollection.Create(this.Emitter, resolvedMethod);
                                    string name          = BridgeTypes.ToJsName(resolvedMethod.DeclaringType, this.Emitter) + "." + overloads.GetOverloadName();
                                    var    isIgnoreClass = resolvedMethod.DeclaringTypeDefinition != null && this.Emitter.Validator.IsIgnoreType(resolvedMethod.DeclaringTypeDefinition);

                                    this.Write(name);

                                    if (!isIgnoreClass && argsInfo.HasTypeArguments)
                                    {
                                        this.WriteOpenParentheses();
                                        new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit();
                                        this.WriteCloseParentheses();
                                    }

                                    this.WriteOpenParentheses();

                                    this.WriteThisExtension(invocationExpression.Target);

                                    if (invocationExpression.Arguments.Count > 0)
                                    {
                                        this.WriteComma();
                                    }

                                    new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, invocationExpression).Emit();

                                    this.WriteCloseParentheses();
                                }

                                if (!string.IsNullOrWhiteSpace(inline) || !isNative)
                                {
                                    this.Emitter.ReplaceAwaiterByVar     = oldValue;
                                    this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                                    return;
                                }
                            }
                            else if (isNative)
                            {
                                if (!string.IsNullOrWhiteSpace(inline))
                                {
                                    this.Write("");
                                    StringBuilder savedBuilder = this.Emitter.Output;
                                    this.Emitter.Output = new StringBuilder();
                                    this.WriteThisExtension(invocationExpression.Target);
                                    argsInfo.ThisArgument = this.Emitter.Output.ToString();
                                    this.Emitter.Output   = savedBuilder;
                                    new InlineArgumentsBlock(this.Emitter, argsInfo, inline).Emit();
                                }
                                else
                                {
                                    argsExpressions.First().AcceptVisitor(this.Emitter);
                                    this.WriteDot();
                                    string name = this.Emitter.GetEntityName(resolvedMethod);
                                    this.Write(name);
                                    this.WriteOpenParentheses();
                                    new ExpressionListBlock(this.Emitter, argsExpressions.Skip(1), paramsArg, invocationExpression).Emit();
                                    this.WriteCloseParentheses();
                                }

                                this.Emitter.ReplaceAwaiterByVar     = oldValue;
                                this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                                return;
                            }
                        }
                    }
                }
            }

            var proto = false;

            if (targetMember != null && targetMember.Target is BaseReferenceExpression)
            {
                var rr = this.Emitter.Resolver.ResolveNode(targetMember, this.Emitter) as MemberResolveResult;

                if (rr != null)
                {
                    proto = rr.IsVirtualCall;

                    /*var method = rr.Member as IMethod;
                     * if (method != null && method.IsVirtual)
                     * {
                     *  proto = true;
                     * }
                     * else
                     * {
                     *  var prop = rr.Member as IProperty;
                     *
                     *  if (prop != null && prop.IsVirtual)
                     *  {
                     *      proto = true;
                     *  }
                     * }*/
                }
            }

            if (proto)
            {
                var baseType = this.Emitter.GetBaseMethodOwnerTypeDefinition(targetMember.MemberName, targetMember.TypeArguments.Count);
                var method   = invocationExpression.GetParent <MethodDeclaration>();

                bool isIgnore = this.Emitter.Validator.IsIgnoreType(baseType);

                if (isIgnore)
                {
                    //throw (System.Exception)this.Emitter.CreateException(targetMember.Target, "Cannot call base method, because parent class code is ignored");
                }

                bool needComma = false;

                var resolveResult = this.Emitter.Resolver.ResolveNode(targetMember, this.Emitter);

                string name = null;

                if (this.Emitter.TypeInfo.GetBaseTypes(this.Emitter).Any())
                {
                    name = BridgeTypes.ToJsName(this.Emitter.TypeInfo.GetBaseClass(this.Emitter), this.Emitter);
                }
                else
                {
                    name = BridgeTypes.ToJsName(baseType, this.Emitter);
                }

                string baseMethod;

                if (resolveResult is InvocationResolveResult)
                {
                    InvocationResolveResult invocationResult = (InvocationResolveResult)resolveResult;
                    baseMethod = OverloadsCollection.Create(this.Emitter, invocationResult.Member).GetOverloadName();
                }
                else if (resolveResult is MemberResolveResult)
                {
                    MemberResolveResult memberResult = (MemberResolveResult)resolveResult;
                    baseMethod = OverloadsCollection.Create(this.Emitter, memberResult.Member).GetOverloadName();
                }
                else
                {
                    baseMethod = targetMember.MemberName;
                    baseMethod = this.Emitter.AssemblyInfo.PreserveMemberCase ? baseMethod : Object.Net.Utilities.StringUtils.ToLowerCamelCase(baseMethod);
                }

                this.Write(name, ".prototype.", baseMethod);

                if (!isIgnore && argsInfo.HasTypeArguments)
                {
                    this.WriteOpenParentheses();
                    new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit();
                    this.WriteCloseParentheses();
                }

                this.WriteDot();

                this.Write("call");
                this.WriteOpenParentheses();

                this.WriteThis();
                needComma = true;

                foreach (var arg in argsExpressions)
                {
                    if (needComma)
                    {
                        this.WriteComma();
                    }

                    needComma = true;
                    arg.AcceptVisitor(this.Emitter);
                }

                this.WriteCloseParentheses();
            }
            else
            {
                var dynamicResolveResult = this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter) as DynamicInvocationResolveResult;

                if (dynamicResolveResult != null)
                {
                    var group = dynamicResolveResult.Target as MethodGroupResolveResult;

                    if (group != null && group.Methods.Count() > 1)
                    {
                        throw new EmitterException(invocationExpression, "Cannot compile this dynamic invocation because there are two or more method overloads with the same parameter count. To work around this limitation, assign the dynamic value to a non-dynamic variable before use or call a method with different parameter count");
                    }
                }

                var     targetResolveResult     = this.Emitter.Resolver.ResolveNode(invocationExpression.Target, this.Emitter);
                var     invocationResolveResult = targetResolveResult as MemberResolveResult;
                IMethod method = null;

                if (invocationResolveResult != null)
                {
                    method = invocationResolveResult.Member as IMethod;
                }

                if (this.IsEmptyPartialInvoking(method))
                {
                    this.Emitter.SkipSemiColon           = true;
                    this.Emitter.ReplaceAwaiterByVar     = oldValue;
                    this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;
                    return;
                }

                int count = this.Emitter.Writers.Count;
                invocationExpression.Target.AcceptVisitor(this.Emitter);

                if (this.Emitter.Writers.Count > count)
                {
                    var tuple = this.Emitter.Writers.Pop();

                    if (method != null && method.IsExtensionMethod)
                    {
                        StringBuilder savedBuilder = this.Emitter.Output;
                        this.Emitter.Output = new StringBuilder();
                        this.WriteThisExtension(invocationExpression.Target);
                        argsInfo.ThisArgument = this.Emitter.Output.ToString();
                        this.Emitter.Output   = savedBuilder;
                    }

                    new InlineArgumentsBlock(this.Emitter, argsInfo, tuple.Item1).Emit();
                    var result = this.Emitter.Output.ToString();
                    this.Emitter.Output    = tuple.Item2;
                    this.Emitter.IsNewLine = tuple.Item3;
                    this.Write(result);
                }
                else
                {
                    var isIgnore = false;

                    if (method != null && method.DeclaringTypeDefinition != null && this.Emitter.Validator.IsIgnoreType(method.DeclaringTypeDefinition))
                    {
                        isIgnore = true;
                    }

                    if (!isIgnore && argsInfo.HasTypeArguments)
                    {
                        this.WriteOpenParentheses();
                        new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit();
                        this.WriteCloseParentheses();
                    }

                    this.WriteOpenParentheses();
                    new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, invocationExpression).Emit();
                    this.WriteCloseParentheses();
                }
            }

            Helpers.CheckValueTypeClone(this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter), invocationExpression, this, pos);

            this.Emitter.ReplaceAwaiterByVar     = oldValue;
            this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;
        }
示例#40
0
 public DelegateInfo(FieldDef field, IMethod methodRef, OpCode callOpcode)
 {
     this.field      = field;
     this.methodRef  = methodRef;
     this.callOpcode = callOpcode;
 }
示例#41
0
 protected virtual bool IsEmptyPartialInvoking(IMethod method)
 {
     return(method != null && method.IsPartial && !method.HasBody);
 }
示例#42
0
        static bool FindEventCall(IList <Instruction> instructions, ref int index, out IField field, out IMethod calledMethod)
        {
            field        = null;
            calledMethod = null;

            int callvirt = FindInstruction(instructions, index, Code.Callvirt);

            if (callvirt < 2)
            {
                return(false);
            }
            index = callvirt + 1;

            var ldloc = instructions[callvirt - 1];

            if (ldloc.OpCode.Code != Code.Ldloc_0)
            {
                return(false);
            }

            var ldfld = instructions[callvirt - 2];

            if (ldfld.OpCode.Code != Code.Ldfld)
            {
                return(false);
            }

            field        = ldfld.Operand as IField;
            calledMethod = instructions[callvirt].Operand as IMethod;
            return(field != null && calledMethod != null);
        }
示例#43
0
 public MethodBodySymbolContext WithScope(IMethod method)
 => new MethodBodySymbolContext(SourceSymbolContext.WithScope(method), Locals.AddRange(method.ParameterLocals), CurrentStatement);
示例#44
0
 private bool IsNativeMethod(IMethod resolvedMethod)
 {
     return(resolvedMethod.DeclaringTypeDefinition != null &&
            this.Emitter.Validator.IsIgnoreType(resolvedMethod.DeclaringTypeDefinition));
 }
示例#45
0
 protected virtual bool IsExceptionLogger(IMethod method)
 {
     return(exceptionLoggerMethods.Find(method));
 }
示例#46
0
 public IStrongValueHandle <IValue> InvokeMethod(IThreadReference thread, IMethod method, InvokeOptions options, params IValue[] arguments)
 {
     throw new NotImplementedException();
 }
示例#47
0
 protected CallInstruction(OpCode opCode, IMethod method) : base(opCode)
 {
     Debug.Assert(method != null);
     this.Method    = method;
     this.Arguments = new InstructionCollection <ILInstruction>(this, 0);
 }
示例#48
0
        protected virtual IEnumerable <string> GetDefineMethods(InitPosition value, Func <MethodDeclaration, IMethod, string> fn)
        {
            var methods  = TypeInfo.InstanceMethods;
            var attrName = "H5.InitAttribute";

            foreach (var methodGroup in methods)
            {
                foreach (var method in methodGroup.Value)
                {
                    foreach (var attrSection in method.Attributes)
                    {
                        foreach (var attr in attrSection.Attributes)
                        {
                            var rr = Emitter.Resolver.ResolveNode(attr.Type);
                            if (rr.Type.FullName == attrName)
                            {
                                throw new EmitterException(attr, "Instance method cannot be Init method");
                            }
                        }
                    }
                }
            }

            methods = TypeInfo.StaticMethods;
            List <string> list = new List <string>();

            foreach (var methodGroup in methods)
            {
                foreach (var method in methodGroup.Value)
                {
                    MemberResolveResult rrMember = null;
                    IMethod             rrMethod = null;
                    foreach (var attrSection in method.Attributes)
                    {
                        foreach (var attr in attrSection.Attributes)
                        {
                            var rr = Emitter.Resolver.ResolveNode(attr.Type);
                            if (rr.Type.FullName == attrName)
                            {
                                InitPosition?initPosition = null;
                                if (attr.HasArgumentList)
                                {
                                    if (attr.Arguments.Count > 0)
                                    {
                                        var argExpr = attr.Arguments.First();
                                        var argrr   = Emitter.Resolver.ResolveNode(argExpr);
                                        if (argrr.ConstantValue is int)
                                        {
                                            initPosition = (InitPosition)argrr.ConstantValue;
                                        }
                                    }
                                    else
                                    {
                                        initPosition = InitPosition.After;
                                    }
                                }
                                else
                                {
                                    initPosition = InitPosition.After;
                                }

                                if (initPosition == value)
                                {
                                    if (rrMember == null)
                                    {
                                        rrMember = Emitter.Resolver.ResolveNode(method) as MemberResolveResult;
                                        rrMethod = rrMember != null ? rrMember.Member as IMethod : null;
                                    }

                                    if (rrMethod != null)
                                    {
                                        if (rrMethod.TypeParameters.Count > 0)
                                        {
                                            throw new EmitterException(method, "Init method cannot be generic");
                                        }

                                        if (rrMethod.Parameters.Count > 0)
                                        {
                                            throw new EmitterException(method, "Init method should not have parameters");
                                        }

                                        if (rrMethod.ReturnType.Kind != TypeKind.Void &&
                                            !rrMethod.ReturnType.IsKnownType(KnownTypeCode.Void))
                                        {
                                            throw new EmitterException(method, "Init method should not return anything");
                                        }

                                        list.Add(fn(method, rrMethod));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(list);
        }
 public void AddOverride(IMethod overridingMethod)
 {
     _overriders.Add(overridingMethod);
 }
示例#50
0
        /// <summary>
        /// Gets the ID string (C# 4.0 spec, §A.3.1) for the specified entity.
        /// </summary>
        public static string GetIdString(this IEntity entity)
        {
            StringBuilder b = new StringBuilder();

            switch (entity.SymbolKind)
            {
            case SymbolKind.TypeDefinition:
                b.Append("T:");
                AppendTypeName(b, (ITypeDefinition)entity, false);
                return(b.ToString());

            case SymbolKind.Field:
                b.Append("F:");
                break;

            case SymbolKind.Property:
            case SymbolKind.Indexer:
                b.Append("P:");
                break;

            case SymbolKind.Event:
                b.Append("E:");
                break;

            default:
                b.Append("M:");
                break;
            }
            IMember member = (IMember)entity;

            if (member.DeclaringType != null)
            {
                AppendTypeName(b, member.DeclaringType, false);
                b.Append('.');
            }
            if (member.IsExplicitInterfaceImplementation && member.Name.IndexOf('.') < 0 && member.ExplicitlyImplementedInterfaceMembers.Count() == 1)
            {
                AppendTypeName(b, member.ExplicitlyImplementedInterfaceMembers.First().DeclaringType, true);
                b.Append('#');
            }
            b.Append(member.Name.Replace('.', '#').Replace('<', '{').Replace('>', '}'));
            IMethod method = member as IMethod;

            if (method != null && method.TypeParameters.Count > 0)
            {
                b.Append("``");
                b.Append(method.TypeParameters.Count);
            }
            IParameterizedMember parameterizedMember = member as IParameterizedMember;

            if (parameterizedMember != null && parameterizedMember.Parameters.Count > 0)
            {
                b.Append('(');
                var parameters = parameterizedMember.Parameters;
                for (int i = 0; i < parameters.Count; i++)
                {
                    if (i > 0)
                    {
                        b.Append(',');
                    }
                    AppendTypeName(b, parameters[i].Type, false);
                }
                b.Append(')');
            }
            if (member.SymbolKind == SymbolKind.Operator && (member.Name == "op_Implicit" || member.Name == "op_Explicit"))
            {
                b.Append('~');
                AppendTypeName(b, member.ReturnType, false);
            }
            return(b.ToString());
        }
示例#51
0
 public string GetSpecialMethodType(DeclaredElementPresenterStyle presenter, IMethod method, ISubstitution substitution)
 => null;
示例#52
0
        public static JsExpression ResolveTypeParameter(ITypeParameter tp, ITypeDefinition currentType, IMethod currentMethod, IMetadataImporter metadataImporter, IErrorReporter errorReporter, INamer namer)
        {
            bool unusable = false;

            switch (tp.OwnerType)
            {
            case SymbolKind.TypeDefinition:
                unusable = metadataImporter.GetTypeSemantics(currentType).IgnoreGenericArguments;
                break;

            case SymbolKind.Method: {
                var sem = metadataImporter.GetMethodSemantics(currentMethod);
                unusable = sem.Type != MethodScriptSemantics.ImplType.InlineCode && metadataImporter.GetMethodSemantics(currentMethod).IgnoreGenericArguments;
                break;
            }

            default:
                errorReporter.InternalError("Invalid owner " + tp.OwnerType + " for type parameter " + tp);
                return(JsExpression.Null);
            }
            if (unusable)
            {
                errorReporter.Message(Messages._7536, tp.Name, tp.OwnerType == SymbolKind.TypeDefinition ? "type" : "method", tp.OwnerType == SymbolKind.TypeDefinition ? currentType.FullName : currentMethod.FullName);
                return(JsExpression.Null);
            }
            return(JsExpression.Identifier(namer.GetTypeParameterName(tp)));
        }
示例#53
0
 /// <summary>
 /// Констуктор решателя
 /// </summary>
 /// <param name="Method">Конкретный метод решения</param>
 /// <param name="Logger">Логгер процесса решения</param>
 public LoggingSolver(IMethod Method, ILogger Logger)
 {
     this.Method = Method;
     this.Logger = Logger;
 }
示例#54
0
        public IList GetMetricHistory(string codeElementName, object metricDefinition)
        {
            CodeBaseManager codeBaseManager = new CodeBaseManager(analysisResultRefsList[0].Project);

            Type   metricType;
            string codeElementType;
            Type   metricDefinitionType = metricDefinition.GetType();

            if (metricDefinitionType == typeof(NDependMetricDefinition))
            {
                metricType      = Type.GetType(((NDependMetricDefinition)metricDefinition).NDependMetricType);
                codeElementType = ((NDependMetricDefinition)metricDefinition).NDependCodeElementType;
            }
            else
            {
                metricType      = Type.GetType(((UserDefinedMetricDefinition)metricDefinition).MetricType);
                codeElementType = ((UserDefinedMetricDefinition)metricDefinition).NDependCodeElementType;
            }

            Type  nullableMetricType = typeof(Nullable <>).MakeGenericType(metricType);
            var   metricValue        = Activator.CreateInstance(nullableMetricType);
            IList metricValues       = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(nullableMetricType));

            foreach (var analysisResultRef in analysisResultRefsList)
            {
                ICodeBase           currentAnalysisResultCodeBase        = codeBaseManager.LoadCodeBase(analysisResultRef);
                CodeElementsManager currentAnalysisResultCodeBaseManager = new CodeElementsManager(currentAnalysisResultCodeBase);
                UserDefinedMetrics  userDefinedMetrics = new UserDefinedMetrics(currentAnalysisResultCodeBase);

                metricValue = null;
                switch (codeElementType)
                {
                case "NDepend.CodeModel.IAssembly":
                    IAssembly selectedAssemblyFromCurrentAnalysisResultCodebase = currentAnalysisResultCodeBaseManager.GetAssemblyByName(codeElementName);
                    if (selectedAssemblyFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = metricDefinitionType == typeof(NDependMetricDefinition) ?
                                      currentAnalysisResultCodeBaseManager.GetCodeElementMetricValue(selectedAssemblyFromCurrentAnalysisResultCodebase, typeof(IAssembly), (NDependMetricDefinition)metricDefinition) :
                                      userDefinedMetrics.InvokeUserDefinedMetric(codeElementName, ((UserDefinedMetricDefinition)metricDefinition).MethodNameToInvoke);
                    }
                    break;

                case "NDepend.CodeModel.INamespace":
                    INamespace selectedNamespaceFromCurrentAnalysisResultCodebase = currentAnalysisResultCodeBaseManager.GetNamespaceByName(codeElementName);
                    if (selectedNamespaceFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = metricDefinitionType == typeof(NDependMetricDefinition) ?
                                      currentAnalysisResultCodeBaseManager.GetCodeElementMetricValue(selectedNamespaceFromCurrentAnalysisResultCodebase, typeof(INamespace), (NDependMetricDefinition)metricDefinition) :
                                      userDefinedMetrics.InvokeUserDefinedMetric(codeElementName, ((UserDefinedMetricDefinition)metricDefinition).MethodNameToInvoke);
                    }
                    break;

                case "NDepend.CodeModel.IType":
                    IType selectedTypeFromCurrentAnalysisResultCodebase = currentAnalysisResultCodeBaseManager.GetTypeByName(codeElementName);
                    if (selectedTypeFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = metricDefinitionType == typeof(NDependMetricDefinition) ?
                                      currentAnalysisResultCodeBaseManager.GetCodeElementMetricValue(selectedTypeFromCurrentAnalysisResultCodebase, typeof(IType), (NDependMetricDefinition)metricDefinition) :
                                      userDefinedMetrics.InvokeUserDefinedMetric(codeElementName, ((UserDefinedMetricDefinition)metricDefinition).MethodNameToInvoke);
                    }
                    break;

                case "NDepend.CodeModel.IMethod":
                    IMethod selectedMethodFromCurrentAnalysisResultCodebase = currentAnalysisResultCodeBaseManager.GetMethodByName(codeElementName);
                    if (selectedMethodFromCurrentAnalysisResultCodebase != null)
                    {
                        metricValue = metricDefinitionType == typeof(NDependMetricDefinition) ?
                                      currentAnalysisResultCodeBaseManager.GetCodeElementMetricValue(selectedMethodFromCurrentAnalysisResultCodebase, typeof(IMethod), (NDependMetricDefinition)metricDefinition) :
                                      userDefinedMetrics.InvokeUserDefinedMetric(codeElementName, ((UserDefinedMetricDefinition)metricDefinition).MethodNameToInvoke);
                    }
                    break;
                }
                metricValues.Add(metricValue);
            }
            return(metricValues);
        }
示例#55
0
        public static string DelegateToTemplate(string tpl, IMethod method, IEmitter emitter)
        {
            bool addThis = !method.IsStatic;

            StringBuilder sb = new StringBuilder(tpl);

            sb.Append("(");

            bool comma = false;

            if (addThis)
            {
                sb.Append("{this}");
                comma = true;
            }

            if (!IsIgnoreGeneric(method, emitter) && method.TypeArguments.Count > 0)
            {
                foreach (var typeParameter in method.TypeArguments)
                {
                    if (comma)
                    {
                        sb.Append(", ");
                    }

                    if (typeParameter.Kind == TypeKind.TypeParameter)
                    {
                        sb.Append("{");
                        sb.Append(typeParameter.Name);
                        sb.Append("}");
                    }
                    else
                    {
                        sb.Append(H5Types.ToJsName(typeParameter, emitter));
                    }
                    comma = true;
                }
            }

            foreach (var parameter in method.Parameters)
            {
                if (comma)
                {
                    sb.Append(", ");
                }

                sb.Append("{");

                if (parameter.IsParams &&
                    method.Attributes.Any(a => a.AttributeType.FullName == "H5.ExpandParamsAttribute"))
                {
                    sb.Append("*");
                }

                sb.Append(parameter.Name);
                sb.Append("}");
                comma = true;
            }

            sb.Append(")");
            return(sb.ToString());
        }
        public void TestFullNameOfValueCollectionCopyToMethod()
        {
            IMethod copyTo = valueCollection.Methods.Single(m => m.Name == "CopyTo");

            Assert.AreEqual("Public NotOverridable Sub System.Collections.Generic.Dictionary(Of TKey, TValue).ValueCollection.CopyTo(array As TValue(), index As Integer)", fullMemberNameAmbience.Convert(copyTo));
        }
 void IScopeAppender.AddStaticBasedScope(IMethod function) => RulesetScope.AddNativeMethod(function);
示例#58
0
 public static bool IsScript(IMethod method)
 {
     return(method.Attributes.Any(a => a.AttributeType.FullName == CS.NS.H5 + ".ScriptAttribute"));
 }
示例#59
0
 public MethodWrapper(IMethod method)
 {
     this.method = method;
 }
示例#60
0
        public static bool IsEntryPointMethod(IEmitter emitter, MethodDeclaration methodDeclaration)
        {
            IMethod method = emitter.Resolver.ResolveNode(methodDeclaration) is MemberResolveResult member_rr ? member_rr.Member as IMethod : null;

            return(IsEntryPointMethod(method));
        }