Search in sources :

Example 51 with Definition

use of org.eclipse.titan.designer.AST.TTCN3.definitions.Definition in project titan.EclipsePlug-ins by eclipse.

the class ChangeCreator method calculateMultiDeclarationCutLoc.

/**
 * Returns the {@link Location} of the {@DeleteEdit} to remove a variable from a declaration list
 */
private Location calculateMultiDeclarationCutLoc(final String fileContent, final StatementNode declStNode) {
    /*
		 * rules for removing multideclaration parts:
		 * 	if part is only one left: remove statement
		 * 	if part is first: remove trailing comma
		 * 	if part is last: remove leading comma
		 * 	if part is intermediate: remove trailing comma
		 * */
    final MultiDeclaration md = declStNode.getMultiDeclaration();
    final StatementNode firstDeclPart = md.getFirstStatement();
    final Definition defVarToMove = declStNode.getDeclaredVar().getDefinition();
    final Definition_Statement declStmt = (Definition_Statement) declStNode.getAstNode();
    final boolean firstDefInMdMoved = firstDeclPart.isMoved();
    final Location declStmtLoc = declStmt.getLocation();
    final String stmtContent = fileContent.substring(declStmtLoc.getOffset(), declStmtLoc.getEndOffset());
    if (!stmtContent.contains(",")) {
        ErrorReporter.logError("ChangeCreator.calculateMultiDeclarationCutLoc(): Given statement" + " is not a multi-declaration statement; loc: " + declStmtLoc.getOffset() + "-" + declStmtLoc.getEndOffset() + " in file " + declStmtLoc.getFile());
        return null;
    }
    // 
    if (md.getSize() <= 1) {
        final Location cutLoc = findStatementLocation(fileContent, declStmt.getLocation(), true);
        // System.err.println("mdcutloc <= 1 -->>>" + fileContent.substring(cutLoc.getOffset(), cutLoc.getEndOffset()) + "<<<");
        return cutLoc;
    }
    // 
    int cutOffset = defVarToMove.getLocation().getOffset();
    int cutEndOffset = defVarToMove.getLocation().getEndOffset();
    if (md.isFirstStatement(declStNode)) {
        // fist var
        if (!md.isAllStatementsMoved()) {
            cutOffset = defVarToMove.getIdentifier().getLocation().getOffset();
        }
        cutEndOffset = calculateEndOffsetIncludingTrailingComma(fileContent, cutEndOffset, declStmtLoc.getEndOffset());
    } else if (md.isLastStatement(declStNode)) {
        // last var
        cutOffset = calculateOffsetIncludingLeadingComma(fileContent, cutOffset, declStmtLoc.getOffset());
    } else {
        // intermediate var
        cutEndOffset = calculateEndOffsetIncludingTrailingComma(fileContent, cutEndOffset, declStmtLoc.getEndOffset());
    }
    // System.err.println("mdcutloc -->>>" + fileContent.substring(cutOffset, cutEndOffset) + "<<<");
    return new Location(declStmtLoc.getFile(), declStmtLoc.getLine(), cutOffset, cutEndOffset);
}
Also used : Definition_Statement(org.eclipse.titan.designer.AST.TTCN3.statements.Definition_Statement) MultiDeclaration(org.eclipse.titanium.refactoring.scope.nodes.MultiDeclaration) Definition(org.eclipse.titan.designer.AST.TTCN3.definitions.Definition) StatementNode(org.eclipse.titanium.refactoring.scope.nodes.StatementNode) Location(org.eclipse.titan.designer.AST.Location)

Example 52 with Definition

use of org.eclipse.titan.designer.AST.TTCN3.definitions.Definition in project titan.EclipsePlug-ins by eclipse.

the class DependencyCollector method reportOverlappingError.

private void reportOverlappingError(final ILocateableNode defCurrent, final ILocateableNode defOverlapping) {
    final Location dLocOverlap = defOverlapping == null ? null : defOverlapping.getLocation();
    final Location dLocCurr = defCurrent == null ? null : defCurrent.getLocation();
    String idOverlap = null;
    if (defOverlapping instanceof Definition) {
        idOverlap = ((Definition) defOverlapping).getIdentifier().toString();
    } else if (defOverlapping instanceof ImportModule) {
        idOverlap = "ImportModule{" + ((ImportModule) defOverlapping).getIdentifier().toString() + "}";
    } else if (defOverlapping instanceof FriendModule) {
        idOverlap = "FriendModule{" + ((FriendModule) defOverlapping).getIdentifier().toString() + "}";
    }
    String idCurr = null;
    if (defCurrent instanceof Definition) {
        idCurr = ((Definition) defCurrent).getIdentifier().toString();
    } else if (defCurrent instanceof ImportModule) {
        idCurr = "ImportModule{" + ((ImportModule) defCurrent).getIdentifier().toString() + "}";
    } else if (defCurrent instanceof FriendModule) {
        idCurr = "FriendModule{" + ((FriendModule) defCurrent).getIdentifier().toString() + "}";
    }
    final String msg1 = (dLocCurr == null) ? "null" : "Definition id: " + idCurr + " (" + defCurrent.getClass().getSimpleName() + ") at " + dLocCurr.getFile() + ", offset " + dLocCurr.getOffset() + "-" + dLocCurr.getEndOffset();
    final String msg2 = (dLocOverlap == null) ? "null" : "Definition id: " + idOverlap + " (" + defOverlapping.getClass().getSimpleName() + ") at " + dLocOverlap.getFile() + ", offset " + dLocOverlap.getOffset() + "-" + dLocOverlap.getEndOffset();
    ErrorReporter.logError("Warning! Locations overlap while reading source project: \n" + msg1 + "\n WITH \n" + msg2);
}
Also used : FriendModule(org.eclipse.titan.designer.AST.TTCN3.definitions.FriendModule) Definition(org.eclipse.titan.designer.AST.TTCN3.definitions.Definition) ImportModule(org.eclipse.titan.designer.AST.TTCN3.definitions.ImportModule) Location(org.eclipse.titan.designer.AST.Location)

Example 53 with Definition

use of org.eclipse.titan.designer.AST.TTCN3.definitions.Definition in project titan.EclipsePlug-ins by eclipse.

the class DependencyCollector method readDependencies.

public WorkspaceJob readDependencies() {
    final WorkspaceJob job = new WorkspaceJob("ExtractModulePar: reading dependencies from source project") {

        @Override
        public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException {
            final ProjectSourceParser projectSourceParser = GlobalParser.getProjectSourceParser(sourceProj);
            // find all dependencies of the 'selection' definition
            Set<IResource> allFiles = new HashSet<IResource>();
            Set<IResource> asnFiles = new HashSet<IResource>();
            NavigableSet<ILocateableNode> dependencies = new TreeSet<ILocateableNode>(new LocationComparator());
            for (Def_ModulePar def : selection) {
                /*
					 * Def_ModulePars with mutliple entries in a single modulepar block have incorrect location info
					 *  (all entries have a location info equal to the location of their parent block)
					 *  that is why the dependencies must be collected into a set that is not sorted by location
					 *
					 *  TODO fix grammar definitions
					 * */
                Set<ILocateableNode> nonSortedTempSet = new HashSet<ILocateableNode>();
                collectDependencies(def, nonSortedTempSet, allFiles, asnFiles);
                dependencies.addAll(nonSortedTempSet);
                allFiles.add(def.getLocation().getFile());
                // adding the selection itself to the dependencies
                if (!dependencies.contains(def)) {
                    dependencies.add(def);
                }
                // get imports and friends for all files
                for (IResource r : allFiles) {
                    if (!(r instanceof IFile)) {
                        continue;
                    }
                    IFile f = (IFile) r;
                    Module m = projectSourceParser.containedModule(f);
                    ImportFinderVisitor impVisitor = new ImportFinderVisitor();
                    m.accept(impVisitor);
                    List<ImportModule> impDefs = impVisitor.getImportDefs();
                    List<FriendModule> friendDefs = impVisitor.getFriendDefs();
                    filterImportDefinitions(allFiles, impDefs, projectSourceParser);
                    filterFriendDefinitions(allFiles, friendDefs, projectSourceParser);
                    dependencies.addAll(impDefs);
                    dependencies.addAll(friendDefs);
                // the dependencies are sorted by file & location to avoid reading through a file multiple times
                }
            }
            // collect the text to insert into the new project
            copyMap = new HashMap<IPath, StringBuilder>();
            try {
                InputStream is = null;
                InputStreamReader isr = null;
                IResource lastFile = null;
                IResource currFile;
                ILocateableNode lastD = null;
                int currOffset = 0;
                for (ILocateableNode d : dependencies) {
                    currFile = d.getLocation().getFile();
                    if (!(currFile instanceof IFile)) {
                        ErrorReporter.logError("ExtractModulePar/DependencyCollector: IResource `" + currFile.getName() + "' is not an IFile.");
                        continue;
                    }
                    if (currFile != lastFile) {
                        // started reading new file
                        lastD = null;
                        if (lastFile != null) {
                            addToCopyMap(lastFile.getProjectRelativePath(), MODULE_TRAILER);
                        }
                        if (isr != null) {
                            isr.close();
                        }
                        if (is != null) {
                            is.close();
                        }
                        is = ((IFile) currFile).getContents();
                        isr = new InputStreamReader(is);
                        currOffset = 0;
                        Module m = projectSourceParser.containedModule((IFile) currFile);
                        String moduleName = m.getIdentifier().getTtcnName();
                        addToCopyMap(currFile.getProjectRelativePath(), MessageFormat.format(MODULE_HEADER, moduleName));
                    }
                    int toSkip = getNodeOffset(d) - currOffset;
                    if (toSkip < 0) {
                        reportOverlappingError(lastD, d);
                        continue;
                    }
                    isr.skip(toSkip);
                    // separators
                    if (d instanceof ImportModule && lastD instanceof ImportModule) {
                        addToCopyMap(currFile.getProjectRelativePath(), SINGLE_SEPARATOR);
                    } else if (d instanceof FriendModule && lastD instanceof FriendModule) {
                        addToCopyMap(currFile.getProjectRelativePath(), SINGLE_SEPARATOR);
                    } else {
                        addToCopyMap(currFile.getProjectRelativePath(), DOUBLE_SEPARATOR);
                    }
                    // 
                    insertDependency(d, currFile, isr);
                    currOffset = d.getLocation().getEndOffset();
                    lastFile = currFile;
                    lastD = d;
                }
                if (lastFile != null) {
                    addToCopyMap(lastFile.getProjectRelativePath(), MODULE_TRAILER);
                }
                if (isr != null) {
                    isr.close();
                }
                if (is != null) {
                    is.close();
                }
                // copy the full content of asn files without opening them
                filesToCopy = new ArrayList<IFile>();
                for (IResource r : asnFiles) {
                    if (!(r instanceof IFile)) {
                        ErrorReporter.logError("ExtractModulePar/DependencyCollector: IResource `" + r.getName() + "' is not an IFile.");
                        continue;
                    }
                    filesToCopy.add((IFile) r);
                }
            } catch (IOException ioe) {
                ErrorReporter.logError("ExtractModulePar/DependencyCollector: Error while reading source project.");
                return Status.CANCEL_STATUS;
            }
            return Status.OK_STATUS;
        }

        private void insertDependency(final ILocateableNode d, final IResource res, final InputStreamReader isr) throws IOException {
            char[] content = new char[d.getLocation().getEndOffset() - getNodeOffset(d)];
            isr.read(content, 0, content.length);
            addToCopyMap(res.getProjectRelativePath(), new String(content));
        }
    };
    job.setUser(true);
    job.schedule();
    return job;
}
Also used : IFile(org.eclipse.core.resources.IFile) ProjectSourceParser(org.eclipse.titan.designer.parsers.ProjectSourceParser) ImportModule(org.eclipse.titan.designer.AST.TTCN3.definitions.ImportModule) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) FriendModule(org.eclipse.titan.designer.AST.TTCN3.definitions.FriendModule) IPath(org.eclipse.core.runtime.IPath) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) WorkspaceJob(org.eclipse.core.resources.WorkspaceJob) Def_ModulePar(org.eclipse.titan.designer.AST.TTCN3.definitions.Def_ModulePar) IOException(java.io.IOException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ILocateableNode(org.eclipse.titan.designer.AST.ILocateableNode) FriendModule(org.eclipse.titan.designer.AST.TTCN3.definitions.FriendModule) Module(org.eclipse.titan.designer.AST.Module) ImportModule(org.eclipse.titan.designer.AST.TTCN3.definitions.ImportModule) IResource(org.eclipse.core.resources.IResource)

Example 54 with Definition

use of org.eclipse.titan.designer.AST.TTCN3.definitions.Definition in project titan.EclipsePlug-ins by eclipse.

the class SelectionFinder method findSelection.

private Definition findSelection() {
    // getting the active editor
    final IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
    if (editor == null || !(editor instanceof TTCN3Editor)) {
        return null;
    }
    final TTCN3Editor targetEditor = (TTCN3Editor) editor;
    // iterating through part of the module
    final IResource selectedRes = extractResource(targetEditor);
    if (!(selectedRes instanceof IFile)) {
        ErrorReporter.logError("SelectionFinder.findSelection(): Selected resource `" + selectedRes.getName() + "' is not a file.");
        return null;
    }
    final IFile selectedFile = (IFile) selectedRes;
    sourceProj = selectedFile.getProject();
    final ProjectSourceParser projectSourceParser = GlobalParser.getProjectSourceParser(sourceProj);
    final Module selectedModule = projectSourceParser.containedModule(selectedFile);
    // getting current selection
    final ISelectionService selectionService = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService();
    final TextSelection textSelection = extractSelection(selectionService.getSelection());
    // getting current selection nodes
    final int selectionOffset = textSelection.getOffset() + textSelection.getLength();
    final SelectionFinderVisitor selVisitor = new SelectionFinderVisitor(selectionOffset);
    selectedModule.accept(selVisitor);
    final Definition selectedDef = selVisitor.getSelection();
    if (selectedDef == null) {
        ErrorReporter.logWarning("SelectionFinder.findSelection(): Visitor did not find a definition in the selection.");
        final IStatusLineManager statusLineManager = targetEditor.getEditorSite().getActionBars().getStatusLineManager();
        statusLineManager.setErrorMessage(ERR_MSG_NO_SELECTION);
        return null;
    }
    return selectedDef;
}
Also used : TTCN3Editor(org.eclipse.titan.designer.editors.ttcn3editor.TTCN3Editor) IFile(org.eclipse.core.resources.IFile) IStatusLineManager(org.eclipse.jface.action.IStatusLineManager) TextSelection(org.eclipse.jface.text.TextSelection) Definition(org.eclipse.titan.designer.AST.TTCN3.definitions.Definition) ISelectionService(org.eclipse.ui.ISelectionService) IEditorPart(org.eclipse.ui.IEditorPart) Module(org.eclipse.titan.designer.AST.Module) IResource(org.eclipse.core.resources.IResource) ProjectSourceParser(org.eclipse.titan.designer.parsers.ProjectSourceParser)

Example 55 with Definition

use of org.eclipse.titan.designer.AST.TTCN3.definitions.Definition in project titan.EclipsePlug-ins by eclipse.

the class SelectionFinder method performHeadless.

void performHeadless(final IFile selFile, final ITextSelection textSel) {
    selectedFile = selFile;
    final String fileContents = readFileContents(selFile);
    if (fileContents == null) {
        ErrorReporter.logError("ExtractToFunctionRefactoring.findSelection(): selFile does not exist at: " + selFile.getFullPath());
        return;
    }
    final IDocument doc = new Document(fileContents);
    textSelection = new TextSelection(doc, textSel.getOffset(), textSel.getLength());
    // 
    project = selFile.getProject();
    sourceParser = GlobalParser.getProjectSourceParser(project);
    selectedModule = sourceParser.containedModule(selectedFile);
    if (selectedModule == null) {
        ErrorReporter.logError("ExtractToFunctionRefactoring.findSelection(): The module in the file " + selectedFile.getName() + " has no name.");
        return;
    }
    // iterating through the module for the selected statements
    final SelectionVisitor selectionVisitor = new SelectionVisitor(textSelection.getOffset(), textSelection.getLength());
    selectedModule.accept(selectionVisitor);
    selectedStatements = selectionVisitor.createStatementList(textSelection);
    if (selectedStatements.isEmpty()) {
        ErrorReporter.logError(ERR_MSG_NO_SELECTION);
        return;
    }
    if (ExtractToFunctionRefactoring.DEBUG_MESSAGES_ON) {
        ErrorReporter.logError(selectedStatements.createDebugInfo());
        ErrorReporter.logError(createDebugInfo());
    }
    // finding return type & runs on clause
    final RunsOnClauseFinder runsonVisitor = new RunsOnClauseFinder(selectedStatements.getLocation());
    selectedModule.accept(runsonVisitor);
    runsOnRef = runsonVisitor.getRunsOnRef();
    parentFunc = runsonVisitor.getFuncDef();
    // finding insert location
    if (parentFunc instanceof Definition) {
        insertLoc = ((Definition) parentFunc).getLocation().getEndOffset();
    } else if (parentFunc instanceof ControlPart) {
        final ControlPart cp = (ControlPart) parentFunc;
        final Location commentLoc = cp.getCommentLocation();
        insertLoc = commentLoc == null ? cp.getLocation().getOffset() : commentLoc.getOffset();
    }
    // 
    final ReturnVisitor retVis = new ReturnVisitor();
    selectedStatements.accept(retVis);
    returnCertainty = retVis.getCertainty();
    if (retVis.getCertainty() != ReturnCertainty.NO) {
        returnType = runsonVisitor.getReturnType();
    }
    // checking erroneousness of selection
    checkErroneousGoto();
    if (containsBreakWithoutLoop()) {
        warnings.add(new RefactoringStatusEntry(RefactoringStatus.WARNING, WARNING_ERRONEOUS_BREAK));
    }
    if (containsContinueWithoutLoop()) {
        warnings.add(new RefactoringStatusEntry(RefactoringStatus.WARNING, WARNING_ERRONEOUS_CONTINUE));
    }
    if (retVis.getCertainty() == ReturnCertainty.MAYBE) {
        warnings.add(new RefactoringStatusEntry(RefactoringStatus.WARNING, WARNING_UNCERTAIN_RETURN));
    }
}
Also used : ITextSelection(org.eclipse.jface.text.ITextSelection) TextSelection(org.eclipse.jface.text.TextSelection) Definition(org.eclipse.titan.designer.AST.TTCN3.definitions.Definition) RefactoringStatusEntry(org.eclipse.ltk.core.refactoring.RefactoringStatusEntry) ControlPart(org.eclipse.titan.designer.AST.TTCN3.definitions.ControlPart) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDocument(org.eclipse.jface.text.IDocument) Location(org.eclipse.titan.designer.AST.Location)

Aggregations

Definition (org.eclipse.titan.designer.AST.TTCN3.definitions.Definition)52 Assignment (org.eclipse.titan.designer.AST.Assignment)16 IValue (org.eclipse.titan.designer.AST.IValue)12 Location (org.eclipse.titan.designer.AST.Location)11 IReferenceChain (org.eclipse.titan.designer.AST.IReferenceChain)10 IType (org.eclipse.titan.designer.AST.IType)10 Identifier (org.eclipse.titan.designer.AST.Identifier)10 Module (org.eclipse.titan.designer.AST.Module)10 ArrayList (java.util.ArrayList)9 Reference (org.eclipse.titan.designer.AST.Reference)9 StatementBlock (org.eclipse.titan.designer.AST.TTCN3.statements.StatementBlock)8 ISubReference (org.eclipse.titan.designer.AST.ISubReference)6 Def_Function (org.eclipse.titan.designer.AST.TTCN3.definitions.Def_Function)6 ExpressionStruct (org.eclipse.titan.designer.AST.TTCN3.values.expressions.ExpressionStruct)6 ProjectSourceParser (org.eclipse.titan.designer.parsers.ProjectSourceParser)6 FieldSubReference (org.eclipse.titan.designer.AST.FieldSubReference)5 RunsOnScope (org.eclipse.titan.designer.AST.TTCN3.definitions.RunsOnScope)5 TTCN3Module (org.eclipse.titan.designer.AST.TTCN3.definitions.TTCN3Module)5 IFile (org.eclipse.core.resources.IFile)4 Restriction_type (org.eclipse.titan.designer.AST.TTCN3.TemplateRestriction.Restriction_type)4