use of org.python.pydev.ast.codecompletion.revisited.visitors.Definition in project Pydev by fabioz.
the class AnalysisPlugin method getDefinitionFromIInfo.
/**
* @param pointers the list where the pointers will be added (if null, a new one will be created).
* @param manager the manager to be used to get the definition.
* @param nature the nature to be used.
* @param info the info that we are looking for.
* @param force whether we should force getting the ItemPointer if it's not readily available.
* @return whether we actually tried to look for a completion or just bailed out due to force being == false.
*/
public static boolean getDefinitionFromIInfo(List<ItemPointer> pointers, ICodeCompletionASTManager manager, IPythonNature nature, IInfo info, ICompletionState completionCache, boolean requireIDefinition, boolean force) {
if (pointers == null) {
pointers = new ArrayList<>();
}
if (!requireIDefinition) {
String file = info.getFile();
if (file != null) {
File f = new File(file);
int line = info.getLine();
int col = info.getCol();
if (line > 0 && col > 0) {
// 0 is invalid.
ItemPointer itemPointer = new ItemPointer(f, new Location(line - 1, col - 1), new Location(line - 1, col - 1), null, null, f.toURI());
pointers.add(itemPointer);
return true;
}
}
}
if (!force) {
return false;
}
IModule mod;
String tok;
mod = manager.getModule(info.getDeclaringModuleName(), nature, true, completionCache);
if (mod != null) {
if (info.getType() == IInfo.MOD_IMPORT_TYPE) {
Definition definition = new Definition(1, 1, "", null, null, mod);
PyRefactoringFindDefinition.getAsPointers(pointers, new Definition[] { definition });
return true;
}
// ok, now that we found the module, we have to get the actual definition
tok = "";
String path = info.getPath();
if (path != null && path.length() > 0) {
tok = path + ".";
}
tok += info.getName();
try {
IDefinition[] definitions = mod.findDefinition(CompletionStateFactory.getEmptyCompletionState(tok, nature, completionCache), -1, -1, nature);
if ((definitions == null || definitions.length == 0) && path != null && path.length() > 0) {
// this can happen if we have something as an attribute in the path:
// class Bar(object):
// def __init__(self):
// self.xxx = 10
//
// so, we'de get a find definition for Bar.__init__.xxx which is something we won't find
// for now, let's simply return a match in the correct context (although the correct way of doing
// it would be analyzing that context to find the match)
IDefinition[] contextDefinitions = mod.findDefinition(CompletionStateFactory.getEmptyCompletionState(path, nature, completionCache), -1, -1, nature);
if (contextDefinitions != null && contextDefinitions.length > 0) {
for (IDefinition iDefinition : contextDefinitions) {
if (iDefinition instanceof Definition) {
Definition definition = (Definition) iDefinition;
if (definition.ast instanceof FunctionDef) {
FunctionDef functionDef = (FunctionDef) definition.ast;
if (functionDef.args != null) {
exprType[] args = functionDef.args.args;
if (args != null && args.length > 0) {
// I.e.: only analyze functions with at least one argument (for self or cls).
Map<String, SourceToken> repToTokenWithArgs = new HashMap<String, SourceToken>();
HeuristicFindAttrs heuristicFindAttrs = new HeuristicFindAttrs(HeuristicFindAttrs.WHITIN_ANY, HeuristicFindAttrs.IN_ASSIGN, "", definition.module.getName(), null, repToTokenWithArgs, nature);
heuristicFindAttrs.visitFunctionDef(functionDef);
List<IToken> tokens = heuristicFindAttrs.getTokens();
List<IDefinition> newDefs = new ArrayList<>();
for (IToken iToken : tokens) {
if (info.getName().equals(iToken.getRepresentation())) {
newDefs.add(new Definition(iToken, definition.scope, definition.module));
}
}
definitions = newDefs.toArray(new IDefinition[newDefs.size()]);
}
}
}
}
}
}
}
PyRefactoringFindDefinition.getAsPointers(pointers, definitions);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return true;
}
use of org.python.pydev.ast.codecompletion.revisited.visitors.Definition in project Pydev by fabioz.
the class TddCodeGenerationQuickFixParticipant method getTddProps.
public List<ICompletionProposalHandle> getTddProps(PySelection ps, IImageCache imageCache, File f, IPythonNature nature, PyEdit edit, int offset, List<ICompletionProposalHandle> ret) {
if (ret == null) {
ret = new ArrayList<ICompletionProposalHandle>();
}
// Additional option: Generate markers for 'self.' accesses
int lineOfOffset = ps.getLineOfOffset(offset);
String lineContents = ps.getLine(lineOfOffset);
// Additional option: Generate methods for function calls
List<TddPossibleMatches> callsAtLine = ps.getTddPossibleMatchesAtLine();
if (callsAtLine.size() > 0) {
// Make sure we don't check the same thing twice.
Map<String, TddPossibleMatches> callsToCheck = new HashMap<String, TddPossibleMatches>();
for (TddPossibleMatches call : callsAtLine) {
String callString = call.initialPart + call.secondPart;
callsToCheck.put(callString, call);
}
CONTINUE_FOR: for (Map.Entry<String, TddPossibleMatches> entry : callsToCheck.entrySet()) {
// we have at least something as SomeClass(a=2,c=3) or self.bar or self.foo.bar() or just foo.bar, etc.
IPyRefactoring pyRefactoring = AbstractPyRefactoring.getPyRefactoring();
try {
TddPossibleMatches possibleMatch = entry.getValue();
String callWithoutParens = entry.getKey();
ItemPointer[] pointers = null;
PySelection callPs = null;
TddPossibleMatches lastPossibleMatchNotFound = possibleMatch;
for (int i = 0; i < 10; i++) {
// more than 10 attribute accesses in a line? No way!
lastPossibleMatchNotFound = possibleMatch;
if (i > 0) {
// We have to take 1 level out of the match... i.e.: if it was self.foo.get(), search now for self.foo.
String line = FullRepIterable.getWithoutLastPart(possibleMatch.full);
List<TddPossibleMatches> tddPossibleMatchesAtLine = ps.getTddPossibleMatchesAtLine(line);
if (tddPossibleMatchesAtLine.size() > 0) {
possibleMatch = tddPossibleMatchesAtLine.get(0);
callWithoutParens = possibleMatch.initialPart + possibleMatch.secondPart;
} else {
continue CONTINUE_FOR;
}
}
String full = possibleMatch.full;
int indexOf = lineContents.indexOf(full);
if (indexOf < 0) {
Log.log("Did not expect index < 0.");
continue CONTINUE_FOR;
}
callPs = new PySelection(ps.getDoc(), ps.getLineOffset() + indexOf + callWithoutParens.length());
RefactoringRequest request = new RefactoringRequest(f, callPs, null, nature, edit);
// Don't look in additional info.
request.setAdditionalInfo(RefactoringRequest.FIND_DEFINITION_IN_ADDITIONAL_INFO, false);
pointers = pyRefactoring.findDefinition(request);
if (((pointers != null && pointers.length > 0) || StringUtils.count(possibleMatch.full, '.') <= 1)) {
break;
}
}
if (pointers == null || callPs == null) {
continue CONTINUE_FOR;
}
if (lastPossibleMatchNotFound != null && lastPossibleMatchNotFound != possibleMatch && pointers.length >= 1) {
// Ok, as we were analyzing a string as self.bar.foo, we didn't find something in a pass
// i.e.: self.bar.foo, but we found it in a second pass
// as self.bar, so, this means we have to open the chance to create the 'foo' in self.bar.
String methodToCreate = FullRepIterable.getLastPart(lastPossibleMatchNotFound.secondPart);
int absoluteCursorOffset = callPs.getAbsoluteCursorOffset();
// +1 for the dot removed too.
absoluteCursorOffset = absoluteCursorOffset - (1 + methodToCreate.length());
PySelection newSelection = new PySelection(callPs.getDoc(), absoluteCursorOffset);
checkCreationBasedOnFoundPointers(edit, callPs, ret, possibleMatch, pointers, methodToCreate, newSelection, nature);
continue CONTINUE_FOR;
}
if (pointers.length >= 1) {
// the __init__ or something at the class level).
if (!checkInitCreation(edit, callPs, pointers, ret)) {
// This was called only when isCall == false
// Ok, if it's not a call and we found a field, it's still possible that we may want to create
// a field if it wasn't found in the __init__
boolean foundInInit = false;
for (ItemPointer p : pointers) {
Definition definition = p.definition;
try {
Object peek = definition.scope.getScopeStack().peek();
if (peek instanceof FunctionDef) {
FunctionDef functionDef = (FunctionDef) peek;
String rep = NodeUtils.getRepresentationString(functionDef);
if (rep != null && rep.equals("__init__")) {
foundInInit = true;
break;
}
}
} catch (Exception e) {
}
}
if (!foundInInit) {
checkMethodCreationAtClass(edit, pyRefactoring, callWithoutParens, callPs, ret, lineContents, possibleMatch, f, nature);
}
}
} else if (pointers.length == 0) {
checkMethodCreationAtClass(edit, pyRefactoring, callWithoutParens, callPs, ret, lineContents, possibleMatch, f, nature);
}
} catch (Exception e) {
if (onGetTddPropsError != null) {
onGetTddPropsError.call(e);
}
Log.log(e);
}
}
}
return ret;
}
use of org.python.pydev.ast.codecompletion.revisited.visitors.Definition in project Pydev by fabioz.
the class TddCodeGenerationQuickFixParticipant method checkInitCreation.
private boolean checkInitCreation(PyEdit edit, PySelection callPs, ItemPointer[] pointers, List<ICompletionProposalHandle> ret) {
for (ItemPointer pointer : pointers) {
Definition definition = pointer.definition;
if (definition != null && definition.ast instanceof ClassDef) {
ClassDef d = (ClassDef) definition.ast;
ASTEntry initEntry = findInitInClass(d);
if (initEntry == null) {
// Give the user a chance to create the __init__.
PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField();
pyCreateMethod.setCreateAs(PyCreateMethodOrField.BOUND_METHOD);
String className = NodeUtils.getRepresentationString(d);
pyCreateMethod.setCreateInClass(className);
List<String> parametersAfterCall = callPs.getParametersAfterCall(callPs.getAbsoluteCursorOffset());
String displayString = StringUtils.format("Create %s __init__ (%s)", className, definition.module.getName());
TddRefactorCompletionInModule completion = new TddRefactorCompletionInModule("__init__", tddQuickFixParticipant.imageMethod, displayString, null, displayString, IPyCompletionProposal.PRIORITY_CREATE, edit, definition.module.getFile(), parametersAfterCall, pyCreateMethod, callPs);
completion.locationStrategy = AbstractPyCreateAction.LOCATION_STRATEGY_FIRST_METHOD;
ret.add(completion);
return true;
}
}
}
return false;
}
use of org.python.pydev.ast.codecompletion.revisited.visitors.Definition in project Pydev by fabioz.
the class TddCodeGenerationQuickFixParticipant method checkCreationBasedOnFoundPointers.
public boolean checkCreationBasedOnFoundPointers(PyEdit edit, PySelection callPs, List<ICompletionProposalHandle> ret, TddPossibleMatches possibleMatch, ItemPointer[] pointers, String methodToCreate, PySelection newSelection, IPythonNature nature) throws MisconfigurationException, Exception {
CompletionCache completionCache = new CompletionCache();
for (ItemPointer pointer : pointers) {
Definition definition = pointer.definition;
try {
definition = rebaseToClassDefDefinition(nature, completionCache, definition, null);
} catch (CompletionRecursionException e) {
// Just keep going.
Log.log(e);
}
if (definition.ast instanceof ClassDef) {
ClassDef d = (ClassDef) definition.ast;
String fullName = NodeUtils.getRepresentationString(d) + "." + methodToCreate;
IToken repInModule = nature.getAstManager().getRepInModule(definition.module, fullName, nature);
if (repInModule != null) {
// System.out.println("Skipping creation of: " + fullName); //We found it, so, don't suggest it.
continue;
}
for (Boolean isCall : new Boolean[] { true, false }) {
// Give the user a chance to create the method we didn't find.
PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField();
List<String> parametersAfterCall = null;
parametersAfterCall = configCreateAsAndReturnParametersAfterCall(callPs, isCall, pyCreateMethod, parametersAfterCall, methodToCreate);
String className = NodeUtils.getRepresentationString(d);
pyCreateMethod.setCreateInClass(className);
String displayString = StringUtils.format("Create %s %s at %s (%s)", methodToCreate, pyCreateMethod.getCreationStr(), className, definition.module.getName());
TddRefactorCompletionInModule completion = new TddRefactorCompletionInModule(methodToCreate, tddQuickFixParticipant != null ? tddQuickFixParticipant.imageMethod : null, displayString, null, displayString, IPyCompletionProposal.PRIORITY_CREATE, edit, definition.module.getFile(), parametersAfterCall, pyCreateMethod, newSelection);
completion.locationStrategy = AbstractPyCreateAction.LOCATION_STRATEGY_END;
ret.add(completion);
}
return true;
}
}
return false;
}
use of org.python.pydev.ast.codecompletion.revisited.visitors.Definition in project Pydev by fabioz.
the class TddQuickFixParticipant method addProps.
@Override
public void addProps(MarkerAnnotationAndPosition markerAnnotation, IAnalysisPreferences analysisPreferences, String line, PySelection ps, int offset, IPythonNature nature, PyEdit edit, List<ICompletionProposalHandle> props) throws BadLocationException, CoreException {
if (nature == null) {
return;
}
ICodeCompletionASTManager astManager = nature.getAstManager();
if (astManager == null) {
return;
}
if (markerAnnotation.position == null) {
return;
}
IMarker marker = markerAnnotation.markerAnnotation.getMarker();
Integer id = (Integer) marker.getAttribute(AnalysisRunner.PYDEV_ANALYSIS_TYPE);
int start = markerAnnotation.position.offset;
int end = start + markerAnnotation.position.length;
ps.setSelection(start, end);
String markerContents;
try {
markerContents = ps.getSelectedText();
} catch (Exception e1) {
// Selection may be wrong.
return;
}
IDocument doc = ps.getDoc();
List<String> parametersAfterCall = ps.getParametersAfterCall(end);
switch(id) {
case IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE:
addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall);
addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall);
break;
case IAnalysisPreferences.TYPE_UNDEFINED_IMPORT_VARIABLE:
// Say we had something as:
// import sys
// sys.Bar
// in which case 'Bar' is undefined
// in this situation, the activationTokenAndQual would be "sys." and "Bar"
// and we want to get the definition for "sys"
String[] activationTokenAndQual = ps.getActivationTokenAndQualifier(true);
if (activationTokenAndQual[0].endsWith(".")) {
ArrayList<IDefinition> selected = findDefinitions(nature, edit, start - 2, doc);
for (IDefinition iDefinition : selected) {
IModule module = iDefinition.getModule();
if (module.getFile() != null) {
Definition definition = (Definition) iDefinition;
File file = module.getFile();
if (definition.ast == null) {
// if we have no ast in the definition, it means the module itself was found (global scope)
// Add option to create class at the given module!
addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall, file);
addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall, file);
} else if (definition.ast instanceof ClassDef) {
ClassDef classDef = (ClassDef) definition.ast;
// Ok, we should create a field or method in this case (accessing a classmethod or staticmethod)
PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField();
String className = NodeUtils.getNameFromNameTok(classDef.name);
pyCreateMethod.setCreateInClass(className);
pyCreateMethod.setCreateAs(PyCreateMethodOrField.CLASSMETHOD);
addCreateClassmethodOption(ps, edit, props, markerContents, parametersAfterCall, pyCreateMethod, file, className);
}
}
}
}
break;
case IAnalysisPreferences.TYPE_UNRESOLVED_IMPORT:
// This case is the following: from other_module4 import Foo
// with 'Foo' being undefined.
// So, we have to suggest creating a Foo class/method in other_module4
PyImportsHandling importsHandling = new PyImportsHandling(ps.getDoc(), false);
int offsetLine = ps.getLineOfOffset(start);
String selectedText = ps.getSelectedText();
Tuple<IModule, String> found = null;
String foundFromImportStr = null;
boolean isImportFrom = false;
OUT: for (ImportHandle handle : importsHandling) {
if (handle.startFoundLine == offsetLine || handle.endFoundLine == offsetLine || (handle.startFoundLine < offsetLine && handle.endFoundLine > offsetLine)) {
List<ImportHandleInfo> importInfo = handle.getImportInfo();
for (ImportHandleInfo importHandleInfo : importInfo) {
String fromImportStr = importHandleInfo.getFromImportStr();
List<String> importedStr = importHandleInfo.getImportedStr();
for (String imported : importedStr) {
if (selectedText.equals(imported)) {
if (fromImportStr != null) {
foundFromImportStr = fromImportStr + "." + imported;
isImportFrom = true;
} else {
// if fromImportStr == null, it's not a from xxx import yyy (i.e.: simple import)
foundFromImportStr = imported;
}
try {
String currentModule = nature.resolveModule(edit.getEditorFile());
ICompletionState state = CompletionStateFactory.getEmptyCompletionState(nature, new CompletionCache());
found = nature.getAstManager().findModule(foundFromImportStr, currentModule, state, new SourceModule(currentModule, edit.getEditorFile(), edit.getAST(), null, nature));
} catch (Exception e) {
Log.log(e);
}
break OUT;
}
}
}
break OUT;
}
}
boolean addOptionToCreateClassOrMethod = isImportFrom;
if (found != null && found.o1 != null) {
// or just create a class or method at the end.
if (found.o1 instanceof SourceModule) {
// if all was found, there's nothing left to create.
if (found.o2 != null && found.o2.length() > 0) {
SourceModule sourceModule = (SourceModule) found.o1;
File file = sourceModule.getFile();
if (found.o2.indexOf('.') != -1) {
// We have to create some intermediary structure.
if (!addOptionToCreateClassOrMethod) {
// Cannot create class or method from the info (only the module structure).
if (sourceModule.getName().endsWith(".__init__")) {
File f = getFileStructure(file.getParentFile(), found.o2);
addCreateModuleOption(ps, edit, props, markerContents, f);
}
} else {
// Ok, the leaf may be a class or method.
if (sourceModule.getName().endsWith(".__init__")) {
String moduleName = FullRepIterable.getWithoutLastPart(sourceModule.getName());
String withoutLastPart = FullRepIterable.getWithoutLastPart(found.o2);
moduleName += "." + withoutLastPart;
String classOrMethodName = FullRepIterable.getLastPart(found.o2);
File f = getFileStructure(file.getParentFile(), withoutLastPart);
addCreateClassInNewModuleOption(ps, edit, props, classOrMethodName, moduleName, parametersAfterCall, f);
addCreateMethodInNewModuleOption(ps, edit, props, classOrMethodName, moduleName, parametersAfterCall, f);
}
}
} else {
// Ok, it's all there, we just have to create the leaf.
if (!addOptionToCreateClassOrMethod || sourceModule.getName().endsWith(".__init__")) {
// Cannot create class or method from the info (only the module structure).
if (sourceModule.getName().endsWith(".__init__")) {
File f = new File(file.getParent(), found.o2 + FileTypesPreferences.getDefaultDottedPythonExtension());
addCreateModuleOption(ps, edit, props, markerContents, f);
}
} else {
// Ok, the leaf may be a class or method.
addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall, file);
addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall, file);
}
}
}
}
} else if (foundFromImportStr != null) {
// We couldn't find anything there, so, we have to create the modules structure as needed and
// maybe create a class or module at the end (but only if it's an import from).
// Ok, it's all there, we just have to create the leaf.
// Discover the source folder where we should create the structure.
File editorFile = edit.getEditorFile();
String onlyProjectPythonPathStr = nature.getPythonPathNature().getOnlyProjectPythonPathStr(false);
List<String> split = StringUtils.splitAndRemoveEmptyTrimmed(onlyProjectPythonPathStr, '|');
for (int i = 0; i < split.size(); i++) {
String fullPath = FileUtils.getFileAbsolutePath(split.get(i));
fullPath = PythonPathHelper.getDefaultPathStr(fullPath);
split.set(i, fullPath);
}
HashSet<String> projectSourcePath = new HashSet<String>(split);
if (projectSourcePath.size() == 0) {
// No source folder for editor... this shouldn't happen (code analysis wouldn't even run on it).
return;
}
String fullPath = FileUtils.getFileAbsolutePath(editorFile);
fullPath = PythonPathHelper.getDefaultPathStr(fullPath);
String foundSourceFolderFullPath = null;
if (projectSourcePath.size() == 1) {
foundSourceFolderFullPath = projectSourcePath.iterator().next();
} else {
for (String string : projectSourcePath) {
if (fullPath.startsWith(string)) {
// Use this as the source folder
foundSourceFolderFullPath = string;
break;
}
}
}
if (foundSourceFolderFullPath != null) {
if (!addOptionToCreateClassOrMethod) {
// Cannot create class or method from the info (only the module structure).
File f = getFileStructure(new File(foundSourceFolderFullPath), foundFromImportStr);
addCreateModuleOption(ps, edit, props, foundFromImportStr, f);
} else {
// Ok, the leaf may be a class or method.
String moduleName = FullRepIterable.getWithoutLastPart(foundFromImportStr);
File file = getFileStructure(new File(foundSourceFolderFullPath), moduleName);
String lastPart = FullRepIterable.getLastPart(foundFromImportStr);
addCreateClassInNewModuleOption(ps, edit, props, lastPart, moduleName, parametersAfterCall, file);
addCreateMethodInNewModuleOption(ps, edit, props, lastPart, moduleName, parametersAfterCall, file);
}
}
}
break;
}
}
Aggregations