use of org.python.pydev.parser.jython.ast.ClassDef in project Pydev by fabioz.
the class IOUtils method addAstInfo.
/**
* Adds ast info information for a module.
*
* @param m the module we want to add to the info
*/
public List<IInfo> addAstInfo(SimpleNode node, ModulesKey key, boolean generateDelta) {
List<IInfo> createdInfos = new ArrayList<IInfo>();
if (node == null || key.name == null) {
return createdInfos;
}
try {
Tuple<DefinitionsASTIteratorVisitor, Iterator<ASTEntry>> tup = getInnerEntriesForAST(node);
if (DebugSettings.DEBUG_ANALYSIS_REQUESTS) {
org.python.pydev.shared_core.log.ToLogFile.toLogFile(this, "Adding ast info to: " + key.name);
}
try {
Iterator<ASTEntry> entries = tup.o2;
FastStack<SimpleNode> tempStack = new FastStack<SimpleNode>(10);
synchronized (this.lock) {
synchronized (ObjectsInternPool.lock) {
final String file = key.file != null ? ObjectsInternPool.internUnsynched(key.file.toString()) : null;
key.name = ObjectsInternPool.internUnsynched(key.name);
while (entries.hasNext()) {
ASTEntry entry = entries.next();
IInfo infoCreated = null;
if (entry.parent == null) {
// we only want those that are in the global scope
if (entry.node instanceof ClassDef) {
// no intern construct (locked in this loop)
NameTok name = (NameTok) ((ClassDef) entry.node).name;
ClassInfo info = new ClassInfo(ObjectsInternPool.internUnsynched(name.id), key.name, null, false, getNature(), file, name.beginLine, name.beginColumn);
add(info, TOP_LEVEL);
infoCreated = info;
} else if (entry.node instanceof FunctionDef) {
// no intern construct (locked in this loop)
NameTok name = (NameTok) ((FunctionDef) entry.node).name;
FuncInfo info2 = new FuncInfo(ObjectsInternPool.internUnsynched(name.id), key.name, null, false, getNature(), file, name.beginLine, name.beginColumn);
add(info2, TOP_LEVEL);
infoCreated = info2;
} else {
// it is an assign
infoCreated = this.addAssignTargets(entry, key.name, TOP_LEVEL, null, false, file);
}
} else {
if (entry.node instanceof ClassDef || entry.node instanceof FunctionDef) {
// ok, it has a parent, so, let's check to see if the path we got only has class definitions
// as the parent (and get that path)
Tuple<String, Boolean> pathToRoot = this.getPathToRoot(entry, false, false, tempStack);
if (pathToRoot != null && pathToRoot.o1 != null && pathToRoot.o1.length() > 0) {
if (entry.node instanceof ClassDef) {
NameTok name = ((NameTok) ((ClassDef) entry.node).name);
ClassInfo info = new ClassInfo(ObjectsInternPool.internUnsynched(name.id), key.name, ObjectsInternPool.internUnsynched(pathToRoot.o1), false, getNature(), file, name.beginLine, name.beginColumn);
add(info, INNER);
infoCreated = info;
} else {
// FunctionDef
NameTok name = ((NameTok) ((FunctionDef) entry.node).name);
FuncInfo info2 = new FuncInfo(ObjectsInternPool.internUnsynched(name.id), key.name, ObjectsInternPool.internUnsynched(pathToRoot.o1), false, getNature(), file, name.beginLine, name.beginColumn);
add(info2, INNER);
infoCreated = info2;
}
}
} else {
// it is an assign
Tuple<String, Boolean> pathToRoot = this.getPathToRoot(entry, true, false, tempStack);
if (pathToRoot != null && pathToRoot.o1 != null && pathToRoot.o1.length() > 0) {
infoCreated = this.addAssignTargets(entry, key.name, INNER, pathToRoot.o1, pathToRoot.o2, file);
}
}
}
if (infoCreated != null) {
createdInfos.add(infoCreated);
}
}
// end while
}
// end lock ObjectsPool.lock
}
// end this.lock
} catch (Exception e) {
Log.log(e);
}
} catch (Exception e) {
Log.log(e);
}
return createdInfos;
}
use of org.python.pydev.parser.jython.ast.ClassDef 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.parser.jython.ast.ClassDef 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.parser.jython.ast.ClassDef 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;
}
}
use of org.python.pydev.parser.jython.ast.ClassDef in project Pydev by fabioz.
the class ArgumentsChecker method checkNameFound.
/*default*/
void checkNameFound(Call callNode, SourceToken sourceToken) throws Exception {
FunctionDef functionDefinitionReferenced;
boolean callingBoundMethod = false;
SimpleNode ast = sourceToken.getAst();
if (ast instanceof FunctionDef) {
functionDefinitionReferenced = (FunctionDef) ast;
analyzeCallAndFunctionMatch(callNode, functionDefinitionReferenced, sourceToken, callingBoundMethod);
} else if (ast instanceof ClassDef) {
ClassDef classDef = (ClassDef) ast;
SimpleNode initNode = defToConsideredInit.get(classDef);
callingBoundMethod = true;
if (initNode == null) {
String className = ((NameTok) classDef.name).id;
Definition foundDef = sourceToken.getDefinition();
IModule mod = this.current;
if (foundDef != null) {
mod = foundDef.module;
}
SimpleNode n = NodeUtils.getNodeFromPath(classDef, "__init__");
if (n instanceof FunctionDef) {
initNode = n;
} else {
IDefinition[] definition = mod.findDefinition(CompletionStateFactory.getEmptyCompletionState(className + ".__init__", this.nature, this.completionCache), -1, -1, this.nature);
for (IDefinition iDefinition : definition) {
Definition d = (Definition) iDefinition;
if (d.ast instanceof FunctionDef) {
initNode = d.ast;
defToConsideredInit.put(classDef, initNode);
break;
}
}
}
}
if (initNode instanceof FunctionDef) {
functionDefinitionReferenced = (FunctionDef) initNode;
analyzeCallAndFunctionMatch(callNode, functionDefinitionReferenced, sourceToken, callingBoundMethod);
}
}
}
Aggregations