페이지

레이블이 eclipse인 게시물을 표시합니다. 모든 게시물 표시
레이블이 eclipse인 게시물을 표시합니다. 모든 게시물 표시

2013년 8월 4일 일요일

Eclispe platform contributor 되다.

Eclipse에 처음으로 내 소스를 반영하여 contributor가 되었다.

내가 반영한 것은 emacs key scheme에 있는 recenter command를 enhancement한 것인데.
기존에는 cursor line이 center 로만 옯겨졌는데 이것을 오리지널 이맥스처럼 center top bottom 으로 스크롤링되게 만드는 패치를 만들어서 반영하였다.

패치를 보면 알겠지만 매우 간단한 작업이었고, 더 어려운것은 그 프로세스 적인 부분이었다.
사실 어떻게 어떻게 해서 contributor 가 될 수 있다는 정보가 별로 없고 막막한 부분이 있었는데 이번에 그런 부분을 공유해보면 혹시나 비슷한 고민을 하고 있는 분들께 도움이 되지 않을까 하여 공유해보고자 한다.

  1. 우선 내가 해결하고자 하는 이슈가 이미 진행중인지 버그질라를 통해서 검색
  2. 해당하는 이슈가 있다면 그 이슈를 이용하면 되고, 없다면 새 이슈를 등록한다. 나의 경우 이슈는 https://bugs.eclipse.org/bugs/show_bug.cgi?id=412267 이었다.
  3. 이슈 등록후, 패치를 attach함.
  4. 이렇게 패치를 등록하면 각 모듈의 maintainer가 이슈를 재할당하고 첨부된 패치에 대한 feedback을 해준다. 나의 경우는 아래 사항들을 얘기했었다
    1.  command의 설명을 업데이트 하고, 소스의 copyright, credential 업데이트
    2. CLA(Contributor license agreement) 서명
    3. coding convention, compact assignment, operator 사이는 공백 하나씩 주기
    4. 버그 리포팅 및 재현할 수 있는 테스트 케이스 기술
  5. 이렇게 몇번의 피드백이 오고간 후 최종 패치를 올렸더니
    한 달여만에 master git 에 반영이 되었다.
    http://git.eclipse.org/c/platform/eclipse.platform.text.git/commit/?id=1726a32434ee8a113d5ab8c3441987c7aa6fdf25
eclipse는 git을 사용하고 있어서 git의 기본적인 사용법을 알아야 더 편할것 같고, 이 외에 정보들은 eclipse wiki등을 찾아 보면 되겠다.

이렇게 eclipse platform 소스에 내 이름이 떡 하니 들어가게 된 히스토리 되겠다.

2013년 1월 28일 월요일

xml catalog in Eclipse

xml catalog in Eclipse

History

  • 2013-01-28, initial version
  • 2013-06-04, using catalogue extension point

overview

eclipse는 xml의
  • element나 attribute의 자동완성 기능
  • validation 기능
을 제공한다. 이 기능을 사용하기 위해서는 그 xml문서의 문법책이라고 볼 수 있는 dtd 혹은 xsd파일이 있어야 한다.
보통 이런 xsd 파일은 http로 공개되어져 있고 eclipse 같은 훌륭한 IDE에선 그 파일을 가져와서 xml 파일은 validation할 수 있다.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
...
위 maven xml의 경우 http://maven.apache.org/xsd/maven-4.0.0.xsd 에 xsd가 있다. 그래서 대부분의 경우 xsd가 resolve가 되면 validation이 가능하다.
하지만 특정한 경우에 xsd를 override하고 싶은 경우가 있을 수 있다. 예를 들면
  • 내부 테스트 환경에서는 xsd위치가 다르다거나
  • 로컬에서 xsd를 바꿔가며 테스트 해보고 싶은 경우
  • 서버 이상으로 xsd에 접근을 못할 경우
그럴때 eclipse에서의 xml catalog를 사용해서 xsd를 override 할 수 있다.

xml fundamental

아래 설명을 이해하려면 최소한의 xml schema에 대한 지식이 있어야 한다.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   targetNamespace="http://example.org/publishing"
   xmlns:tns="http://example.org/publishing"
>

   <!-- type definitions -->
   <xsd:simpleType name="AuthorId">
      <!-- define value space details here -->
      ...
   </xsd:simpleType>

   <xsd:complexType name="AuthorType">
      <!-- define structural details here -->
      ...
   </xsd:complexType>

   <!-- global element/attribute declarations -->
   <xsd:element name="author" type="tns:AuthorType"/>
   <xsd:attribute name="authorId" type="tns:AuthorId"/>
   ...

</xsd:schema>
  • 위에서 xmlns:xxx는 xxx에대한 namespace정의다.
  • schema 에 있는 targetNamespace 는 이 스키마의 namespace가 http://example.org/publishing 이라는 것
  • xmlns:tns가 targetNamespace와 같은 것으로 한번 더 정의한 이유는 이 스키마 내부에서 특정 엘리먼트를 reference하기 위해서다. tns:AuthorType 이나 tns:AuthorId 처럼
위 xsd에 맞게 xml을 쓸때는 아래처럼 쓴다
<x:author xmlns:x="http://example.org/publishing"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://example.org/publishing pubs.xsd"
>
...
  • xmlns:x 가 위 xsd에서 정의한 nampspace이고 그것을 사용하고 있다
  • schemaLocation에서 <namespace> <xsd uri> pair를 한개 이상 정의할 수 있다

Defining xml catalog with dtd

Defining xml catalog with xsd

Preferences>XML>Xml Catalog 에서 xml catalog를 설정할 수 있다.
<c:Catalogue xmlns:c="http://www.eclipse.org/webtools/Catalogue" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.eclipse.org/webtools/Catalogue http://www.eclipse.org/webtools/Catalogue/Catalogue.xsd ">
    <c:Book>
        <title>Professional XML Schema</title>
        <date>2001</date>
        <isbn>1-861005-47-4</isbn>
        <publisher>Wrox Press</publisher>
    </c:Book>
</c:Catalogue>
방법은 2가지
namespace name으로 할경우, xsi:schemaLocation은 xml에서 제거를 해야 동작한다
이렇게 정의한 xml catalog는 import/export도 가능하다.

Defining xml catalog using extension point

preference를 이용한 xml catalog는 설정은 자신의 eclipse workspace에만 적용되는 local한 것인 한계가 있다. 내가 개발한 plugin을 사용하는 사람에게 설정을 해주고 싶다면 extension point를 이용해서 설정을 하는것도 가능하다.
org.eclipse.wst feature에 있는 "org.eclipse.wst.xml.core.catalogContributions" extension point를 이용하면 된다. 예제는 org.eclipse.wst.standard.schemas plugin의 소스를 import해서 살펴보면 어떻게 정의하고 사용하였는지 알 수 있다.

ex>
             point="org.eclipse.wst.xml.core.catalogContributions">
                        id="org.tizen.nativecpp.misc.manifest.catalog">
                              name="http://schemas.tizen.org/2012/12/manifest"
                  uri="xsd/manifest.xsd">
           

         



2012년 12월 13일 목요일

Manipulating Texts in Eclipse

Manipulating texts in Eclipse

History

revisionchangesauthor
0.1initial version 2012-12-05 수 Darren Ha
0.2textBuffer.commit 2012-12-13 목 Darren Ha

Introduction

manipulating texts in Eclipse way can be hard for initial Eclipse plugin developers. I couldn't find any structured tutorial or articles. So this articles is born. any comments about the contets are welcomed! I hope it helps you too.

Getting IDocument form a IPath

A FileBuffer represents a file that is being modified over time. Fille buffers for text files provide IDocument(a content model) and IAnnotationModel(a marker model). so IDdocument is essential for manipulating texts.
ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
IPath path = new Path("/sample/test.h");
try{
    bufferManager.connect(path, LocationKind.IFILE, monitor);
    ITextFileBuffer textBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
    IDocument document = textBuffer.getDocument();
}finally{
    bufferManager.disconnect(path, LocationKind.IFILE, monitor);
}  

Creating and applying TextEdit

We can modify IDocument using TextEdit subclasses: e.g. ReplaceEdit, InsertEdit, DeleteEdit to apply those changed multiple times in a file, you should use MultiTextEdit which is tree container of TextEdits. MultiTextEdit::apply can produce an error if the changes made at the same location at multiple times.
MultiTextEdit::apply doesn't change file contetns immediately. to change file content you must call ITextFileBuffer::commit.
ITextFileBuffer textBuffer = ...;
IDocument document = ..;

FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(document);
IRegion regionReplace = finder.find(0, "textTobeReplaced", true, true, false, false);
IRegion regionInsert = finder.find(0, "//TODO", true, true, false, false);

MultiTextEdit multiEdit = new MultiTextEdit();
multiEdit.addChild( new ReplaceEdit(regionReplace.getOffset(), regionReplace.getLength(), "ReplacedText"));
multiEdit.addChild( new InsertEdit(regionInsert.getOffset(), regionInsert.getLength()));
multiEdit.apply(document);
textBuffer.commit(monitor, true);

using CDT refactoring mechanism

You can use CDT built-in refactoring framework to change texts more elegant way. the following codes demonstrate invoking rename refactoring of CDT programtically. You can invoke this by clicking Alt+Shift+R in eclipse source editor. It's cool!
If the indexer has unresolved symbols , when build is broken, the refactoring operation can fail.
IFile file = new File("/sample/test.h");
IRegion region = ...;
CRefactoringArgument arg = new CRefactoringArgument(file, region.getOffset(), region.getLength());
CRenameProcessor proc = new CRenameProcessor(CRefactory.getInstance(), arg);
proc.setReplacementText("ReplacedText");
proc.setSelectedOptions(-1);
proc.setScope(TextSearchWrapper.SCOPE_SINGLE_PROJECT);
CRenameRefactoring refactor = new CRenameRefactoring(proc);

((CRenameProcessor)refactor.getProcessor()) .lockIndex();
try{
    RefactoringStatus rs = refactor.checkInitialConditions(monitor);
    if (rs.hasFatalError()) {
        throw new Exception("checkInitialcondtion fail");
    }
    rs = refactor.checkFinalConditions(monitor);
    if (rs.hasError()) {
        throw new Exception("checkFinalcondtion fail");
    }
    Change change = refactor.createChange(monitor);
    change.perform(monitor);
}finally{
    ((CRenameProcessor)refactor.getProcessor()).unlockIndex();
}

2012년 11월 28일 수요일

Eclipse Wizard Tutorial

Wizard

History

revisionchangesauthor
0.1initial version 2012-11-28 수 Darren Ha

Wizard

Wizard 클래스에서 상속받아서 클래스를 만든다. IImportWizard interface를 implement하는 이유는 eclipse의 import 메뉴에 사용하기 위해서 이다. 내부 구현을 보면 IImportWizard, IExportWizard, INewWizard 모두 같은 interface이고 단지 이름만 다르다. 따라서, IImportWizard를 implement한 클래스도 new project 혹은 export wizard에서 사용될 수 있다.
public class MyWizard extends Wizard implements IImportWizard {
    @Override
    public void init(IWorkbench workbench, IStructuredSelection selection) {
    }

    @Override
    public void addPages() {
        MainPage main = new MainPage();
        addPage(main);
    }

    @Override
    public boolean performFinish() {
        // TODO Auto-generated method stub
        return false;
    }
}

Wizard Page

MyWizard::addPages에서 추가될 page는 WizardPage를 상속받아서 만들고, Dialog와 마찬가지로 createControl에서 dialog를 구성해주면 된다.
public class MainPage extends WizardPage {
    public MainPage() {
        super("main");
    }
    @Override
    public void createControl(Composite parent) {

        Label l = new Label(parent, SWT.NONE);
        l.setText("test");
        setControl(l);
    }
}  

Validating each page's input

WizardPage::setPageComplete()로 해당 페이지의 input이 조건에 맞게 들어왔는지 검사해서 next 버튼을 enable할지 여부를 판단한다. SetMessage 함수로 여러가지 메세지를 wizard 헤더 영역에 나타낼 수 있다. 아래는 Text control에 제대로 된 비밀번호를 입력했을때만 finish 버튼을 enable하는 부분임.
protected void updatePageComplete() {
       setMessage(null);
       setPageComplete(false);

       String pwd = fText.getText();

       if (!pwd.equals(PASSWORD)) {
           setMessage(MSG, ERROR);
           return;
       }

       setPageComplete(true);
   }

Launching Wizard

Wizard Extension Points

eclipse의 File>New/Import/Export에 나타나게 하려면 eclipse가 제공하는 wizard extension point를 추가해야 한다. Eclipse의 plugin.xml editor에서 extension tab으로 이동한 후 아래 extension중 하나를 추가. new project -> org.eclipse.ui.newWizards import -> org.eclipse.ui.importWizards export -> org.eclipse.ui.exportWizards 추가한 extension point의 하위에 context menu를 이용하여 wizard 를 추가. class 를 실제 구현한 클래스의 이름을 추가하여 매핑해준다.

Using WizardDialog

WizardDialog를 이용해서 언제든 Programatically wizard를 띄울 수 있다. 아래 처럼.
public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
        IStructuredSelection selection = StructuredSelection.EMPTY;

        ISelection sel = HandlerUtil.getCurrentSelection(event);
        if (sel instanceof IStructuredSelection) {
            selection = (IStructuredSelection)sel;
        }


        MyWizard wizard = new MyWizard();
        wizard.init(window.getWorkbench(), selection);

        WizardDialog dialog = new WizardDialog(window.getShell(), wizard);
        dialog.open();
        return null;
    }

Tutorial Project

https://github.com/nberserk/eclipsetutorials 에 가시면 위에서 언급된 소스가 모두 포함된 eclipse project가 있습니다.

2012년 11월 10일 토요일

how to use DOM AST in CDT


update 2012/11/10:
 I created separate plugin to provide DOM AST viewer called ASTViewer. You can install it using the following update site :
https://raw.github.com/nberserk/ASTViewer/master/org.eclipse.cdt.ui.astviewer.update 

for more details information see here : https://github.com/nberserk/ASTViewer


I can't find any useful resources yet. so I share this information on my blog.
DOM AST viewer shows Abstract Syntax Tree of C/C++ program in tree manner. very useful for AST related work. I don't know Why this viewer is included in test plugin. that's why we can't use it in official CDT.

anyway, here is how to use DOM AST :
  • first get CDT source from CDT repository: http://git.eclipse.org/c/cdt/org.eclipse.cdt.git
    you can get source code for each released version here. e.g. > CDT_8_0_2.zip
  • copy CDT_8_0_2.zip/CDT_8_0_2/core/org.eclipse.cdt.ui.tests to your hard drive
  • import org.eclipse.cdt.ui.tests
  • remove build error ( i removed all source files except org.eclipse.cdt.ui.tests.DOMAST)
  • run
  • Window->Show View -> C/C++ -> DOM AST
  • done





2012년 10월 25일 목요일

Using AST in CDT

CDT AST(abstract syntax tree)

History

revisionchangesauthor
0.1initial version 2012-10-25 목 Darren Ha
0.2getting simplified ast tree using index 2012-10-31 수 Darren Ha

Introduction

AST는 코드에서 refactoring 등의 기능을 지원하기 위해서 만든 data structure이며 트리 구조를 가지고 있다. 이것을 이용해서 JDT 나 CDT 등에서 아주 강력하고 개발자에게 많은 도움을 주는 툴들을 만들 수 있다. refactoring 기능이나 static analyzer등의 기능들. 그렇다면 CDT의 index 와는 뭐가 틀릴까? index가 전체 프로젝트의 단위에서 동작하고 각 심볼단위(function or variable)로만 동작했다면, AST는 translation unit(header file or source file)단위로 정보를 get 할 수 있고, 각 function안의 statement 한 줄 한 줄에 대한 정보를 모두 가지고 있다. detail면에서는 ast훨씬 더 정교한 데이터를 가지고 있는 셈이다. <br/>

Creating With AST

// getting ast from CDE CoreModel
Path path = new Path("hello/src/hello.cpp");
ITranslationUnit tu = (ITranslationUnit) CoreModel.getDefault().create(path);
IASTTranslationUnit ast = tu.getAST(); // it's full ast
// excludes header from ast, much simplified ast.
IASTTranslationUnit simpleast = tu.getAST(index, ITranslationUnit.AST_SKIP_ALL_HEADERS); 
tu.getAST()의 경우는 header를 포함한 모든 ast node를 리턴하지만, tu.getAST(index, ..)의 경우는 헤더를 포함할지 하지 않을지 선택할 수 있다. 헤더를 포함하고 싶지 않을 경우에 사용하면 된다. C++의 헤더 디펜던시를 생각하면, performance gain이 크다.

Visiting AST

// traversing AST
ast.accept(new ASTVisitor() {
        {
            shouldVisitDeclarations = true;
        }
        @Override
        public int visit(IASTDeclaration declaration) {
            System.out.println(declaration);
            return PROCESS_CONTINUE;
        } // visit
    });  
ast tree는 visitor 패턴을 통해서 traverse할 수 있고, ASTVisitor의 생성자에서 visit하고 싶은 대상을 정할 수 있다. ASTVisitor::shouldVisitXXXXX 의 변수를 true로 해주면 매칭되는 node를 visit하게 된다.
예로 아래의 c++ function을 ast tree로 나타내 보자. 그럼 이해가 어느정도 될 것이다.
Application*
BasicApp::CreateInstance(void)
{
    int a;
    return new BasicApp();
}
위의 소스를 ast tree로 보면 아래처럼 표현된다. 소스에 비해서 아주 자세하게 표현되고 있다.
  • ICPPASTFunctionDefinition: BasicApp::CreateInstance
    • ICPPASTNamedTypeSepcifier: Application
    • ICPPFunctionDeclarator: Application*
      • IASTPointer
      • ICPPASTQualifiedName: BasicApp::CreateInstance
      • ICPPASTParameterDeclaration
        • ICPPASTSimpleDeclSpecifier: void
    • ICPPASTCompoundStatement: {}
      • IASTDeclarationStatement
        • ICPPASTSimpleDeclaration: a
          • ICPPASTSimpleDeclSpecifier: int
          • ICPPASTDeclarator, IASTImplicitNameOwner
            • IASTName: a
      • IASTReturnStatement: return new BasicApp();
        • IASTNewExpression
          • ICPPASTTypeId
            • ICPPASTNamedTypeSpecifier:BasicApp
              • IASTName: BasicApp
            • ICPPASTConstructorInitializer

Application

ast로 이런것을 할 수 있다. 다음은 c++에서 흔히 저지르는 실수인 if (a == b) 대신에 if (a=b) 로 assignment가 되는 실수를 detect하는 visitor를 만든 예이다. 이 예제는 reference 1에서 가져온 예임을 밝힙니다.
class CheckCodeVisitor extends ASTVisitor {
    CheckCodeVisitor() {
        shouldVisitExpressions= true;
    }
    public int visit(IASTExpression expression) {
        if (isAssignmentExpression(expression) && isUsedAsCondition(expression)) {
            System.out.println("warning ..." + expression.getFileLocation());
        }
        return PROCESS_CONTINUE;
    }
    private boolean isAssignmentExpression(IASTExpression e) {
        if (e instanceof IASTBinaryExpression) {
            IASTBinaryExpression binExpr= (IASTBinaryExpression) e;
            return binExpr.getOperator() == IASTBinaryExpression.op_assign;
        }
        return false;
    }
    private boolean isUsedAsCondition(IASTExpression expression) {
        ASTNodeProperty prop = expression.getPropertyInParent();
        if (prop == IASTForStatement.CONDITION || prop == IASTIfStatement.CONDITION)
            return true;
        return false;
    }
}

DOM AST(AST viewer)

CDT에는 DOM AST라는 AST트리를 보여주는 아주 훌륭한 viewer가 있었는데, 언젠가부터 org.eclipse.cdt.ui.tests 패키지에 포함되어 버려서 현재는 소스를 빌드하지 않으면 볼 수가없다. AST 관련 작업을 해야 한다면 필수 유틸 되겠다.

2012년 9월 20일 목요일

using cdt index

using CDT index

intro

CDT는 내부적으로 우리가 자주 사용하는 code assist, Open Declaration(F3), Open call Hierarchy(Ctrl + Alt + H) 등에 사용하기 위해서 내부적으로 c/c++ 코드를 parsing 해서 그 정보를 가지고 있는데 이것을 Index라고 한다. Indexer를 사용해서 특정 변수/함수 의 definition , declaration, reference 등의 정보를 가지고 올 수 있다.

getting IIndex

ICProject project = CoreModel.getDefault().getCModel().getCProject("hello");
CCorePlugin.getIndexManager().joinIndexer(IIndexManaer.FOREVER, null); // wait until indexing completes
IIndex index = null;
try{
    index = CCorePlugin.getIndexManager().getIndex(project);
    index.acquireReadLock(); // lock index

    IIndexBinding[] bindings = index.findBindings(Pattern.compile("main"), false, IndexFilter.All, null);
    for (IIndexBinding b : bindings) {
        System.out.print("name: " + b.getName()+" " );
        String[] qnames = b.getQualifiedName();
    }
}catch(Exception e){
    e.printStackTrace();
}finally{
    try{
        index.releaseReadLock();
    }catch (Exception e2){
        e.printStackTrace();
    }
}

Indexing 작업은 보통 main thread와 다른 thread에서 수행이 되기 때문에 joinIndexer로 인덱싱이 끝날때까지 기다린후 index에 lock을 걸고 findBinding 으로 쿼리를 수행할 수 있다.

querying

findBinding으로 IIndexBinding 을 얻고 여기서 얻은 IIndexBinding으로 아래 함수들을 불러 원하는 IIndexName을 얻을 수 있다. IIndex::findDeclarations : 함수/변수의 선언부와 구현부 IIndex::findDefinitions : 함수의 구현부 IIndex::findReferences : 합수나 변수가 사용된(use) 부분 그렇다면 함수의 선언부만 쿼리하고싶으면 어떻게 할까? IIndex::findNames(binding, IIndex.FINDDECLARATIONS)를 부르면 된다. 실제로 IIndex::findDeclarations은 IIndex::findNames(binding, IINdex.FINDDECLARATIONSDEFINITIONS)와 같다.
// finding declaration of BasicApp::CreateInstance
Pattern[] p = new Pattern[2];
p[0] = Pattern.compile("BasicApp");
p[1] = Pattern.compile("CreateInstance");
IIndexBinding[] bindings = index.findBindings(p , true, IndexFilter.CPP_DECLARED_OR_IMPLICIT, monitor);
for (IIndexBinding binding : bindings) {                
    IIndexName[] names = index.findNames(binding, IIndex.FIND_DECLARATIONS);
}  

getting index info

위 쿼리 함수들로 얻은 IIndexName으로 파일 위치나 기타 정보등을 얻을 수 있다.
for(IIndexName name: names){
    // get full path
    String path = name.getFile().getLocation().getFullPath();
    // get offset & length
    int offset = name.getNodeOffset();
    int length = name.getNodeLength();  
}

2012년 7월 21일 토요일

Eclipse PDE source attach

http://git.eclipse.org/c/pde/eclipse.pde.ui.git
에 가면 각 릴리즈 별로 taggin이 되어 있는데 자신의 버전에 맞는 태그를 찾아서 소스를 다운 받고 이것을 Attach해주면 된다.

내 경우는 
http://git.eclipse.org/c/pde/eclipse.pde.ui.git/snapshot/R3_7_2.zip
를 다운받고 attach해주니 잘 된다.