How could I search references to a field on a AST or a CompilationUnit in eclipse? - eclipse

Hi,
I'm developing an Eclipse plugin. I
need to find all the references in the
source using AST's or jdt.core.dom
or something like that. I need this
references like ASTNodes in order to
get the parent node and check several
things in the expression where
references are involved.
Thanks beforehand.
Edited:
I want to concrete a little more, My problem is that I try to catch some references to a constant but... I have not idea how I can do to catch in the matches this references. I need check the expressions which the references to a determined constant are involved. I only get the source of the method where they are used.
I think the problem is the scope or the pattern:
pattern = SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES);
scope = SearchEngine.createJavaSearchScope(declaringType.getMethods());
Thanks beforehand!

I used something like:
Search for the declaration of an
method, returns an IMethod
Search for references to the
IMethod, record those IMethods
For each IMethod returned, create an
AST from its compilation unit
Searching for declarations or references looks like the following code.
SearchRequestor findMethod = ...; // do something with the search results
SearchEngine engine = new SearchEngine();
IJavaSearchScope workspaceScope = SearchEngine.createWorkspaceScope();
SearchPattern pattern = SearchPattern.createPattern(searchString,
IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS,
SearchPattern.R_EXACT_MATCH);
SearchParticipant[] participant = new SearchParticipant[] { SearchEngine
.getDefaultSearchParticipant() };
engine.search(pattern, participant, workspaceScope, findMethod,
monitor);
Once you have your IMethod references, you can get to the AST using:
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
if (methodToSearch.isBinary()) {
parser.setSource(methodToSearch.getClassFile());
} else {
parser.setSource(methodToSearch.getCompilationUnit());
}
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
See http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_int_core.htm for more details on java search, the java model, and the AST.

Related

Get elements of list beginning with specific letter

I have a list of words allWords and I am trying to create a new list from allWords containing only those words that begin with a specific letter currLetter. Looking at the docs, collection.map() seems like a great choice. However the statement below won't compile since .starts(with: ) returns a boolean.
targetWords = allWords.map { $0.starts(with: currLetter) }
Can anyone point me in the right direction?
While not described in the documentation of collection type instance methods, the solution is to use filter() instead of map():
targetWords = allWords.filter { $0.starts(with: currLetter) }

FSharpLint, how to use the rule "InterfaceNamesMustBeginWithI" in SuppressMessageAttribute?

[<SuppressMessage("NameConventions","InterfaceNamesMustBeginWithI")>] //No effect
[<SuppressMessage("NameConventions","InterfaceNames")>] //It's working
module Test=
type [<AllowNullLiteral>] MutationEvent =
abstract attrChange: float with get, set
...
Also, failed to search source code about "InterfaceNamesMustBeginWithI".
The name of the rule is InterfaceNames, so you can suppress it thus:
[<SuppressMessage("","InterfaceNames")>]
module Test =
...
Also note that the first argument to SuppressMessage is not used by fsharplint, so it can be anything (although not null, strangely enough!)
There are pointers to InterfaceNamesMustBeginWithI in the documentation, but this is not correct.

Resolve bindings for new created types?

I am developing an Eclipse plug-in to refactor Java source code with JDT. I create some new classes, but experienced problems with the resolving of these new types. Therefore is my question: is it possible to resolve new created types without reparsing them?
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setResolveBindings(true);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(existingCompilationUnit);
CompilationUnit unit = (CompilationUnit)parser.createAST(null);
AST ast = unit.getAST();
// create a new type
TypeDeclaration newCreatedType = ast.newTypeDeclaration();
// fill type declaration with methods, fields, etc.
// ...
// create new compilation unit for the new type
CompilationUnit newCreatedCompilationUnit = ast.newCompilationUnit();
newCreatedCompilationUnit.types().add(newCreatedType);
newCreatedType.resolveBinding(); // returns null
It is of course possible to reparse it, but then it is contained within another AST, which causes problems when I try to rewrite elements of the AST:
parser.setSource(newCreatedCompilationUnit);
CompilationUnit newParsedCompilationUnit = (CompilationUnit)parser.createAST(null);
TypeDeclaration newParsedType = (TypeDeclaration)newParsedCompilationUnit.types().get(0);
newParsedType.resolveBinding() // returns a correct binding, but newParsedType.getAST() != ast
Then I tried to copy the new type to the old AST, which corrects the AST, but the binding informations are lost again:
CompilationUnit copiedCompilationUnit = (CompilationUnit) newUnit.copySubtree(ast, newParsedCompilationUnit);
// (copiedCompilationUnit.getAST() == ast) is true
TypeDeclaration copiedType = (TypeDeclaration)copiedCompilationUnit.types().get(0);
copiedType.resolveBinding() // returns null
By now I must decide between no binding or the wrong AST and I cannot find a solution to that.

Detecting direct instantiation with nDepend

With the nDepend API, would something like the following be possible?
I want to keep a watch out for instances where our object factory has been bypassed and a concrete class is being instantiated directly.
Obviously I'd need to be able to filter out things like:
StringBuilder stringBuilder = new StringBuilder();
perhaps by adding to the Where clause type names to exclude, or namespaces in which to check, but I want to make sure we see:
IMyCustomType item = ObjectFactory.Get<IMyCustomType>();
and not this:
MyCustomType item = new MyCustomType();
Thanks.
Maybe such code rule below could help you, hopefully it is understandable enough to not have to comment it:
warnif count > 0
let ctors = Application.Namespaces.WithNameLike("Namespaces1*").ChildMethods().Where(m => m.IsConstructor)
let codeThatMustNotCallCtors = Application.Namespaces.WithNameLike("Namespaces2*").ChildMethods()
from m in codeThatMustNotCallCtors.UsingAny(ctors)
select new { m, ctorsCalled = m.MethodsCalled.Intersect(ctors ) }

How to support custom options with protobuf-net?

I use protobuf-net and ProtoGen.exe to parse following .proto file (given by another project)
enum RGBFlags { FLAG_RED = 1; FLAG_GREEN = 2; FLAG_BLUE = 4; }
message SomeMessage {
// Values from RGBFlags only allowed
optional int32 flags = 2;
}
My fellow programmers in C++ don't care about type safety and treat flags field as a plain integer. I wanted to be more strict and try to avoid such code:
SomeMessage foo = new SomeMessage();
foo.flags = (int)RGBFlags.FLAG_BLUE | (int)RGBFlags.FLAG_GREEN;
I thought that I could use protbuf custom options to amend proto code and modify XSLT transform of ProtoGet to generate necessary `[Flags]' annotations.
extend google.protobuf.EnumOptions {
optional bool generate_bit_field = 60000;
}
enum RGBFlags {
option (generate_bit_field) = true;
FLAG_RED = 1; FLAG_GREEN = 2; FLAG_BLUE = 4;
}
message SomeMessage {
// Values from RGBFlags only allowed
optional int32 flags = 2;
}
Problem is that all custom options appear as uninterpreted_option in the temporary file in ProtoGen.
Any idea what I could do to get [Flags] annotations in my code?
Re flags; the raw protobuf spec doesn't really have support for composite enum values, so in some ways I understand why they are doing it that way. And sadly there is no such this as partial enum, so you can't add the [Flags] in a separate code file.
Re custom options; it is an excellent question, and support for custom options has been raised before. It is definitely something I'd like to add, but relative to other features it simply isn't a massively demanded item, so (due to limited resource) it has not (yet) been investigated fully.
Therefore, I don't have a great answer for you; that feature isn't really there much right now. You could hard-code that one scenario in your xslt (for your specific types). Or wait until I get around to it (I don't have a specific timescale). Or take a peek yourself.