페이지

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