public static MemberInfo FindMember(Expression expr) { var visitor = new MemberFinder(); visitor.Visit(expr); return(visitor.Member); }
public void Blah() { MemberHasAttributeMatcher matcher = new MemberHasAttributeMatcher("CodeWeaving.Matcher.SampleCode.SuperDuperAttribute"); AssemblyDefinition assembly = AssemblyFactory.GetAssembly(GetType().Assembly.Location); MemberFinder memberFinder = new MemberFinder(); FindMemberUsages findMemberUsages = new FindMemberUsages(); foreach (MemberReference member in memberFinder.FindMembers(assembly, matcher)) { PropertyDefinition property = member as PropertyDefinition; if (property != null) { Console.WriteLine("Found: {0}", property); foreach (MemberUsage usage in findMemberUsages.FindUsages(assembly, property.GetMethod)) { Console.WriteLine("Usage: {0}", usage.MethodDefinition); CodeInspector codeInspector = new CodeInspector(); codeInspector.Inspect(usage.MethodDefinition, _mocks.DynamicMock <IInspectionVisitor>()); ControlFlowGraph controlFlowGraph = FlowGraphFactory.CreateControlFlowGraph(usage.MethodDefinition); // ActionFlowGraph actionFlowGraph = FlowGraphFactory.CreateActionFlowGraph(controlFlowGraph); StringWriter writer = new StringWriter(); FormatControlFlowGraph(writer, controlFlowGraph); Console.WriteLine(writer.ToString()); } } } }
public void IncludeWith <TEntity>(Expression <Func <TEntity, object> > fnMember) where TEntity : IEntity { foreach (var member in MemberFinder.Find(fnMember)) { included.Add(member); } }
public static IEnumerable <MemberInfo> Find(Expression expression) { var mf = new MemberFinder(); mf.Visit(expression); return(mf.members); }
public static string Find(Expression expression) { var finder = new MemberFinder(); finder.Visit(expression); return(string.Join(".", finder.names)); }
GetAttributedMembers <TMemberInfoType, TAttributeType>(object target, MemberFinder <TMemberInfoType> memberFinder) where TMemberInfoType : MemberInfo where TAttributeType : InstrumentationBaseAttribute { Dictionary <string, List <TMemberInfoType> > memberInfoList = new Dictionary <string, List <TMemberInfoType> >(); Type type = target.GetType(); MemberInfo[] memberInfos = memberFinder(type); foreach (MemberInfo memberInfo in memberInfos) { object[] attributes = memberInfo.GetCustomAttributes(typeof(TAttributeType), false); foreach (InstrumentationBaseAttribute attribute in attributes) { if (memberInfoList.ContainsKey(attribute.SubjectName) == false) { memberInfoList.Add(attribute.SubjectName, new List <TMemberInfoType>()); } List <TMemberInfoType> list = memberInfoList[attribute.SubjectName]; list.Add((TMemberInfoType)memberInfo); } } return(memberInfoList); }
/// <summary> /// Initializes the drawer by resolving any optional references to members for min/max value. /// </summary> protected override void Initialize() { MemberInfo member; // Min member reference. if (Attribute.MinMember != null) { if (MemberFinder.Start(Property.ParentType) .IsNamed(Attribute.MinMember) .HasNoParameters() .TryGetMember(out member, out errorMessage)) { var type = member.GetReturnType(); if (type == typeof(int)) { intMinGetter = new InspectorPropertyValueGetter <int>(Property, Attribute.MinMember); } else if (type == typeof(float)) { floatMinGetter = new InspectorPropertyValueGetter <float>(Property, Attribute.MinMember); } } } // Max member reference. if (Attribute.MaxMember != null) { if (MemberFinder.Start(Property.ParentType) .IsNamed(Attribute.MaxMember) .HasNoParameters() .TryGetMember(out member, out errorMessage)) { var type = member.GetReturnType(); if (type == typeof(int)) { intMaxGetter = new InspectorPropertyValueGetter <int>(Property, Attribute.MaxMember); } else if (type == typeof(float)) { floatMaxGetter = new InspectorPropertyValueGetter <float>(Property, Attribute.MaxMember); } } } // Min max member reference. if (Attribute.MinMaxMember != null) { vector2IntMinMaxGetter = new InspectorPropertyValueGetter <Vector2Int>(Property, Attribute.MinMaxMember); if (errorMessage != null) { errorMessage = vector2IntMinMaxGetter.ErrorMessage; } } }
/// <summary> /// Creates a StringMemberHelper to get a display string. /// </summary> /// <param name="property">The property.</param> /// <param name="memberName">The member name.</param> /// <param name="allowInstanceMember">If <c>true</c>, then StringMemberHelper will look for instance members.</param> /// <param name="allowStaticMember">If <c>true</c>, then StringMemberHelper will look for static members.</param> /// <exception cref="System.InvalidOperationException">Require either allowInstanceMember or allowStaticMember to be true.</exception> public InspectorPropertyValueGetter(InspectorProperty property, string memberName, bool allowInstanceMember = true, bool allowStaticMember = true) { this.memberProperty = property.FindParent(x => x.Info.GetMemberInfo() != null, true); // TODO: Expression temporarily disabled. //if (memberName != null && memberName.Length > 0 && memberName[0] == '$') //{ // var expression = memberName.Substring(1); // this.isStaticExpression = property.ParentValueProperty == null && property.Tree.IsStatic; // this.expressionMethod = ExpressionCompilerUtility.CompileExpression(expression, this.isStaticExpression, property.ParentType, out this.errorMessage); // if (this.expressionMethod != null && this.expressionMethod.Method.ReturnType.IsCastableTo(typeof(TReturnType)) == false) // { // this.errorMessage = "Cannot cast type of " + this.expressionMethod.Method.ReturnType + " to type of " + typeof(TReturnType).Name + "."; // this.expressionMethod = null; // } //} //else { var parentType = this.memberProperty.ParentType; var finder = MemberFinder.Start(parentType) .HasReturnType <TReturnType>(true) .IsNamed(memberName) .HasNoParameters(); if (!allowInstanceMember && !allowStaticMember) { throw new InvalidOperationException("Require either allowInstanceMember and/or allowStaticMember to be true."); } else if (!allowInstanceMember) { finder.IsStatic(); } else if (!allowStaticMember) { finder.IsInstance(); } MemberInfo member; if (finder.TryGetMember(out member, out this.errorMessage)) { if (member is MethodInfo) { memberName += "()"; } if (member.IsStatic()) { this.staticValueGetter = DeepReflection.CreateValueGetter <TReturnType>(parentType, memberName); } else { this.instanceValueGetter = DeepReflection.CreateWeakInstanceValueGetter <TReturnType>(parentType, memberName); } } } }
public void ShouldIgnoreASetMethod() { var member = MemberFinder .GetSourceMembers(typeof(PublicSetMethod <short>)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldBeNull(); }
public void ShouldIgnoreAWriteOnlyPublicProperty() { var member = MemberFinder .GetSourceMembers(typeof(PublicWriteOnlyProperty <long>)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldBeNull(); }
public void ShouldFindARootArrayElement() { var member = MemberFinder .GetSourceMembers(typeof(int[])) .FirstOrDefault(); member.ShouldNotBeNull(); }
public void ShouldIgnoreAPropertyGetter() { var member = MemberFinder .GetSourceMembers(typeof(PublicProperty <string>)) .FirstOrDefault(m => m.Name.StartsWith("get_")); member.ShouldBeNull(); }
public void ShouldIgnoreGetHashCode() { var member = MemberFinder .GetSourceMembers(typeof(PublicProperty <DateTime?>)) .FirstOrDefault(m => m.Name == "GetHashCode"); member.ShouldBeNull(); }
public void ShouldIgnoreAReadOnlyArrayProperty() { var member = MemberFinder .GetTargetMembers(typeof(PublicReadOnlyProperty <long[]>)) .FirstOrDefault(m => m.Name.StartsWith("Value")); member.ShouldBeNull(); }
public void ShouldIgnoreAPublicReadOnlySimpleTypeProperty() { var member = MemberFinder .GetTargetMembers(typeof(PublicReadOnlyProperty <long>)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldBeNull(); }
public void ShouldIgnoreAPropertySetter() { var member = MemberFinder .GetTargetMembers(typeof(PublicProperty <long>)) .FirstOrDefault(m => m.Name.StartsWith("set_")); member.ShouldBeNull(); }
public void ShouldIgnoreAPublicReadOnlyArrayField() { var member = MemberFinder .GetTargetMembers(typeof(PublicReadOnlyField <byte[]>)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldBeNull(); }
public void ShouldIgnoreAGetMethod() { var member = MemberFinder .GetTargetMembers(typeof(PublicGetMethod <string[]>)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldBeNull(); }
public void ShouldIgnoreANonPublicField() { var member = MemberFinder .GetTargetMembers(typeof(InternalField <List <byte> >)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldBeNull(); }
public void ShouldFindAPublicProperty() { var member = MemberFinder .GetSourceMembers(typeof(PublicProperty <string>)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldNotBeNull(); member.Type.ShouldBe(typeof(string)); }
protected override void DrawPropertyLayout(InspectorProperty property, OnClickMethodAttribute attribute, GUIContent label) { // Get context object for the current property. PropertyContext <OnClickContext> contextBuffer = property.Context.Get <OnClickContext>(this, "OnClickContext", (OnClickContext)null); OnClickContext context = contextBuffer.Value; // The context has been configured to null. So we initialize the context value the first time the property is drawn. if (context == null) { // Create the context and store the value in the buffer object. context = new OnClickContext(); contextBuffer.Value = context; // Use MemberFinder to find the specified method, and store the method info in the context object. context.Method = MemberFinder.Start(property.ParentType) .IsMethod() .HasNoParameters() .IsNamed(attribute.MethodName) .GetMember <MethodInfo>(out contextBuffer.Value.ErrorMessage); } // Display any error that might have occured. if (context.ErrorMessage != null) { SirenixEditorGUI.ErrorMessageBox(context.ErrorMessage); // Continue drawing the rest of the property as normal. this.CallNextDrawer(property, label); } else { // Get the mouse down event. bool clicked = Event.current.rawType == EventType.MouseDown && Event.current.button == 0 && property.LastDrawnValueRect.Contains(Event.current.mousePosition); if (clicked) { // Invoke the method stored in the context object. if (context.Method.IsStatic) { context.Method.Invoke(null, null); } else { context.Method.Invoke(property.ParentValues[0], null); } } // Draw the property. this.CallNextDrawer(property, label); if (clicked) { // If the event havn't been used yet, then use it here. Event.current.Use(); } } }
public void ShouldFindAPublicField() { var member = MemberFinder .GetSourceMembers(typeof(PublicField <int>)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldNotBeNull(); member.Type.ShouldBe(typeof(int)); }
public void ShouldFindAPublicGetMethod() { var member = MemberFinder .GetSourceMembers(typeof(PublicGetMethod <DateTime>)) .FirstOrDefault(m => m.Name == "GetValue"); member.ShouldNotBeNull(); member.Type.ShouldBe(typeof(DateTime)); }
public void ShouldFindAPublicProperty() { var member = MemberFinder .GetTargetMembers(typeof(PublicProperty <byte>)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldNotBeNull(); member.Type.ShouldBe(typeof(byte)); }
/// <summary> /// 将 <paramref name="member"/> 替换为具体的成员。 /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="member">成员名称。</param> /// <param name="expression">一个 <see cref="MemberExpression"/>。</param> /// <returns></returns> public SortDefinition Replace <TSource>(string member, Expression <Func <TSource, object> > expression) { if (Member == member) { Member = MemberFinder.Find(expression); } return(this); }
protected override void Initialize() { // Use MemberFinder to find the specified method, and store the method info in the context object. this.Method = MemberFinder.Start(this.Property.ParentType) .IsMethod() .HasNoParameters() .IsNamed(this.Attribute.MethodName) .GetMember <MethodInfo>(out this.ErrorMessage); }
public void ShouldFindAPublicReadOnlyComplexTypeProperty() { var member = MemberFinder .GetTargetMembers(typeof(PublicReadOnlyProperty <object>)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldNotBeNull(); member.Type.ShouldBe(typeof(object)); member.IsWriteable.ShouldBeFalse(); }
public void ShouldFindAPublicSetMethod() { var member = MemberFinder .GetTargetMembers(typeof(PublicSetMethod <DateTime>)) .FirstOrDefault(m => m.Name == "SetValue"); member.ShouldNotBeNull(); member.Type.ShouldBe(typeof(DateTime)); member.IsWriteable.ShouldBeTrue(); }
public void ShouldFindAPublicReadOnlyField() { var member = MemberFinder .GetTargetMembers(typeof(PublicReadOnlyField <IEnumerable <byte> >)) .FirstOrDefault(m => m.Name == "Value"); member.ShouldNotBeNull(); member.Type.ShouldBe(typeof(IEnumerable <byte>)); member.IsWriteable.ShouldBeFalse(); }
public override ValueProvider <TResult> TryEvaluate(TContext context, string reference) { if (string.IsNullOrEmpty(reference) == false && (this.Settings.RequireSymbolForMemberReferences == false || reference[0] == '$')) { string error; MethodInfo method; var name = reference.TrimStart('$'); if (MemberFinder.Start(context.GetParentType()) .IsMethod() .HasNoParameters() .HasConvertableReturnType <TResult>() .IsNamed(name) .TryGetMember <MethodInfo>(out method, out error)) { bool isStatic = method.IsStatic(); Func <object, TResult> methodCaller; if (isStatic) { // TODO: Emit methodCaller = instance => { return(ConvertUtility.Convert <TResult>(method.Invoke(null, null))); }; } else { // TODO: Emit methodCaller = instance => { if (instance == null) { throw new NullReferenceException(); } return(ConvertUtility.Convert <TResult>(method.Invoke(instance, null))); }; } return(new FuncValueProvider <TResult>(context, isStatic == false, methodCaller)); } else { context.LogFailInfoFormat(this, " - {0} {1}", typeof(TResult).GetNiceName(), name); return(null); } } else { return(null); } }
public override void ParseAndAnalyzeCompilationUnit(string fname, string text, int line, int col, ErrorNodeList errors, Compilation compilation, AuthoringSink sink) { if (fname == null || text == null || errors == null || compilation == null){Debug.Assert(false); return;} if (compilation != null && compilation.CompilerParameters is SpecSharpCompilerOptions) this.allowSpecSharpExtensions = !((SpecSharpCompilerOptions)compilation.CompilerParameters).Compatibility; CompilationUnitList compilationUnitSnippets = compilation.CompilationUnits; if (compilationUnitSnippets == null){Debug.Assert(false); return;} //Fix up the CompilationUnitSnippet corresponding to fname with the new source text CompilationUnitSnippet cuSnippet = this.GetCompilationUnitSnippet(compilation, fname); if (cuSnippet == null) return; Compiler compiler = new Compiler(); compiler.CurrentCompilation = compilation; cuSnippet.SourceContext.Document = compiler.CreateDocument(fname, 1, new DocumentText(text)); cuSnippet.SourceContext.EndPos = text.Length; //Parse all of the compilation unit snippets Module symbolTable = compilation.TargetModule = compiler.CreateModule(compilation.CompilerParameters, errors); AttributeList assemblyAttributes = symbolTable is AssemblyNode ? symbolTable.Attributes : null; AttributeList moduleAttributes = symbolTable is AssemblyNode ? ((AssemblyNode)symbolTable).ModuleAttributes : symbolTable.Attributes; int n = compilationUnitSnippets.Count; for (int i = 0; i < n; i++){ CompilationUnitSnippet compilationUnitSnippet = compilationUnitSnippets[i] as CompilationUnitSnippet; if (compilationUnitSnippet == null){Debug.Assert(false); continue;} Document doc = compilationUnitSnippet.SourceContext.Document; doc = compilationUnitSnippet.SourceContext.Document; if (doc == null || doc.Text == null){Debug.Assert(false); continue;} IParserFactory factory = compilationUnitSnippet.ParserFactory; if (factory == null) continue; compilationUnitSnippet.Nodes = null; compilationUnitSnippet.PreprocessorDefinedSymbols = null; IParser p = factory.CreateParser(doc.Name, doc.LineNumber, doc.Text, symbolTable, compilationUnitSnippet == cuSnippet ? errors : new ErrorNodeList(), compilation.CompilerParameters); if (p == null){Debug.Assert(false); continue;} if (p is ResgenCompilerStub) continue; Parser specSharpParser = p as Parser; if (specSharpParser == null) p.ParseCompilationUnit(compilationUnitSnippet); else specSharpParser.ParseCompilationUnit(compilationUnitSnippet, compilationUnitSnippet != cuSnippet, false); //TODO: this following is a good idea only if the files will not be frequently reparsed from source //StringSourceText stringSourceText = doc.Text.TextProvider as StringSourceText; //if (stringSourceText != null && stringSourceText.IsSameAsFileContents) // doc.Text.TextProvider = new CollectibleSourceText(doc.Name, doc.Text.Length); } //Construct symbol table for entire project ErrorHandler errorHandler = new ErrorHandler(errors); SpecSharpCompilation ssCompilation = new SpecSharpCompilation(); TrivialHashtable ambiguousTypes = new TrivialHashtable(); TrivialHashtable referencedLabels = new TrivialHashtable(); TrivialHashtable scopeFor = this.scopeFor = new TrivialHashtable(); Scoper scoper = new Scoper(scopeFor); scoper.currentModule = symbolTable; Looker symLooker = new Looker(null, new ErrorHandler(new ErrorNodeList(0)), scopeFor, ambiguousTypes, referencedLabels); symLooker.currentAssembly = (symLooker.currentModule = symbolTable) as AssemblyNode; Looker looker = new Looker(null, errorHandler, scopeFor, ambiguousTypes, referencedLabels); looker.currentAssembly = (looker.currentModule = symbolTable) as AssemblyNode; looker.VisitAttributeList(assemblyAttributes); bool dummyCompilation = compilation.CompilerParameters is SpecSharpCompilerOptions && ((SpecSharpCompilerOptions)compilation.CompilerParameters).DummyCompilation; if (dummyCompilation){ //This happens when there is no project. In this case, semantic errors should be ignored since the references and options are unknown. //But proceed with the full analysis anyway so that some measure of Intellisense can still be provided. errorHandler.Errors = new ErrorNodeList(0); } for (int i = 0; i < n; i++){ CompilationUnit cUnit = compilationUnitSnippets[i]; scoper.VisitCompilationUnit(cUnit); } for (int i = 0; i < n; i++){ CompilationUnit cUnit = compilationUnitSnippets[i]; if (cUnit == cuSnippet) looker.VisitCompilationUnit(cUnit); //Uses real error message list and populate the identifier info lists else symLooker.VisitCompilationUnit(cUnit); //Errors are discarded } //Run resolver over symbol table so that custom attributes on member signatures are known and can be used //to error check the the given file. TypeSystem typeSystem = new TypeSystem(errorHandler); Resolver resolver = new Resolver(errorHandler, typeSystem); resolver.currentAssembly = (resolver.currentModule = symbolTable) as AssemblyNode; Resolver symResolver = new Resolver(new ErrorHandler(new ErrorNodeList(0)), typeSystem); symResolver.currentAssembly = resolver.currentAssembly; symResolver.VisitAttributeList(assemblyAttributes); for (int i = 0; i < n; i++) { CompilationUnit cUnit = compilationUnitSnippets[i]; if (cUnit == cuSnippet) resolver.VisitCompilationUnit(cUnit); //Uses real error message list and populate the identifier info lists else symResolver.VisitCompilationUnit(cUnit); //Errors are discarded } if (dummyCompilation) return; //Now analyze the given file for errors Checker checker = new Checker(ssCompilation, errorHandler, typeSystem, scopeFor, ambiguousTypes, referencedLabels); checker.currentAssembly = (checker.currentModule = symbolTable) as AssemblyNode; checker.VisitAttributeList(assemblyAttributes, checker.currentAssembly); checker.VisitModuleAttributes(moduleAttributes); checker.VisitCompilationUnit(cuSnippet); MemberFinder finder = new MemberFinder(line, col); finder.VisitCompilationUnit(cuSnippet); Node node = finder.Member; if (node == null){ if (line == 0 && col == 0) node = cuSnippet; else return; } SpecSharpCompilerOptions options = (SpecSharpCompilerOptions) compilation.CompilerParameters; if (options.IsContractAssembly) return; ssCompilation.RunPlugins(node, errorHandler); Normalizer normalizer = new Normalizer(typeSystem); normalizer.Visit(node); Analyzer analyzer = new Analyzer(typeSystem, compilation); analyzer.Visit(node); if (options.RunProgramVerifierWhileEditing) ssCompilation.AddProgramVerifierPlugin(typeSystem, compilation); ssCompilation.analyzer = analyzer; // make the analyzer available to plugins for access to method CFGs ssCompilation.RunPlugins(node, errorHandler); ssCompilation.analyzer = null; analyzer = null; }
public static bool ExpressionContains(IExpression expression, ITypeDefinitionMember member) { var mf = new MemberFinder(member); mf.Traverse(expression); return mf.found; }