Search in sources :

Example 96 with Module

use of org.eclipse.titan.designer.AST.Module in project titan.EclipsePlug-ins by eclipse.

the class RenameRefactoring method runAction.

/**
 * Helper function used by RenameRefactoringAction classes for TTCN-3,
 * ASN.1 and TTCNPP editors
 */
public static void runAction(final IEditorPart targetEditor, final ISelection selection) {
    final IStatusLineManager statusLineManager = targetEditor.getEditorSite().getActionBars().getStatusLineManager();
    statusLineManager.setErrorMessage(null);
    final IFile file = (IFile) targetEditor.getEditorInput().getAdapter(IFile.class);
    if (file == null) {
        statusLineManager.setErrorMessage(FILENOTIDENTIFIABLE);
        return;
    }
    if (!TITANNature.hasTITANNature(file.getProject())) {
        statusLineManager.setErrorMessage(TITANNature.NO_TITAN_FILE_NATURE_FOUND);
        return;
    }
    final IPreferencesService prefs = Platform.getPreferencesService();
    final boolean reportDebugInformation = prefs.getBoolean(ProductConstants.PRODUCT_ID_DESIGNER, PreferenceConstants.DISPLAYDEBUGINFORMATION, true, null);
    int offset;
    if (selection instanceof TextSelection && !selection.isEmpty() && !"".equals(((TextSelection) selection).getText())) {
        if (reportDebugInformation) {
            TITANDebugConsole.getConsole().newMessageStream().println("text selected: " + ((TextSelection) selection).getText());
        }
        TextSelection tSelection = (TextSelection) selection;
        offset = tSelection.getOffset() + tSelection.getLength();
    } else {
        offset = ((IEditorWithCarretOffset) targetEditor).getCarretOffset();
    }
    // run semantic analysis to have up-to-date AST
    // FIXME: it does not work for incremental parsing
    final ProjectSourceParser projectSourceParser = GlobalParser.getProjectSourceParser(file.getProject());
    final WorkspaceJob job = projectSourceParser.analyzeAll();
    if (job == null) {
        if (reportDebugInformation) {
            TITANDebugConsole.getConsole().newMessageStream().println("Rename refactoring: WorkspaceJob to analyze project could not be created.");
        }
        return;
    }
    try {
        job.join();
    } catch (InterruptedException e) {
        ErrorReporter.logExceptionStackTrace(e);
        return;
    }
    // find the module
    if (ResourceExclusionHelper.isExcluded(file)) {
        targetEditor.getEditorSite().getActionBars().getStatusLineManager().setErrorMessage(MessageFormat.format(EXCLUDEDFROMBUILD, file.getFullPath()));
        return;
    }
    final Module module = projectSourceParser.containedModule(file);
    if (module == null) {
        statusLineManager.setErrorMessage(MessageFormat.format(NOTFOUNDMODULE, file.getName()));
        return;
    }
    ReferenceFinder rf = findOccurrencesLocationBased(module, offset);
    if (rf == null) {
        rf = new ReferenceFinder();
        boolean isDetected = rf.detectAssignmentDataByOffset(module, offset, targetEditor, true, reportDebugInformation);
        if (!isDetected) {
            return;
        }
    }
    RenameRefactoring renameRefactoring = new RenameRefactoring(file, module, rf);
    RenameRefactoringWizard renameWizard = new RenameRefactoringWizard(renameRefactoring);
    RefactoringWizardOpenOperation operation = new RefactoringWizardOpenOperation(renameWizard);
    try {
        operation.run(targetEditor.getEditorSite().getShell(), "");
    } catch (InterruptedException irex) {
        // operation was canceled
        if (reportDebugInformation) {
            TITANDebugConsole.getConsole().newMessageStream().println("Rename refactoring has been cancelled");
        }
    } finally {
        // ===================================
        // === Re-analysis after renaming ====
        // ===================================
        Map<Module, List<Hit>> changed = rf.findAllReferences(module, file.getProject(), null, reportDebugInformation);
        final Set<Module> modules = new HashSet<Module>();
        modules.add(module);
        modules.addAll(changed.keySet());
        reanalyseAstAfterRefactoring(file.getProject(), modules);
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) IStatusLineManager(org.eclipse.jface.action.IStatusLineManager) TextSelection(org.eclipse.jface.text.TextSelection) WorkspaceJob(org.eclipse.core.resources.WorkspaceJob) IPreferencesService(org.eclipse.core.runtime.preferences.IPreferencesService) ProjectSourceParser(org.eclipse.titan.designer.parsers.ProjectSourceParser) RefactoringWizardOpenOperation(org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation) ReferenceFinder(org.eclipse.titan.designer.AST.ReferenceFinder) List(java.util.List) ArrayList(java.util.ArrayList) Module(org.eclipse.titan.designer.AST.Module) ASN1Module(org.eclipse.titan.designer.AST.ASN1.definitions.ASN1Module) HashSet(java.util.HashSet)

Example 97 with Module

use of org.eclipse.titan.designer.AST.Module in project titan.EclipsePlug-ins by eclipse.

the class RenameRefactoring method createChange.

@Override
public Change createChange(final IProgressMonitor pm) throws CoreException {
    CompositeChange result = new CompositeChange(getName());
    // add the change of all found identifiers grouped by module
    boolean isAsnRename = module.getModuletype() == Module.module_type.ASN_MODULE;
    String newTtcnIdentifierName = newIdentifierName;
    if (isAsnRename) {
        newTtcnIdentifierName = Identifier.getTtcnNameFromAsnName(newIdentifierName);
    }
    List<IFile> filesToProcess = new ArrayList<IFile>(idsMap.size());
    for (Module m : idsMap.keySet()) {
        List<Hit> hitList = idsMap.get(m);
        boolean isTtcnModule = m.getModuletype() == Module.module_type.TTCN3_MODULE;
        IFile file = (IFile) hitList.get(0).identifier.getLocation().getFile();
        TextFileChange tfc = new TextFileChange(file.getName(), file);
        result.add(tfc);
        MultiTextEdit rootEdit = new MultiTextEdit();
        tfc.setEdit(rootEdit);
        for (Hit hit : hitList) {
            int offset = hit.identifier.getLocation().getOffset();
            int length = hit.identifier.getLocation().getEndOffset() - offset;
            String newName = isTtcnModule ? newTtcnIdentifierName : newIdentifierName;
            // reference.
            if (rf.fieldId == null && hit.reference != null && hit.reference.getModuleIdentifier() == null && rf.assignment.getMyScope().getModuleScope() != hit.reference.getMyScope().getModuleScope() && hit.reference.getMyScope().hasAssignmentWithId(CompilationTimeStamp.getBaseTimestamp(), new Identifier(isTtcnModule ? Identifier_type.ID_TTCN : Identifier_type.ID_ASN, newIdentifierName))) {
                newName = rf.assignment.getMyScope().getModuleScope().getName() + "." + newName;
            }
            rootEdit.addChild(new ReplaceEdit(offset, length, newName));
        }
        filesToProcess.add((IFile) m.getLocation().getFile());
    }
    return result;
}
Also used : IFile(org.eclipse.core.resources.IFile) ArrayList(java.util.ArrayList) TextFileChange(org.eclipse.ltk.core.refactoring.TextFileChange) Hit(org.eclipse.titan.designer.AST.ReferenceFinder.Hit) Identifier(org.eclipse.titan.designer.AST.Identifier) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) CompositeChange(org.eclipse.ltk.core.refactoring.CompositeChange) Module(org.eclipse.titan.designer.AST.Module) ASN1Module(org.eclipse.titan.designer.AST.ASN1.definitions.ASN1Module) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 98 with Module

use of org.eclipse.titan.designer.AST.Module in project titan.EclipsePlug-ins by eclipse.

the class RenameRefactoring method reanalyseAstAfterRefactoring.

/**
 * Re-analyzes AST after a rename-refactoring finished
 * At first reports outdating for the projects containing file has been refactored.
 * Then analyzes the project where the reanalysis started from (and its dependencies)
 * @param project  The project where the renaming started from
 * @param modules The modules containing renaming
 */
public static void reanalyseAstAfterRefactoring(final IProject project, final Set<Module> modules) {
    final ConcurrentLinkedQueue<WorkspaceJob> reportOutdatingJobs = new ConcurrentLinkedQueue<WorkspaceJob>();
    for (Module tempModule : modules) {
        final IFile f = (IFile) tempModule.getLocation().getFile();
        final WorkspaceJob op = new WorkspaceJob("Reports outdating for file: " + f.getName()) {

            @Override
            public IStatus runInWorkspace(final IProgressMonitor monitor) {
                IProject proj = f.getProject();
                reportOutdatingJobs.add(GlobalParser.getProjectSourceParser(proj).reportOutdating(f));
                return Status.OK_STATUS;
            }
        };
        op.setPriority(Job.LONG);
        op.setSystem(true);
        op.setUser(false);
        // waiting for f to be released
        op.setRule(f);
        op.setProperty(IProgressConstants.ICON_PROPERTY, ImageCache.getImageDescriptor("titan.gif"));
        reportOutdatingJobs.add(op);
        op.schedule();
    }
    // Waits for finishing update then analyzes all projects related to this change
    final WorkspaceJob op = new WorkspaceJob("Analyzes all projects related to this change") {

        @Override
        public IStatus runInWorkspace(final IProgressMonitor monitor) {
            while (!reportOutdatingJobs.isEmpty()) {
                WorkspaceJob job = reportOutdatingJobs.poll();
                try {
                    if (job != null) {
                        job.join();
                    }
                } catch (InterruptedException e) {
                    ErrorReporter.logExceptionStackTrace(e);
                }
            }
            // Now everything is released and reported outdated, so the analysis can start:
            final ProjectSourceParser projectSourceParser = GlobalParser.getProjectSourceParser(project);
            projectSourceParser.analyzeAll();
            return Status.OK_STATUS;
        }
    };
    op.setPriority(Job.LONG);
    op.setSystem(true);
    op.setUser(false);
    // op.setRule(file); //waiting for file to be released << Don't apply, it will wait forever!!!
    op.setProperty(IProgressConstants.ICON_PROPERTY, ImageCache.getImageDescriptor("titan.gif"));
    op.schedule();
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IFile(org.eclipse.core.resources.IFile) WorkspaceJob(org.eclipse.core.resources.WorkspaceJob) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Module(org.eclipse.titan.designer.AST.Module) ASN1Module(org.eclipse.titan.designer.AST.ASN1.definitions.ASN1Module) IProject(org.eclipse.core.resources.IProject) ProjectSourceParser(org.eclipse.titan.designer.parsers.ProjectSourceParser)

Example 99 with Module

use of org.eclipse.titan.designer.AST.Module in project titan.EclipsePlug-ins by eclipse.

the class NewASN1ModuleCreationWizardPage method validatePage.

/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.dialogs.WizardNewFileCreationPage#validatePage()
	 */
@Override
protected boolean validatePage() {
    if (!super.validatePage()) {
        return false;
    }
    final String extension = getContainerFullPath().append(getFileName()).getFileExtension();
    if (extension == null) {
        // test what will happen if we add the extension
        IPath fullPath = getContainerFullPath().append(getFileName()).addFileExtension(GlobalParser.SUPPORTED_ASN1_EXTENSIONS[1]);
        // path is invalid if any prefix is occupied by a file
        final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        while (fullPath.segmentCount() > 1) {
            if (root.getFile(fullPath).exists()) {
                setErrorMessage(OCCUPIED);
                return false;
            }
            fullPath = fullPath.removeLastSegments(1);
        }
    } else {
        // test the extension
        boolean valid = false;
        for (int i = 0; i < GlobalParser.SUPPORTED_ASN1_EXTENSIONS.length; i++) {
            if (GlobalParser.SUPPORTED_ASN1_EXTENSIONS[i].equals(extension)) {
                valid = true;
                break;
            }
        }
        if (!valid) {
            setErrorMessage(ERROR_MESSAGE);
            return false;
        }
    }
    // check modulename
    final IPath path = getContainerFullPath();
    if (hasLicense && path != null) {
        final IFile file = createFileHandle(path.append(getFileName()));
        final ProjectSourceParser projectSourceParser = GlobalParser.getProjectSourceParser(file.getProject());
        if (projectSourceParser.getLastTimeChecked() == null) {
            final WorkspaceJob job = projectSourceParser.analyzeAll();
            if (job != null) {
                try {
                    job.join();
                } catch (InterruptedException e) {
                    ErrorReporter.logExceptionStackTrace(e);
                }
            }
        }
        final String moduleName = getFileName();
        final int dotIndex = moduleName.indexOf('.');
        final String dotLessModuleName = dotIndex == -1 ? moduleName : moduleName.substring(0, dotIndex);
        final Module module = projectSourceParser.getModuleByName(dotLessModuleName);
        if (module != null) {
            setErrorMessage("A module with the name " + moduleName + " already exists in the project " + file.getProject().getName());
            return false;
        }
    }
    // validate the syntax of the module name
    validateName();
    setErrorMessage(null);
    return true;
}
Also used : IFile(org.eclipse.core.resources.IFile) IPath(org.eclipse.core.runtime.IPath) IWorkspaceRoot(org.eclipse.core.resources.IWorkspaceRoot) WorkspaceJob(org.eclipse.core.resources.WorkspaceJob) Module(org.eclipse.titan.designer.AST.Module) ProjectSourceParser(org.eclipse.titan.designer.parsers.ProjectSourceParser)

Example 100 with Module

use of org.eclipse.titan.designer.AST.Module in project titan.EclipsePlug-ins by eclipse.

the class AstWalkerJava method run.

public void run(IAction action) {
    /**/
    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    for (IProject p : projects) {
        if (p.getName().equals("org.eclipse.titan.codegenerator.output"))
            try {
                p.delete(true, true, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("org.eclipse.titan.codegenerator.output");
    try {
        project.create(null);
        project.open(null);
        IProjectDescription description = project.getDescription();
        description.setNatureIds(new String[] { JavaCore.NATURE_ID });
        project.setDescription(description, null);
        IJavaProject javaProject = JavaCore.create(project);
        IFolder binFolder = project.getFolder("bin");
        binFolder.create(false, true, null);
        javaProject.setOutputLocation(binFolder.getFullPath(), null);
        List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
        IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
        LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall);
        for (LibraryLocation element : locations) {
            entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null));
        }
        javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
        IFolder sourceFolder = project.getFolder("src");
        sourceFolder.create(false, true, null);
        IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder);
        IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
        IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
        System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
        newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
        javaProject.setRawClasspath(newEntries, null);
        javaProject.getPackageFragmentRoot(sourceFolder).createPackageFragment("org.eclipse.titan.codegenerator.javagen", false, null);
        javaProject.getPackageFragmentRoot(sourceFolder).createPackageFragment("org.eclipse.titan.codegenerator.TTCN3JavaAPI", false, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    String destpath = new String("");
    String wspath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString().replaceAll("/", "\\\\");
    destpath += wspath;
    destpath += "\\org.eclipse.titan.codegenerator.output\\src\\org\\eclipse\\titan\\codegenerator\\javagen\\";
    props.setProperty("javafile.path", destpath);
    /**/
    AstWalkerJava.files.clear();
    AstWalkerJava.fileNames.clear();
    AstWalkerJava.componentList.clear();
    AstWalkerJava.testCaseList.clear();
    AstWalkerJava.testCaseRunsOnList.clear();
    AstWalkerJava.functionList.clear();
    AstWalkerJava.functionRunsOnList.clear();
    AstWalkerJava.initOutputFolder();
    AstWalkerJava.getActiveProject();
    /*
		 * // init console logger IConsole myConsole = findConsole("myLogger");
		 * IWorkbenchPage page = window.getActivePage(); String id =
		 * IConsoleConstants.ID_CONSOLE_VIEW; IConsoleView view; try { view =
		 * (IConsoleView) page.showView(id); view.display(myConsole); } catch
		 * (PartInitException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */
    // initialize common files
    myASTVisitor.currentFileName = "TTCN_functions";
    myASTVisitor.visualizeNodeToJava(myASTVisitor.importListStrings);
    myASTVisitor.visualizeNodeToJava("class TTCN_functions{\r\n}\r\n");
    Def_Template_Visit_Handler.isTemplate = false;
    final ProjectSourceParser sourceParser = GlobalParser.getProjectSourceParser(selectedProject);
    sourceParser.analyzeAll();
    logToConsole("Version built on 2016.10.24");
    logToConsole("Starting to generate files into: " + props.getProperty("javafile.path"));
    myASTVisitor visitor = new myASTVisitor();
    for (Module module : sourceParser.getModules()) {
        // start AST processing
        walkChildren(visitor, module.getOutlineChildren());
    }
    visitor.finish();
    logToConsole("Files generated into: " + props.getProperty("javafile.path"));
    // write additional classes
    Additional_Class_Writer additional_class = new Additional_Class_Writer();
    myASTVisitor.currentFileName = "HC";
    myASTVisitor.visualizeNodeToJava(myASTVisitor.importListStrings);
    myASTVisitor.visualizeNodeToJava(additional_class.writeHCClass());
    myASTVisitor.currentFileName = "HCType";
    myASTVisitor.visualizeNodeToJava(myASTVisitor.importListStrings);
    myASTVisitor.visualizeNodeToJava(additional_class.writeHCTypeClass());
    // clear lists
    logger.severe("analysis complete");
    /**/
    File fromdir = new File(wspath + "\\org.eclipse.titan.codegenerator\\src\\org\\eclipse\\titan\\codegenerator\\TTCN3JavaAPI\\");
    String toapidir = wspath + "\\org.eclipse.titan.codegenerator.output\\src\\org\\eclipse\\titan\\codegenerator\\TTCN3JavaAPI\\";
    File[] fromfiles = fromdir.listFiles();
    for (File f : fromfiles) {
        try {
            Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(toapidir + f.getName()), StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String tppath = wspath + "\\" + selectedProject.getFullPath().toString().split("/")[1] + "\\src\\";
    File tp_cfg_dir = new File(tppath);
    String togendir = wspath + "\\org.eclipse.titan.codegenerator.output\\src\\org\\eclipse\\titan\\codegenerator\\javagen\\";
    File[] from_testports_cfg = tp_cfg_dir.listFiles();
    for (File f : from_testports_cfg) {
        if (f.getName().endsWith(".java")) {
            try {
                Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(togendir + f.getName()), StandardCopyOption.REPLACE_EXISTING);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (f.getName().endsWith(".cfg")) {
            try {
                Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(toapidir + "cfg.cfg"), StandardCopyOption.REPLACE_EXISTING);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    try {
        ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
    } catch (Exception e) {
        e.printStackTrace();
    }
/**/
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) ArrayList(java.util.ArrayList) LibraryLocation(org.eclipse.jdt.launching.LibraryLocation) IProject(org.eclipse.core.resources.IProject) PartInitException(org.eclipse.ui.PartInitException) IOException(java.io.IOException) ProjectSourceParser(org.eclipse.titan.designer.parsers.ProjectSourceParser) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) IJavaProject(org.eclipse.jdt.core.IJavaProject) IVMInstall(org.eclipse.jdt.launching.IVMInstall) IProjectDescription(org.eclipse.core.resources.IProjectDescription) TTCN3Module(org.eclipse.titan.designer.AST.TTCN3.definitions.TTCN3Module) Module(org.eclipse.titan.designer.AST.Module) IFile(org.eclipse.core.resources.IFile) File(java.io.File) IFolder(org.eclipse.core.resources.IFolder)

Aggregations

Module (org.eclipse.titan.designer.AST.Module)130 ProjectSourceParser (org.eclipse.titan.designer.parsers.ProjectSourceParser)51 ArrayList (java.util.ArrayList)37 TTCN3Module (org.eclipse.titan.designer.AST.TTCN3.definitions.TTCN3Module)36 IFile (org.eclipse.core.resources.IFile)32 Assignment (org.eclipse.titan.designer.AST.Assignment)22 Identifier (org.eclipse.titan.designer.AST.Identifier)21 Location (org.eclipse.titan.designer.AST.Location)16 Reference (org.eclipse.titan.designer.AST.Reference)16 ImportModule (org.eclipse.titan.designer.AST.TTCN3.definitions.ImportModule)16 HashMap (java.util.HashMap)14 List (java.util.List)13 WorkspaceJob (org.eclipse.core.resources.WorkspaceJob)11 IPreferencesService (org.eclipse.core.runtime.preferences.IPreferencesService)11 IProject (org.eclipse.core.resources.IProject)10 IResource (org.eclipse.core.resources.IResource)10 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)10 Assignments (org.eclipse.titan.designer.AST.Assignments)9 Scope (org.eclipse.titan.designer.AST.Scope)9 TextSelection (org.eclipse.jface.text.TextSelection)8