페이지

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년 10월 20일 토요일

Ben & Fitz, Team Geek


이책은 정말 시간가는줄 모르고 흥미있게 읽었다. 개발자라면 모두가 읽어야 하는 필독서 라고 감히 권하고 싶다. 특히 필자들이 직접 겪은 에피소드들의 얘기가 좋았다. 팍팍 와 닿는다.

가히 소프트웨어를 혼자 개발하는 시대는 갔다. 모든 훌륭한 소프트웨어는 팀단위로 이루어기에 좋은 팀을 만드는 것이 프로젝트 성공의 key이다. 유능한 리더는 있을지 몰라도 혼자서 모든 것을 만드는 천재 개발자의 얘기는 미신에 불과하다.

좋은 팀을 만들고 싶고, 좋은 리더가 되고 싶고, 많은 사람들이 사용하는 great software를 만들고 싶다면 꼭 팀플레이를 잘하는 팀원이 되어야 한다. 팀플레이를 잘 할 수 있게 하는 지침서 되겠다.

Team Geek

The Myth of the Genius Programmer

  • genious myth
    • Linus's real achievement was to lead these people and coordinate their work; Linux is the shining result of their collective labor. p3
  • hiding is considered harmful
    • could be reinventing wheels
    • bus factor. p7
    • hard to fail eary/fast/often
  • sw development is a team sport
  • HRT(humility, respect, trust)
  • handling criticism
    • u r not ur code. don't equate your self-worth with ur code quality. p17
    • when giving feedback, do not make him feel stupid. make the question about You. p17
  • the key to learing from your failures is to document your failures. postmortems. p19
  • leave time for learing

Building an Awesome Team Culture

  • include as few people as necessary in synchronous communication(like meetings) and to go for a broader audience in asynchronous communication(like email). p34
  • mission statement helps your team confront differences and come to an agreement.
잘 정리된 mission statement는 다른 생각을 가진 사람들과 일을 할때 결론에 도달하게끔 도와준다. 우리가 하고자 하는 것이 무엇인지 항상 잊지 않게 만듦과 동시에 의견 충돌시 guidance가 될 수도 있다.

Every Boat Needs a Captain

  • You never intended to become a leader. but somehow it happened anyway. p54
  • @deprecated manager
  • traditional managers worry about how to get things done, while leaders forge the way. p56
  • quantifying mgmt work is difficult. makint team te be happy and productive is a big measure of your job. p58
  • anti patterns
    • hire pushovers
    • ignore low performers
      • hope is not a strategy. p61
    • ignore human issues
    • be everyone's friend
    • compromise hiring bar
    • treat ur team like children
  • leadership patterns
    • lose the ego
      • cultivate collective team ego and identity
      • driving the team to consensus and helping to set the direction, the details are decided by members
      • do not try
        • to get everything to right
        • to know everything
      • apoligize when u make mistakes; absolutely u will
    • be a zen master
      • mediating ur reactions and maintaining calm is important. p68
      • if someone asks u for advice, asking questions
    • be a catalyst
      • build consensus
      • In many cases, knowing the right person is more valuable than knowing the right answer. p71
      • make them feel safe and secure so that they can take greater risks; risk is fascinating thing
    • be a teacher and a mentor
    • set clear goals
    • be honest
      • jumping in front of train. pick and choose the ones u want to stop. p76
    • track happiness
      • is there anyting you need ?
      • tracking their careers; get promoted, learn something new, launch something important, and work with smart people
      • give opportunities to improve themselves
    • Tips and Tricks
      • Delegate
      • seek to replace yourself
      • know when to make waves
      • shield ur team from chaos
        • outside ur team is world of chaos and uncertainty
      • let your team know when they're doing well
  • intrinsic versus extrinsic motivation
    • Dan claims you can increase intrinsic motivation by giving people three things: autonomy, mastery, purpose. p83
    • An engineer's skills are like the blade of knife: you may spend thousands of dollars to find engineers with sharpest skills, but if you use that knife for years without sharpening it, you will wind up with a dull knife that is inefficient, and useless

Dealing With Poisonous People

  • the hardest part of SW development is people. p85
  • It's behaviors you want to filter out, not individuials. it's naive to think of individuals as purely good or bad.
  • Identifying the threat
    • not respecting other people's time; ask something with any homework
    • ego; incapable of accepting a consensus decision
    • perfectionism can be lead to paralysis
  • Repelling the poison
    • redirect the energy of perfectionists
    • don't feed the trolls
    • don't get overly emotional; choose your battles carefully and keep calm
    • look for facts in the bile
    • focus on the long term

The Art of Organizational Manipulation

The ideal: how a team ought to function within a company

  • ur life under an ideal manager
    • pursue extra responsibility
    • take risks
    • act like an adult
    • question things
    • your manager is not clarvoyant

The reality: when ur env is an obstacle to ur success

  • bad manager traits
    • fear of failure
    • want to be inserted into every interaction u have with people
    • hoarding information
  • office politician; looking impactful than actually being impactful
  • bad organization

Manipulating your organization

  • forgiveness than permission
  • If you can't take the Path, maek the path
    • adopting open source tools
    • persuade management
    • It's impossible simply to stop a bad habit; u need to replace it with a good one.
  • Learn to manage upward
    • selling yourself
    • underpromise and overdeliver whenever possible
    • offensive work vs defensive work
  • luck and favor economy
    • earn credits, it will pay enormous dividens.
  • get promoted to a position of safety
    • the higher you can get, the more control you'll have over your destiny
  • seek powerful friends
    • connectors, old-timers
  • how to ask a busy executive for anything … via email
    • three bullets and a call to action

Plan B-get out

  • be prepared and know ur options

Users Are People, Too

  • margeting
    • perception is nine-tenth of the law
  • pay attention to first impressions
  • under promise and over deliver
  • focus on the user, and all else will follow
  • speed is a feature
  • don't be all things; too many options are bad
  • hiding compexity
    • ITunes's mp3 mgmt
    • Google's search box
    • abstractions will eventually leak; e.g. browser 404 error
      • provide APIs
  • create trust and delight
    • trust is your most sacred resource; see Netflix case
    • delight; Google's April Fools day

2012년 9월 24일 월요일

추창민, 광해

광해
별 다섯.

고리타분한 왕실을 상식으로 바꿔 보려한 한 광대의 이야기.

요즘 대선 철이라 그런지
작금의 정치상황을
보고 얘기하려 한것은 아닌지.
만약 그렇다면 제일 가까운 이는  xxx가 아닌가 싶다.

비록 정치에 대한 경험은 떨어지지만
국민을 가엽게 여기는 맘으로
모든 것을 헤쳐나가고자 하는 이.

누구나 측은지심을 가지고 있고
상식만 가지고 있다면
왕의 자리에 누가 앉든 중요하지 않다.
그 자리가 그 사람을 왕으로 만들겠지.

광대의 목소리 vs 왕의 목소리
남자의 목소리에 대한 매력의 극과 극을 보여준다.
누구나 노력을 하면 목소리도 바꿀 수 있다고 한다.
존 내버로는 주름살 제거 수술 보다는
목소리에 대한 투자가 훨씬 현명한 일이라 했다.
남자들이여 목소리에 투자하라~

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년 9월 6일 목요일

응답하라 1997



지금보다 절실한 나중이란없다. 나중이란 영원히 오지않을수도 있기때문이다. 눈앞에 와있는 지금이 아닌 안올지도 모르는 다음 기회를 얘기하기엔 삶은 그리 길지 않다


누구를 좋아하는 건 선택의 문제가 아냐. 가슴이 시키는 거야.

16화 - 첫사랑이 이루어지지 않는 이유.

2가지 재미난 상징들!


1.
윤재
+ 넌 어떻게 나보다 우리 형 마음을 그렇게 잘알아? 
정신과 가서 사람들 맘 좀 들여다 보고 치료좀 해주라고

준희
= 남의 마음은 잘 보는데 내맘을 잘 몰라서
내 맘부터 정리하고(포장된 박스를 테이프로 봉인한다. )

2.
준희 
+ 이게 마지막 짐입니다. 
- 아유 그래도 또한번 확인해보세요. 
항상 갔다가 한번은 되돌아 오더라고요. 
꼭 하나씩 빼먹고 오더라고요.
+ 그래요? (집으로 올라가자 윤재가 있고 그와 마지막 인사를 한다. )

후자에서 소름 돋았음.

----------
저마다의 첫사랑이 아름다운 이유는
첫사랑이 그닥 아름다웠기 때문만은 아니다.
그 첫사랑의 시절엔
영악하지 못한 젊음이 있었고
지독할 만큼 순수한 내가 있었으며
주체할 수 없이 뜨거운 당신이 있었기 때문일 것이다.
그리고 다시는 젊고 그 순수한 열정의 시절로
돌아갈 수 없다는 걸 이미 알고 있기 때문이다.

첫사랑은 무모하다.
영악한 계산없이 순수와 열정만으로
모든 것을 던져 버리고는
결국 실패한다.
하지만 그래서 극적이다.
다시는 가져볼 수 없는 체온과 감정들로 얽혀진 무모한 이야기들
첫사랑은 그래서 내 생애 가장 극적인 드라마다
그리하여 실패해도 좋다
희극보다는 비극적 결말이 오래 남는 법이며
그리하여 실패한 첫사랑의 비극적 드라마 한편쯤
내 삶 한자락에 남겨두는 것도
폼나는 일이다.

첫사랑은 시절이다.
흘러가면 그 뿐이다
이제 맞게 되는 새로운 시절엔
새로운 사랑에게 기회를 줘야 한다.

첫사랑의 체온과 순수함은 아닐지라도
그 상처로 인해 조금은 자라고 성숙해진
어른의 사랑을 기다려야 한다
기다리는 사람만이 사랑을 꿈꿀 수 있다.
---------
로맨스가 지나면 생활이 온다.
순수함은 때묻어 가고 열정은 얼어붙어 가며
젊음은 영악함으로 나이들어 간다
그리하여 순수했던 시절의 첫사랑은
이제 고단하고 지난한 일상이 된다.
마치 첫사랑은 이루어지지 않은것처럼 보이는 이유다
누구도 성공한 첫사랑의 로맨스는 이야기하지 않으니까

2012년 8월 31일 금요일

조 내버로, 우리는 어떻게 설득 당하는가

28
미모 보상(beauty dividend). 잘 생긴 사람이 더 돈을 잘 벌고 더 빨리 승진한다. 불공평해 보일수도있지만 이것이 현실이다. 비언어에 통달하기 위해서는 반드시 외모에도 관심을 기울여야 한다.

33
말 따라하기(verbal mirroring)
안타깝게도 대다수 사람들은 대화를 할때 자신만의 언어로  주로 사용한다. 대화의 효과를 극대화 하려면 상대방의 언어로 대화해야 한다. 상대방이 child란 단어를 사용한다면 나도 kid나 daughter대신 child를 사용하는 식이다.

38
깨진 유리창 법칙
어떤지역이 외관상 무질서한 모습을 보일경우 그 지역의 범죄나 반사회적 사건이 일어날 확률도 같이 높아진다는 이론

44
편안/불안 패러다임

131
우리는 대체로 권위있고 유능해 보이는 사람의 말을 잘 듣는 편이다. 비언어가 그다지 중요하지 않다고 생각하는 사람이 있다면 회의실 상점 레스토랑에 들어가 누군가를 보았을때 그의 자세에서 열의가 느껴지는지 무관심이 느껴지는지에 따라 그에 대한 인상이 얼마나 달라졌는지 떠올려보라. 자세는 멀리서보더라도 즉각적으로 그 사람의 전반적 이미지를 형성한다.

137
목소리의 힘.
만약 누군가 내게 주름살 제거 수술을 받는게 나을지, 아니며 시간을 조금 들여 목소리를 개선하는게 나을지 묻는 다면 나는 수술비로 쓸 돈을 저축해두고 목소리를 가다듬는 편이 훨씬 낫다고 대답할 것이다.

151
모든 동물은 본능적으로 뛰어난 외모를 지닌 개체를 선택한다. 가령 공작은 가장 화려한 꼬리를 지닌 개체가, 사자는 가장 큰 갈기를 지닌 개체가, 종마는 가장 위풍당당해 보이는 개체가 선택을 받는다. 태어날때부터 어떤한 선입견이 없는 상태에서도 인간은 미를 감지한다 아기가 추한 얼굴보다 아름다운 얼굴을 더 오래 응시하는 이유도 여기에 있다.

163
옷이 사람을 만든다는 격언에는 강력한 진실이 담겨있다. 사람은 자신이 입은 옷에 따라 페르소나(persona-다른 사람들 눈에 비치는 외적 인격, 가면을 쓴 인격)가 달라진다는 것이다.

166
사무실 조명과 생산성의 관계.
생산성 향상은 환경변화가 야기한 자극에서 비롯된 것. 시간이 지나 처음의 신선함이 사라지면 사람들이 변화에 익숙해져서(적응성은 인간의 특징이다) 행동변화 역시 사라진다.

167
정치인들이 쓰리 버튼이 아닌 투 버튼 정장만 입는 사실을 아는가? 흉부를 드러낼수록 더 정직한 사람으로 인식되기 때문이다.

183
편안함 보상(comfort dividend)
특정 치과의사 가족주치의를 계속 찾는 이유는 그들의 솜씨가 뛰어난 것은 물론 편안함까지 주기 때문이다.

193
조명을 많이 켜둘수록 더 많은 사람들이
주유소에 들른다는 사실을 깨달았다.
밝은 곳이 더 안전한 곳이라 생각.
편안과 안전의 동일시.

237
모든 사물은 엔트로피가 증가하는 방향으로
즉 에너지가 고갈되어 허물어지는 방향으로
변해간다는 열역학 제2법칙을 들어본적 있을 것이다.
나는 이 엔트로피의 법칙을 감정에 적용하여
그들이 자발적으로 감정을 소진시키게 했다.
잠시 기다리면 그들은 진이 다 빠져서
더 이상 감정표현을 할 수없게 된다.
그러면 나는 심문을 시작했다.

245
일에서 유머와 재미를 찾아 부정적 스트레스를 해소할 수단으로 삼아보자. (유머 유머..)

280
전화통화에 관한 법칙
침묵은 금이다. 누군가 불쾌한 얘기를 할때는 한참동안 침묵을 지키는 것도 좋다. 이 강력한 비언어는 사람들의 주의를 당신에게 집중시킨다.
한참 말을 멈춰서 상대방이 말을 하도록 하라. 대다수 사람들은 침묵을 두려워하기 때문에 그 적막함을 채우려 하다가 본의 아니게 비밀등을 발설하곤 한다.(이건 소개팅 자리에서도 비슷하다. 적막이 무서워 말도 안되는 얘기를 하다가 매력을 잃는것과 비슷한 듯)

283
어떤 경우에도 시각자료에 표시된 내용을 그대로 읽거나 되풀이해서 말하지 말라
청중이 당신의 얘기를 더 듣고 싶어하는 상태에서 프레젠테이션이 끝나야 한다. 주제 대해 모든 것을 다 쏟아낸 발표자는 호평을 받지 못한다.

289
결국 모든 준비는 자신감을 얻기위해서 하는 것이다. 자신감은 그 무엇으로도 대체할 수 없다. 준비가 충분하다는 믿음을 가지고 자신있게 면접장으로 들어가라.