Пример #1
0
        public void Initialize(ModuleDeclaration module)
        {
            this.loggingImplementation = new LoggingImplementationTypeBuilder(module);
            this.formatWriter          = new StringFormatWriter(module);

            this.loggerType = module.FindType(typeof(Logger));

            Predicate <MethodDefDeclaration> singleMessagePredicate =
                method => method.Parameters.Count == 1 &&
                IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String);

            this.categoryInitializerMethod = module.FindMethod(module.FindType(typeof(LogManager)), "GetLogger", singleMessagePredicate);

            this.writeDebugMethod = module.FindMethod(this.loggerType, "Trace", singleMessagePredicate);
            this.writeInfoMethod  = module.FindMethod(this.loggerType, "Info", singleMessagePredicate);
            this.writeWarnMethod  = module.FindMethod(this.loggerType, "Warn", singleMessagePredicate);
            this.writeErrorMethod = module.FindMethod(this.loggerType, "Error", singleMessagePredicate);
            this.writeFatalMethod = module.FindMethod(this.loggerType, "Fatal", singleMessagePredicate);

            this.getIsTraceEnabledMethod = module.FindMethod(this.loggerType, "get_IsTraceEnabled");
            this.getIsInfoEnabledMethod  = module.FindMethod(this.loggerType, "get_IsInfoEnabled");
            this.getIsWarnEnabledMethod  = module.FindMethod(this.loggerType, "get_IsWarnEnabled");
            this.getIsErrorEnabledMethod = module.FindMethod(this.loggerType, "get_IsErrorEnabled");
            this.getIsFatalEnabledMethod = module.FindMethod(this.loggerType, "get_IsFatalEnabled");
        }
Пример #2
0
 private protected AbstractMethodBaseSignature(CallingConvention callingConvention, uint genParamCount, ITypeSignature <TypeSig> retType, IEnumerable <ITypeSignature <TypeSig> > parameters, IEnumerable <ITypeSignature <TypeSig> > paramsAfterSentinel) : base(callingConvention)
 {
     RetType             = retType;
     Parameters          = parameters;
     GenParamCount       = genParamCount;
     ParamsAfterSentinel = paramsAfterSentinel;
 }
        private MethodDefDeclaration CreateWrapperMethod(IMethod loggerMethod)
        {
            MethodDefDeclaration wrapperMethod = new MethodDefDeclaration
            {
                Name       = this.implementationType.Methods.GetUniqueName(loggerMethod.Name + "{0}"),
                Attributes = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig,
            };

            this.implementationType.Methods.Add(wrapperMethod);

            wrapperMethod.ReturnParameter = new ParameterDeclaration
            {
                Attributes    = ParameterAttributes.Retval,
                ParameterType = this.module.Cache.GetIntrinsic(IntrinsicType.Void)
            };

            ITypeSignature       loggerFieldType        = loggerMethod.DeclaringType.GetNakedType();
            MethodDefDeclaration loggerMethodDefinition = loggerMethod.GetMethodDefinition();

            if (!loggerMethodDefinition.IsStatic)
            {
                wrapperMethod.Parameters.Add(new ParameterDeclaration(0, "logger", loggerFieldType));
            }

            for (int i = 0; i < loggerMethodDefinition.Parameters.Count; i++)
            {
                ParameterDeclaration parameter = loggerMethodDefinition.Parameters[i];
                wrapperMethod.Parameters.Add(new ParameterDeclaration(wrapperMethod.Parameters.Count, parameter.Name,
                                                                      parameter.ParameterType.TranslateType(this.module)));
            }

            this.EmitWrapperCallBody(wrapperMethod, loggerMethod);

            return(wrapperMethod);
        }
                protected override void ImplementOnException(InstructionBlock block, ITypeSignature exceptionType, InstructionWriter writer)
                {
                    MethodDefDeclaration targetMethod = this.transformationInstance.AspectWeaverInstance.TargetElement as MethodDefDeclaration;

                    if (targetMethod == null)
                    {
                        return;
                    }

                    // TODO: nested types
                    string category = targetMethod.DeclaringType.Name;
                    ILoggingCategoryBuilder builder  = this.backendInstance.GetCategoryBuilder(category);
                    InstructionSequence     sequence = block.AddInstructionSequence(null, NodePosition.After, null);

                    writer.AttachInstructionSequence(sequence);

                    LocalVariableSymbol exceptionLocal = block.MethodBody.RootInstructionBlock.DefineLocalVariable(
                        exceptionType, DebuggerSpecialNames.GetVariableSpecialName("ex"));

                    LogSeverity logSeverity = LogSeverity.Warning;

                    if (builder.SupportsIsEnabled)
                    {
                        builder.EmitGetIsEnabled(writer, logSeverity);
                        InstructionSequence branchSequence = block.AddInstructionSequence(null, NodePosition.After, sequence);
                        writer.EmitBranchingInstruction(OpCodeNumber.Brfalse_S, branchSequence);
                    }

                    builder.EmitWrite(writer, block, "An exception occurred:\n{0}", 1, logSeverity,
                                      w => w.EmitInstructionLocalVariable(OpCodeNumber.Stloc, exceptionLocal),
                                      (i, w) => w.EmitInstructionLocalVariable(OpCodeNumber.Ldloc, exceptionLocal));

                    writer.EmitInstruction(OpCodeNumber.Rethrow);
                    writer.DetachInstructionSequence();
                }
        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");
        }
Пример #6
0
        public Type ReadNextType()
        {
            uint           typeId        = ReadUInt32();
            ITypeSignature typeSignature = _typeManager.ResolveTypeSignature(typeId);

            return(typeSignature.Read(this));
        }
 internal void PrintType(ITypeSignature typeSig, IModule module)
 {
     PrintType(
         typeSig,
         module,
         (_flags & SignaturePrintingFlags.IgnoreTypeOwner) == SignaturePrintingFlags.IgnoreTypeOwner);
 }
Пример #8
0
 public Symbol(string identifier, ITypeSignature type, bool initialized, int definedOnLine)
 {
     Identifier    = identifier;
     Type          = type;
     Initialized   = initialized;
     DefinedOnLine = definedOnLine;
 }
Пример #9
0
        public void Initialize(ModuleDeclaration module)
        {
            this.loggingImplementation = new LoggingImplementationTypeBuilder(module);
            this.formatWriter = new StringFormatWriter(module);

            this.loggerType = module.FindType(typeof(Logger));

            Predicate<MethodDefDeclaration> singleMessagePredicate =
                method => method.Parameters.Count == 1 &&
                    IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String);

            this.categoryInitializerMethod = module.FindMethod(module.FindType(typeof(LogManager)), "GetLogger", singleMessagePredicate);

            this.writeDebugMethod = module.FindMethod(this.loggerType, "Trace", singleMessagePredicate);
            this.writeInfoMethod = module.FindMethod(this.loggerType, "Info", singleMessagePredicate);
            this.writeWarnMethod = module.FindMethod(this.loggerType, "Warn", singleMessagePredicate);
            this.writeErrorMethod = module.FindMethod(this.loggerType, "Error", singleMessagePredicate);
            this.writeFatalMethod = module.FindMethod(this.loggerType, "Fatal", singleMessagePredicate);

            this.getIsTraceEnabledMethod = module.FindMethod(this.loggerType, "get_IsTraceEnabled");
            this.getIsInfoEnabledMethod = module.FindMethod(this.loggerType, "get_IsInfoEnabled");
            this.getIsWarnEnabledMethod = module.FindMethod(this.loggerType, "get_IsWarnEnabled");
            this.getIsErrorEnabledMethod = module.FindMethod(this.loggerType, "get_IsErrorEnabled");
            this.getIsFatalEnabledMethod = module.FindMethod(this.loggerType, "get_IsFatalEnabled");
        }
 public MethodBodyWrappingImplementationOptions(string transformation, MethodBodyWrappingImplementationType wrappingImplementationType, ITypeSignature[] exceptionTypes)
 {
     if (transformation == null) throw new ArgumentNullException("transformation");
     _transformation = transformation;
     _wrappingImplementationType = wrappingImplementationType;
     _exceptionTypes = exceptionTypes;
 }
        internal static bool EqualsValueTypeOrEnum(ITypeSignature typeSig, IAssembly owner)
        {
            if (typeSig.Namespace != "System")
            {
                return(false);
            }

            if (typeSig.Name != "ValueType" && typeSig.Name != "Enum")
            {
                return(false);
            }

            if (typeSig.IsNested)
            {
                return(false);
            }

            var assemblySig = typeSig.Owner as IAssemblySignature;

            if (assemblySig == null)
            {
                assemblySig = owner;
            }

            if (assemblySig.Name != "mscorlib")
            {
                return(false);
            }

            return(true);
        }
Пример #12
0
        private void PrintDeclaringType(ITypeSignature typeSig, IModule module, bool ignoreOwner)
        {
            var owner = typeSig.Owner;

            if (owner != null)
            {
                if (owner.SignatureType == SignatureType.Type)
                {
                    PrintDeclaringType((ITypeSignature)owner, module, ignoreOwner);
                    _builder.Append("/");
                }
                else if (!ignoreOwner)
                {
                    PrintResolutionScope(owner);
                }
            }
            else if (!ignoreOwner && module != null)
            {
                if (module.IsPrimeModule)
                {
                    PrintResolutionScope(module.Assembly);
                }
                else
                {
                    PrintResolutionScope(module);
                }
            }

            PrintIdentifier(CodeModelUtils.GetTypeName(typeSig.Name, typeSig.Namespace));
        }
        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));
        }
                private bool ShouldUseWrapper(MethodDefDeclaration targetMethod)
                {
                    if (targetMethod.Name == "ToString")
                    {
                        MethodDefDeclaration parent = targetMethod.GetParentDefinition(true);
                        if (parent != null)
                        {
                            if (parent.MatchesReference(
                                    this.transformationInstance.parent.assets.ToStringMethodSignature))
                            {
                                return(true);
                            }
                        }
                    }

                    for (int i = 0; i < targetMethod.Parameters.Count; i++)
                    {
                        ITypeSignature parameterType = targetMethod.Parameters[i].ParameterType;

                        if (!parameterType.BelongsToClassification(TypeClassifications.Intrinsic) ||
                            IntrinsicTypeSignature.Is(parameterType, IntrinsicType.Object))
                        {
                            return(true);
                        }
                    }

                    return(false);
                }
        public static string ToReflectionString(this ITypeSignature typeSig, IModule module = null, SignaturePrintingFlags flags = SignaturePrintingFlags.None)
        {
            var printer = new ReflectionSignaturePrinter(flags);

            printer.PrintType(typeSig, module);

            return(printer.ToString());
        }
        public static ITypeSignature GetElementType(this ITypeSignature typeSig, TypeElementCode type)
        {
            while (typeSig != null && typeSig.ElementCode != type)
            {
                typeSig = typeSig.ElementType;
            }

            return(typeSig);
        }
        public static ITypeSignature GetLastElementType(this ITypeSignature typeSig)
        {
            while (typeSig.ElementType != null)
            {
                typeSig = typeSig.ElementType;
            }

            return(typeSig);
        }
        private void AddEquatable(TypeDefDeclaration enhancedType)
        {
            var genericInstance = this.equatableInterface.GetTypeDefinition().GetGenericInstance(new GenericMap(
                                                                                                     enhancedType.Module,
                                                                                                     new ITypeSignature[] { enhancedType.GetCanonicalGenericInstance() }));
            ITypeSignature interfaceRef = genericInstance.TranslateType(enhancedType.Module);

            enhancedType.InterfaceImplementations.Add(interfaceRef);
        }
        private void InjectExactlyOfType(InstructionWriter writer, ITypeSignature genericTypeInstance)
        {
            writer.EmitInstruction(OpCodeNumber.Ldarg_1);
            writer.EmitInstructionMethod(OpCodeNumber.Call, this.getTypeMethod);

            writer.EmitInstructionType(OpCodeNumber.Ldtoken, genericTypeInstance);
            writer.EmitInstructionMethod(OpCodeNumber.Call, this.getTypeFromHandleMethod);

            writer.EmitInstruction(OpCodeNumber.Ceq);
        }
        private bool IsLocalType(ITypeSignature typeSig)
        {
            typeSig = typeSig.GetDeclaringType();
            if (typeSig == null)
            {
                return(true);
            }

            return(null == typeSig.ResolutionScope);
        }
        protected virtual IType ResolveDeclaringType(ITypeSignature typeSig, IModule context)
        {
            var owner = typeSig.Owner;

            if (owner == null)
            {
                if (context.IsPrimeModule)
                {
                    return(context.Assembly.GetTypeOrExportedType(typeSig.Name, typeSig.Namespace));
                }
                else
                {
                    return(context.GetType(typeSig.Name, typeSig.Namespace));
                }
            }

            switch (owner.SignatureType)
            {
            case SignatureType.Assembly:
            {
                var assembly = ResolveAssembly((IAssemblySignature)owner, context.Module);
                if (assembly == null)
                {
                    return(null);
                }

                return(assembly.GetTypeOrExportedType(typeSig.Name, typeSig.Namespace));
            }

            case SignatureType.Module:
            {
                var module = context.Assembly.GetModule(((IModuleSignature)owner).Name);
                if (module == null)
                {
                    return(null);
                }

                return(module.GetType(typeSig.Name, typeSig.Namespace));
            }

            case SignatureType.Type:
            {
                var enclosingType = ResolveDeclaringType((ITypeSignature)owner, context);
                if (enclosingType == null)
                {
                    return(null);
                }

                return(enclosingType.GetNestedType(typeSig.Name, typeSig.Namespace));
            }

            default:
                throw new NotImplementedException();
            }
        }
Пример #22
0
        public void WriteType(Type type)
        {
            if (type.ContainsGenericParameters)
            {
                throw new InvalidOperationException("Cannot write an incomplete type. The type in question has generic parameters still.");
            }

            ITypeSignature typeSignature = _typeManager.ResolveTypeSignature(type);

            typeSignature.Write(this, type);
        }
        public FieldDefDeclaration GetCategoryField(string category, ITypeSignature fieldType, Action<InstructionWriter> initializeFieldAction )
        {
            FieldDefDeclaration categoryField;
            if (!this.categoryFields.TryGetValue(category, out categoryField))
            {
                categoryField = this.CreateCategoryField(fieldType, initializeFieldAction);
                this.categoryFields[category] = categoryField;
            }

            return categoryField;
        }
        bool IAdvice.RequiresWeave(WeavingContext context)
        {
            ITypeSignature addressType = context.StackTypeStatus.GetAt(1);

            bool weave = context.Method.DeclaringType != this.wrapperType &&
                         this.methods.ContainsKey(context.JoinPoint.Instruction.OpCodeNumber) &&
                         !((PointerTypeSignature)addressType.GetNakedType()).IsManaged;

            Console.WriteLine("method={0}, instruction={1}, address={2}, weave={3}", context.Method, context.JoinPoint.Instruction, addressType, weave);

            return(weave);
        }
        private void EmitEqualsField(InstructionWriter writer, CreatedEmptyMethod methodBody,
                                     FieldDefDeclaration field)
        {
            ITypeSignature fieldType = field.FieldType;

            if ((fieldType.GetNakedType() is IntrinsicTypeSignature sig &&
                 sig.IntrinsicType != IntrinsicType.Object &&
                 sig.IntrinsicType != IntrinsicType.String
                 ) || fieldType.IsEnum())
            {
                this.EmitSimpleValueCheck(writer, methodBody, field);
            }
        public FieldDefDeclaration GetCategoryField(string category, ITypeSignature fieldType, Action <InstructionWriter> initializeFieldAction)
        {
            FieldDefDeclaration categoryField;

            if (!this.categoryFields.TryGetValue(category, out categoryField))
            {
                categoryField = this.CreateCategoryField(fieldType, initializeFieldAction);
                this.categoryFields[category] = categoryField;
            }

            return(categoryField);
        }
        public static IAssemblySignature GetAssembly(this ITypeSignature typeSig, IModule module)
        {
            var resScope = typeSig.ResolutionScope;

            if (resScope != null && resScope.SignatureType == SignatureType.Assembly)
            {
                return((IAssemblySignature)resScope);
            }
            else
            {
                return(module.Assembly);
            }
        }
Пример #28
0
 public VariableDefinition(
     int nodeId,
     SourceSpan span,
     Token identifier,
     ITypeSignature typeSignature,
     IExpression initializer)
 {
     NodeId        = nodeId;
     Span          = span;
     Identifier    = identifier;
     TypeSignature = typeSignature;
     Initializer   = initializer;
 }
                public void Implement()
                {
                    ITypeSignature exceptionSignature = this.transformationInstance.AspectWeaver.Module.Cache.GetType(typeof(Exception));

                    bool hasOnEntry = this.options.OnEntryLevel != LogLevel.None;

                    bool hasOnSuccess = this.options.OnSuccessLevel != LogLevel.None;

                    bool hasOnException = this.options.OnExceptionLevel != LogLevel.None;

                    Implement(hasOnEntry, hasOnSuccess, false, hasOnException ? new[] { exceptionSignature } : null);
                    this.Context.AddRedirection(this.Redirection);
                }
        public static bool Equals(this ITypeSignature typeSig, IModule module, string fullName, string assemblyName)
        {
            if (typeSig.FullName != fullName)
            {
                return(false);
            }

            if (GetAssembly(typeSig, module).Name != assemblyName)
            {
                return(false);
            }

            return(true);
        }
        private void WriteMethodArguments(StringBuilder formatBuilder, int[] argumentsIndex, int startParameter, bool includeParameterName,
                                          bool includeParameterType, bool includeParameterValue, bool includeOutParams)
        {
            IMethodSignature methodSignature = this.context.MethodMapping.MethodSignature;
            int parameterCount = methodSignature.ParameterCount;

            for (int i = 0; i < parameterCount; i++)
            {
                int index = i + startParameter;

                if (index > 0)
                {
                    formatBuilder.Append(", ");
                }

                bool isOut = this.targetMethod.Parameters[i].Attributes.HasFlag(ParameterAttributes.Out);
                bool isRef = this.targetMethod.Parameters[i].ParameterType is PointerTypeSignature;

                ITypeSignature parameterType = methodSignature.GetParameterType(i);

                if (includeParameterType)
                {
                    string typeName = parameterType.GetReflectionName(ReflectionNameOptions.MethodParameterContext, NameShortener.Instance);
                    if (isRef)
                    {
                        typeName = string.Format("{0} {1}", (isOut ? "out" : "ref"), typeName.Remove(typeName.Length - 6));  //Remove 'ByRef' suffix
                    }
                    formatBuilder.Append(typeName);
                }

                if (includeParameterName)
                {
                    formatBuilder.AppendFormat(" {0}", this.context.MethodMapping.MethodMappingInformation.GetParameterName(i));
                }



                if ((includeOutParams || !isOut) && includeParameterValue)
                {
                    if (includeParameterName || includeParameterType)
                    {
                        formatBuilder.AppendFormat(" = ");
                    }

                    AppendFormatPlaceholder(index, formatBuilder, parameterType);
                    argumentsIndex[index] = i;
                }
            }
        }
        public static ITypeSignature GetOutermostType(this ITypeSignature typeSig)
        {
            while (true)
            {
                var enclosingTypeSig = typeSig.EnclosingType;
                if (enclosingTypeSig == null)
                {
                    break;
                }

                typeSig = enclosingTypeSig;
            }

            return(typeSig);
        }
        public static ITypeSignature GetDeclaringType(this ITypeSignature typeSig)
        {
            typeSig = typeSig.GetLastElementType();
            if (typeSig.ElementCode == TypeElementCode.GenericType)
            {
                typeSig = typeSig.DeclaringType;
            }

            if (typeSig.ElementCode == TypeElementCode.DeclaringType)
            {
                return(typeSig);
            }

            return(null);
        }
 internal static bool?TryGetIsValueType(ITypeSignature typeSig)
 {
     if (typeSig is IType)
     {
         return(((IType)typeSig).IsValueType());
     }
     else if (typeSig is TypeReference)
     {
         return(((TypeReference)typeSig).IsValueType);
     }
     else
     {
         return(null);
     }
 }
Пример #35
0
        public void Initialize(ModuleDeclaration module)
        {
            this.module = module;
            this.loggingImplementation = new LoggingImplementationTypeBuilder(module);
            this.loggerType = module.FindType(typeof(Logger));

            LoggerMethodsBuilder builder = new LoggerMethodsBuilder(module, this.loggerType);

            this.categoryInitializerMethod = module.FindMethod(module.FindType(typeof(LogManager)), "GetLogger",
                method => method.Parameters.Count == 1 && IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String) );

            this.loggerMethods[LogLevel.Debug] = builder.CreateLoggerMethods("Trace");
            this.loggerMethods[LogLevel.Info] = builder.CreateLoggerMethods("Info");
            this.loggerMethods[LogLevel.Warning] = builder.CreateLoggerMethods("Warn");
            this.loggerMethods[LogLevel.Error] = builder.CreateLoggerMethods("Error");
            this.loggerMethods[LogLevel.Fatal] = builder.CreateLoggerMethods("Fatal");
        }
 private static void AppendFormatPlaceholder(int i, StringBuilder formatBuilder, ITypeSignature parameterType)
 {
     if (IntrinsicTypeSignature.Is(parameterType, IntrinsicType.String))
     {
         formatBuilder.AppendFormat("\"" + "{{{0}}}" + "\"", i);
     }
     else if (!parameterType.BelongsToClassification(TypeClassifications.Intrinsic) ||
              IntrinsicTypeSignature.Is(parameterType, IntrinsicType.Object))
     {
         formatBuilder.Append("{{");
         formatBuilder.AppendFormat("{{{0}}}", i);
         formatBuilder.Append("}}");
     }
     else
     {
         formatBuilder.AppendFormat("{{{0}}}", i);
     }
 }
        private FieldDefDeclaration CreateCategoryField(ITypeSignature fieldType, Action<InstructionWriter> initializeFieldAction)
        {
            string fieldName = string.Format("l{0}", this.containingType.Fields.Count + 1);

            FieldDefDeclaration loggerFieldDef = new FieldDefDeclaration
            {
                Name = fieldName,
                Attributes = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.InitOnly,
                FieldType = fieldType
            };
            this.containingType.Fields.Add(loggerFieldDef);

            InstructionSequence sequence = this.constructorBlock.AddInstructionSequence(null,
                                                                                        NodePosition.Before,
                                                                                        this.returnSequence);

            this.writer.AttachInstructionSequence(sequence);
            initializeFieldAction(this.writer);
            this.writer.EmitInstructionField(OpCodeNumber.Stsfld, loggerFieldDef);
            this.writer.DetachInstructionSequence();

            return loggerFieldDef;
        }
        public LoggerMethodsBuilder(ModuleDeclaration module, ITypeSignature loggerType)
        {
            this.module = module;
            this.loggerType = loggerType;

            // matches XXX(string)
            this.objectPredicate = method => method.Parameters.Count == 1 &&
                                             IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.Object);

            // matches XXX(string format, object arg)
            this.format1Predicate = method => method.Parameters.Count == 2 &&
                                              IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String) &&
                                              IntrinsicTypeSignature.Is(method.Parameters[1].ParameterType, IntrinsicType.Object);

            // matches XXX(string format, object arg0, object arg1)
            this.format2Predicate = 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);

            // matches XXX(string format, object arg0, object arg1, object arg2)
            this.format3Predicate = 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);

            // matches XXX(string format, params object[] args)
            this.formatArrayPredicate = method => method.Parameters.Count == 2 &&
                                                  IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String) &&
                                                  method.Parameters[1].ParameterType.BelongsToClassification(TypeClassifications.Array);

            this.objectExceptionPredicate = method => method.Parameters.Count == 2 &&
                                                      IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.Object) &&
                                                      method.Parameters[1].ParameterType.MatchesReference(module.Cache.GetType(typeof(Exception)));
        }
 protected override void ImplementOnException(InstructionBlock block, ITypeSignature exceptionType, InstructionWriter writer)
 {
 }
 public static void Get_RuntimeType(this InstructionWriter instructionWriter, ITypeSignature type, WeavingHelper weavingHelper)
 {
     weavingHelper.GetRuntimeType(type, instructionWriter);
 }
 public static void New_EmptyArray(this InstructionWriter instructionWriter, ITypeSignature type)
 {
     instructionWriter.EmitInstruction(OpCodeNumber.Ldc_I4_0);
     instructionWriter.EmitInstructionType(OpCodeNumber.Newarr, type);
 }
        private static void EmitBoxIfNeeded(InstructionWriter instructionWriter, ITypeSignature type)
        {
            var isStruct = type.IsStruct();
            if (!isStruct)
                return;

            instructionWriter.EmitInstructionType(OpCodeNumber.Box, type);
        }
 public static void Cast_ToType(this InstructionWriter instructionWriter, ITypeSignature type)
 {
     instructionWriter.EmitInstructionType(OpCodeNumber.Castclass, type);
 }
Пример #44
0
        public static PropertyDeclaration ImplementPublicProperty(
            this TypeDefDeclaration type,
            string name,
            ITypeSignature propertyType,
            MethodAttributes extraAttributes,
            IEnumerable<CustomAttributeDeclaration> propertyAttributes,
            CustomAttributeDeclaration compilerGenerated)
        {
            var field = CreateBackingField(type, name, propertyType, compilerGenerated);

            var property = CreateProperty(type, name, propertyType, propertyAttributes);

            var methodAttributes = MethodAttributes.Public
                                    | MethodAttributes.HideBySig
                                    | MethodAttributes.SpecialName;

            methodAttributes |= extraAttributes;

            ImplementGetter(property, type, field, methodAttributes, compilerGenerated);
            ImplementSetter(property, type, field, methodAttributes, compilerGenerated);
            return property;
        }
        protected override void Initialize()
        {
            // Target module.
              ModuleDeclaration module = this.Project.Module;

              // Prepare types and methods. They will be used later by advices.
              this.boolType = module.FindType(typeof(bool), BindingOptions.Default);
              this.objectType = module.FindType(typeof(object), BindingOptions.Default);
              this.invariantCultureGetter = module.FindMethod(typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod(), BindingOptions.Default);
              this.getLoggerByStringMethod = module.FindMethod(typeof(LogManager).GetMethod("GetLogger", new Type[] { typeof(string) }), BindingOptions.Default);
              this.registerLoggerMethod = module.FindMethod(typeof(LoggerHelper).GetMethod("RegisterLogger", new Type[] { typeof(Type) }), BindingOptions.Default);
              this.registerLoggerWithPolicyMethod = module.FindMethod(typeof(LoggerHelper).GetMethod("RegisterLogger", new Type[] { typeof(Type), typeof(LoggerNamePolicy), typeof(LoggerNamePolicy) }), BindingOptions.Default);

              this.ilogType = module.FindType(typeof(ILog), BindingOptions.Default);
              this.compilerGeneratedAttributeType = module.FindType(typeof(CompilerGeneratedAttribute), BindingOptions.Default).GetTypeDefinition();

              // Prepare level support items for all levels.
              this.levelSupportItems[LogLevel.Debug] = this.CreateSupportItem("Debug");
              this.levelSupportItems[LogLevel.Info] = this.CreateSupportItem("Info");
              this.levelSupportItems[LogLevel.Warn] = this.CreateSupportItem("Warn");
              this.levelSupportItems[LogLevel.Error] = this.CreateSupportItem("Error");
              this.levelSupportItems[LogLevel.Fatal] = this.CreateSupportItem("Fatal");
        }
 public InterfaceImplementationTreeNode(ITypeSignature type)
     :
     base( TreeViewImage.Interface, type )
 {
     this.Text = type.ToString();
 }
                protected override void ImplementOnException(InstructionBlock block, ITypeSignature exceptionType, InstructionWriter writer)
                {
                    //// TODO: nested types

                    int[] argumentsIndex;
                    string messageFormatString;

                    if (this.options.OnExceptionOptions != LogOptions.None)
                    {
                        string messageArgumentsFormatString = this.argumentsFormatter.CreateMessageArguments(this.options.OnExceptionOptions, false, out argumentsIndex);
                        messageFormatString = "An exception occurred in " + messageArgumentsFormatString + ":\n{" + argumentsIndex.Length + "}";
                    }
                    else
                    {
                        argumentsIndex = new int[0];
                        messageFormatString = "An exception occurred:\n{0}";
                    }

                    this.EmitMessage(block, writer, this.options.OnExceptionLevel, messageFormatString, argumentsIndex, exceptionType);

                    writer.EmitInstruction(OpCodeNumber.Rethrow);
                    writer.DetachInstructionSequence();
                }
Пример #48
0
 public static PropertyDeclaration ImplementPublicProperty(
     this TypeDefDeclaration type,
     string name,
     ITypeSignature propertyType,            
     CustomAttributeDeclaration compilerGenerated)
 {
     return ImplementPublicProperty(type, name, propertyType, 0, null, compilerGenerated);
 }
        /// <summary>
        /// Creates a private static readonly field.
        /// </summary>
        /// <param name="name">Name of the field.</param>
        /// <param name="type">Type of the field.</param>
        /// <returns>Private static readonly field of the specified type.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="name"/> or <paramref name="type"/> is <see langword="null"/>.</exception>
        private static FieldDefDeclaration CreateField(string name, ITypeSignature type)
        {
            if (name == null)
              {
            throw new ArgumentNullException("name");
              }
              if (type == null)
              {
            throw new ArgumentNullException("type");
              }

              FieldDefDeclaration field = new FieldDefDeclaration();
              field.Attributes = FieldAttributes.InitOnly | FieldAttributes.Private | FieldAttributes.Static;
              field.Name = name;
              field.FieldType = type;
              return field;
        }
 public EnhancePropertySetterMethodBodyWrappingImplementation(IPropertyTransformationContext transformationContext, AspectInfrastructureTask task, MethodBodyTransformationContext context)
     : base(task, context)
 {
     if (transformationContext == null) throw new ArgumentNullException("transformationContext");
     _transformationContext = transformationContext;
     _assets =
         _transformationContext.Module.Cache.GetItem(
             () => new TransformationAssets(_transformationContext.Module));
     _stringTypeSignature = _transformationContext.Module.Cache.GetIntrinsic(typeof(string));
 }
                private void EmitMessage(InstructionBlock block, InstructionWriter writer,
                    LogLevel logLevel, string messageFormatString, int[] arguments, ITypeSignature exceptionType = null)
                {
                    MethodDefDeclaration targetMethod = Context.TargetElement as MethodDefDeclaration;
                    if (targetMethod == null)
                    {
                        return;
                    }

                    // TODO: nested types
                    string category = targetMethod.DeclaringType.Name;
                    ILoggingCategoryBuilder builder = this.backendInstance.GetCategoryBuilder(category);

                    InstructionSequence sequence = block.AddInstructionSequence(null, NodePosition.After, null);
                    writer.AttachInstructionSequence(sequence);

                    LocalVariableSymbol exceptionLocal = null;
                    if (exceptionType != null)
                    {
                        exceptionLocal = block.MethodBody.RootInstructionBlock.DefineLocalVariable(
                        exceptionType, DebuggerSpecialNames.GetVariableSpecialName("ex"));
                    }

                    if (builder.SupportsIsEnabled)
                    {
                        builder.EmitGetIsEnabled(writer, logLevel);
                        InstructionSequence branchSequence = block.AddInstructionSequence(null, NodePosition.After, sequence);
                        writer.EmitBranchingInstruction(OpCodeNumber.Brfalse_S, branchSequence);
                    }

                    bool useWrapper = ShouldUseWrapper(targetMethod);

                    Action<InstructionWriter> getExceptionAction = exceptionLocal != null ? (Action<InstructionWriter>)(w => w.EmitInstructionLocalVariable(OpCodeNumber.Stloc, exceptionLocal)) : null;

                    builder.EmitWrite(writer,
                        messageFormatString,
                        exceptionType == null ? arguments.Length : arguments.Length + 1,
                        logLevel,
                        getExceptionAction,
                        (i, instructionWriter) =>
                        {
                            if (i < arguments.Length)
                            {
                                int index = arguments[i];
                                if (index == MessageArgumentsFormatter.ThisArgumentPosition)
                                {
                                    this.methodMappingWriter.EmitLoadInstance(false, instructionWriter);
                                }
                                else if (index == MessageArgumentsFormatter.ReturnParameterPosition)
                                {
                                    instructionWriter.EmitInstructionLocalVariable(OpCodeNumber.Ldloc, Context.ReturnValueVariable);
                                    instructionWriter.EmitConvertToObject(
                                        Context.MethodMapping.MethodSignature.ReturnType);
                                }
                                else
                                {
                                    this.methodMappingWriter.EmitLoadArgument(index, instructionWriter);

                                    instructionWriter.EmitConvertToObject(this.methodMappingWriter.MethodMapping.MethodSignature.GetParameterType(index).GetNakedType(TypeNakingOptions.IgnoreManagedPointers));
                                }
                            }
                            else
                            {
                                //Emit exception parameter
                                instructionWriter.EmitInstructionLocalVariable(OpCodeNumber.Ldloc, exceptionLocal);
                            }
                        },
                        useWrapper);
                    if (exceptionType == null)
                    {
                        writer.DetachInstructionSequence();
                    }
                }
Пример #52
0
 private static PropertyDeclaration CreateProperty(TypeDefDeclaration type, string name, ITypeSignature propertyType, IEnumerable<CustomAttributeDeclaration> attributesList)
 {
     var property = new PropertyDeclaration
     {
         Name = name,
         PropertyType = propertyType,
         CallingConvention = CallingConvention.HasThis,
     };
     type.Properties.Add(property);
     ImplementAttributes(property, attributesList);
     return property;
 }
Пример #53
0
        private static IField CreateBackingField(
            TypeDefDeclaration type,
            string name,
            ITypeSignature fieldType,
            CustomAttributeDeclaration compilerGenerated)
        {
            var field = new FieldDefDeclaration
            {
                Attributes = FieldAttributes.Private,
                Name = string.Format("<{0}>k__BackingField", name),
                FieldType = fieldType
            };

            // Create a backing field
            type.Fields.Add(field);
            MarkCompilerGenerated(field, compilerGenerated);
            return GenericHelper.GetCanonicalGenericInstance(field);
        }
                protected override void ImplementOnException(InstructionBlock block, ITypeSignature exceptionType, InstructionWriter writer)
                {
                    MethodDefDeclaration targetMethod = this.transformationInstance.AspectWeaverInstance.TargetElement as MethodDefDeclaration;
                    if (targetMethod == null)
                    {
                        return;
                    }

                    // TODO: nested types
                    string category = targetMethod.DeclaringType.Name;
                    ILoggingCategoryBuilder builder = this.backendInstance.GetCategoryBuilder(category);
                    InstructionSequence sequence = block.AddInstructionSequence(null, NodePosition.After, null);
                    writer.AttachInstructionSequence(sequence);

                    LocalVariableSymbol exceptionLocal = block.MethodBody.RootInstructionBlock.DefineLocalVariable(
                        exceptionType, DebuggerSpecialNames.GetVariableSpecialName("ex"));

                    LogSeverity logSeverity = LogSeverity.Warning;
                    if (builder.SupportsIsEnabled)
                    {
                        builder.EmitGetIsEnabled(writer, logSeverity);
                        InstructionSequence branchSequence = block.AddInstructionSequence(null, NodePosition.After, sequence);
                        writer.EmitBranchingInstruction(OpCodeNumber.Brfalse_S, branchSequence);
                    }

                    builder.EmitWrite(writer, block, "An exception occurred:\n{0}", 1, logSeverity,
                                      w => w.EmitInstructionLocalVariable(OpCodeNumber.Stloc, exceptionLocal),
                                      (i, w) => w.EmitInstructionLocalVariable(OpCodeNumber.Ldloc, exceptionLocal));

                    writer.EmitInstruction(OpCodeNumber.Rethrow);
                    writer.DetachInstructionSequence();
                }
Пример #55
0
 public Assets(ModuleDeclaration module)
 {
     OnThrow = module.FindMethod(typeof(OnThrowAspectAttribute).GetMethod("OnThrow", new[] { typeof(Exception) }), BindingOptions.Default);
     Exception = module.FindType(typeof(Exception));
 }