The WebKit Open Source Project

WebKit Coding Style Guidelines

インデント(字下げ) Indentation



  1. Use spaces, not tabs. Tabs should only appear in files that require them for semantic meaning, like Makefiles.
    タブではなくスペース(空白文字)を使います。 タブを使うのは、Makefile のような、タブ文字であることが要求されるファイル内のみとします。
  2. The indent size is 4 spaces.
    インデントのサイズはスペース4文字です。

    Right:

    int main()
    {
        return 0;
    }
    

    Wrong:

    int main() 
    {
            return 0;
    }
    
  3. The contents of an outermost namespace block (and any nested namespaces with the same scope) should not be indented. The contents of other nested namespaces should be indented.
    いちばん外側の namespace ブロック(同じスコープ上でネストしている namespace がある場合はそれも)の中身はインデントしません。 それ以外の場所でネストしている namespace では中身をインデントさせます。

    Right:

    // Document.h
    namespace WebCore {
    
    class Document {
        Document();
        ...
    };
    
    namespace NestedNamespace {
        ...
    }
    
    } // namespace WebCore
    
    // Document.cpp
    namespace WebCore {
    
    Document::Document()
    {
        ...
    }
    
    } // namespace WebCore
    

    Wrong:

    // Document.h
    namespace WebCore {
    
        class Document {
            Document();
            ...
        };
    
        namespace NestedNamespace {
        ...
        }
    
    } // namespace WebCore
    
    // Document.cpp
    namespace WebCore {
    
        Document::Document()
        {
            ...
        }
    
    } // namespace WebCore
    
  4. A case label should line up with its switch statement. The case statement is indented.
    case ラベルは switch 文と同じ位置に並べます。 case 文の内容はインデントしてください。

    Right:

    switch (condition) {
    case fooCondition:
    case barCondition:
        i++;
        break;
    default:
        i--;
    }
    

    Wrong:

    switch (condition) {
        case fooCondition:
        case barCondition:
            i++;
            break;
        default:
            i--;
    }
    
  5. Boolean expressions at the same nesting level that span multiple lines should have their operators on the left side of the line instead of the right side.
    ネスティングレベルが同じブール式(boolean expression)が複数行にまたがる場合、演算子を右側ではなく左側に置きます。

    Right:

    if (attr->name() == srcAttr
        || attr->name() == lowsrcAttr
        || (attr->name() == usemapAttr && attr->value().domString()[0] != '#'))
        return;
    

    Wrong:

    if (attr->name() == srcAttr ||
        attr->name() == lowsrcAttr ||
        (attr->name() == usemapAttr && attr->value().domString()[0] != '#'))
        return;
    

スペース(空白文字) Spacing

  1. Do not place spaces around unary operators.
    単項演算子の前後にはスペースをつけないようにします。

    Right:

    i++;
    

    Wrong:

    i ++;
    
  2. Do place spaces around binary and ternary operators.
    二項演算子、三項演算子の前後にはスペースをつけます。

    Right:

    y = m * x + b;
    f(a, b);
    c = a | b;
    return condition ? 1 : 0;
    

    Wrong:

    y=m*x+b;
    f(a,b);
    c = a|b;
    return condition ? 1:0;
    
  3. Do not place spaces before comma and semicolon.
    コンマとセミコロンの前にはスペースをつけません。

    Right:

    for (int i = 0; i < 10; ++i)
        doSomething();
    
    f(a, b);
    

    Wrong:

    for (int i = 0 ; i < 10 ; ++i)
        doSomething();
    
    f(a , b) ;
    
  4. Place spaces between control statements and their parentheses.
    制御文と括弧の間にはスペースをつけます。

    Right:

    if (condition)
        doIt();
    

    Wrong:

    if(condition)
        doIt();
    
  5. Do not place spaces between a function and its parentheses, or between a parenthesis and its content.
    関数名と括弧の間にスペースをつけません。括弧と引数の間にもスペースをつけません。

    Right:

    f(a, b);
    

    Wrong:

    f (a, b);
    f( a, b );
    

改行 Line breaking

  1. Each statement should get its own line.
    それぞれの文 (statement) ごとに一行を割り当てるようにします。

    Right:

    x++;
    y++;
    if (condition)
        doIt();
    

    Wrong:

    x++; y++;
    if (condition) doIt();
    
  2. An else statement should go on the same line as a preceding close brace if one is present, else it should line up with the if statement.
    else 文の前に右括弧がある場合は、その右括弧と同じ行に else 文を続けます。

    Right:

    if (condition) {
        ...
    } else {
        ...
    }
    
    if (condition)
        doSomething();
    else
        doSomethingElse();
    
    if (condition)
        doSomething();
    else {
        ...
    }
    

    Wrong:

    if (condition) {
        ...
    }
    else {
        ...
    }
    
    if (condition) doSomething(); else doSomethingElse();
    
    if (condition) doSomething(); else {
        ...
    }
    
  3. An else if statement should be written as an if statement when the prior if concludes with a return statement.
    return 文で終わっている if の直後では、else if 文のかわりに単なる if 文を書きます。

    Right:

    if (condition) {
        ...
        return someValue;
    }
    if (condition) {
        ...
    }
    

    Wrong:

    if (condition) {
        ...
        return someValue;
    } else if (condition) {
        ...
    }
    

中括弧(ブレース) Braces

  1. Function definitions: place each brace on its own line.
    関数定義の場合:括弧それぞれに専用行を割り振ります。

    Right:

    int main()
    {
        ...
    }
    

    Wrong:

    int main() {
        ...
    }
    
  2. Other braces: place the open brace on the line preceding the code block; place the close brace on its own line.
    それ以外:左括弧はコードブロックの直前の行につけます。 右括弧には専用行を割り振ります。

    Right:

    class MyClass {
        ...
    };
    
    namespace WebCore {
        ...
    }
    
    for (int i = 0; i < 10; ++i) {
        ...
    }
    

    Wrong:

    class MyClass 
    {
        ...
    };
    
  3. One-line control clauses should not use braces unless comments are included or a single statement spans multiple lines.
    条件ブロック が1行ですみ、コメント挿入や複数行にまたがる単文を使っていない場合、括弧は使いません。

    Right:

    if (condition)
        doIt();
    
    if (condition) {
        // Some comment
        doIt();
    }
    
    if (condition) {
        myFunction(reallyLongParam1, reallyLongParam2, ...
            reallyLongParam5);
    }
    

    Wrong:

    if (condition) {
        doIt();
    }
    
    if (condition)
        // Some comment
        doIt();
    
    if (condition)
        myFunction(reallyLongParam1, reallyLongParam2, ...
            reallyLongParam5);
    
  4. Control clauses without a body should use empty braces:
    ループ本体がないブロックには、何も入っていない括弧を使います。

    Right:

    for ( ; current; current = current->next) { }
    

    Wrong:

    for ( ; current; current = current->next);
    

ヌル、false、ゼロ Null, false and 0

  1. In C++, the null pointer value should be written as 0. In C, it should be written as NULL. In Objective-C and Objective-C++, follow the guideline for C or C++, respectively, but use nil to represent a null Objective-C object.

  2. C++ では、ヌルポインタの値を 0 と書きます。 C では NULL と書きます。 Objective-C と Objective-C++ ではそれぞれ C と C++ のガイドラインに従いますが、Objective-C のヌルオブジェクトは nil を使って表します。
  3. C++ and C bool values should be written as true and false. Objective-C BOOL values should be written as YES and NO.

  4. C++ と C の bool 値は true、false と書きます。 Objective-C の BOOL 値は YES、NO と書きます。
  5. Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.

    true/false、ヌル/非ヌル、ゼロ/非ゼロの判定はすべて、値そのものの一致/不一致を使わない方法で行ってください。

    Right:

    if (condition)
        doIt();
        
    if (!ptr)
        return;
    
    if (!count)
        return;
    

    Wrong:

    if (condition == true)
        doIt();
        
    if (ptr == NULL)
        return;
        
    if (count == 0)
        return;
    
  6. In Objective-C, instance variables are initialized to zero automatically. Don't add explicit initializations to nil or NO in an init method.

  7. Objecttive-C では、インスタンス変数は自動的にゼロに初期化されます。 nil や NO への明示的な初期化処理を初期化メソッド内に追加しないでください。

浮動小数点数の表記 Floating point literals

  1. Unless required in order to force floating point math, do not append .0, .f and .0f to floating point literals.
    浮動小数点方式での演算を明示せざるを得ない場合を除いて、浮動小数点型リテラルには .0、.f、.0f を追加しません。

    Right:

    const double duration = 60;
    
    void setDiameter(float diameter)
    {
        radius = diameter / 2;
    }
    
    setDiameter(10);
    
    const int framesPerSecond = 12;
    double frameDuration = 1.0 / framesPerSecond;
    

    Wrong:

    const double duration = 60.0;
    
    void setDiameter(float diameter)
    {
        radius = diameter / 2.f;
    }
    
    setDiameter(10.f);
    
    const int framesPerSecond = 12;
    double frameDuration = 1 / framesPerSecond; // integer division 整数除算になる
    

名前 Names

  1. Use CamelCase. Capitalize the first letter, including all letters in an acronym, in a class, struct, protocol, or namespace name. Lower-case the first letter, including all letters in an acronym, in a variable or function name.
    CamelCase を使います。 class、struct、protocol、namespace の名前では、(最初の単語の)最初の文字を大文字にします。 単語が頭字語(acronym)ならすべての文字を大文字にします。 変数名、関数名では(最初の単語の)最初の文字を小文字にしてください。 単語が頭字語ならすべての文字を小文字にします。

    Right:

    struct Data;
    size_t bufferSize;
    class HTMLDocument;
    String mimeType();
    

    Wrong:

    struct data;
    size_t buffer_size;
    class HtmlDocument;
    String MIMEType();
    
  2. Use full words, except in the rare case where an abbreviation would be more canonical and easier to understand.
    略称のほうが標準的でわかりやすくなるレアケースを除き、省略していない単語を使います。

    Right:

    size_t characterSize;
    size_t length;
    short tabIndex; // more canonical このほうが普通
    

    Wrong:

    size_t charSize;
    size_t len;
    short tabulationIndex; // bizarre くどい
    
  3. Data members in C++ classes should be private. Static data members should be prefixed by "s_". Other data members should be prefixed by "m_".
    C++ のデータメンバーは private にします。 static なデータメンバーには "s_" のプレフィックスをつけます。 それ以外のデータメンバーには "m_" のプレフィックスをつけます。

    Right:

    class String {
    public:
        ...
    
    private:
        short m_length;
    };
    

    Wrong:

    class String {
    public:
        ...
    
        short length;
    };
    
  4. Prefix Objective-C instance variables with "_".
    Objective-C のインスタンス変数には "_" のプレフィックスをつけます。

    Right:

    @class String
        ...
        short _length;
    @end
    

    Wrong:

    @class String
        ...
        short length;
    @end
    
  5. Precede boolean values with words like "is" and "did".
    ブール型の値には "is"(「~であるか?」)や "did"(「~したか?」)などの語句を前につけます。

    Right:

    bool isValid;
    bool didSendData;
    

    Wrong:

    bool valid;
    bool sentData;
    
  6. Precede setters with the word "set". Use bare words for getters. Setter and getter names should match the names of the variables being set/gotten.
    setter は名前の先頭に "set" をつけます。 getter は(先頭に get などつけずに)そのままの語句を使います。 setter と getter の名前は設定 (set)/取り出し (get) を行う変数の名前に合わせてください。

    Right:

    void setCount(size_t); // sets m_count
    size_t count(); // returns m_count
    

    Wrong:

    void setCount(size_t); // sets m_theCount
    size_t getCount();
    
  7. Use descriptive verbs in function names.
    関数名には(その動作の)説明的な動詞を入れます。

    Right:

    bool convertToASCII(short*, size_t);
    

    Wrong:

    bool toASCII(short*, size_t);
    
  8. Leave meaningless variable names out of function declarations. A good rule of thumb is if the parameter type name contains the parameter name (without trailing numbers or pluralization), then the parameter name isn't needed. Usually, there should be a parameter name for bools, strings, and numerical types.
    無意味な変数名は関数宣言から取り除きます。 原則的にいえば、ある引数の型に対応する引数名がひとつですむ(番号をつけたり複数の名前を使わずにすむ)場合、引数名のほうは不要です。 一般的にいって、ブール型、文字列型、数値型には引数名をつけたほうがよいでしょう。

    Right:

    void setCount(size_t);
    
    void doSomething(ScriptExecutionContext*);
    

    Wrong:

    void setCount(size_t count);
    
    void doSomething(ScriptExecutionContext* context);
    
  9. Objective-C method names should follow the Cocoa naming guidelines — they should read like a phrase and each piece of the selector should start with a lowercase letter and use intercaps.

  10. Objective-C のメソッド名は Cocoa の命名ガイドラインに従います。 名前は語句として読めるようなものとし、その最初の単語節は小文字で始め、それ以降の各単語節は先頭文字を小文字にします(intercaps)。
  11. Enum members should user InterCaps with an initial capital letter.

  12. 列挙型(enum)のメンバーは大文字で始め、各単語節の先頭を大文字にします。
  13. Prefer const to #define. Prefer inline functions to macros.

  14. なるべく #define よりも const を、マクロよりもインライン関数を使うようにします。
  15. #defined constants should use all uppercase names with words separated by underscores.

  16. #define の定数定義はすべて大文字を使い、単語をアンダースコアで区切ります。
  17. Macros that expand to function calls or other non-constant computation: these should be named like functions, and should have parentheses at the end, even if they take no arguments (with the exception of some special macros like ASSERT). Note that usually it is preferable to use an inline function in such cases instead of a macro.

    関数呼び出しや定数化できない計算処理に展開されるマクロの場合は、関数的な名前をつけ、引数を使わない場合であっても最後に括弧をつけるようにします(ASSERT のような一部の特殊なマクロは例外)。 念のためいっておくと、このような場合はマクロではなくインライン関数を使うのがふつうです。

    Right:

    #define WBStopButtonTitle() \
            NSLocalizedString(@"Stop", @"Stop button title")
    

    Wrong:

    #define WB_STOP_BUTTON_TITLE \
            NSLocalizedString(@"Stop", @"Stop button title")
    
    #define WBStopButtontitle \
            NSLocalizedString(@"Stop", @"Stop button title")
    
  18. #define, #ifdef "header guards" should be named exactly the same as the file (including case), replacing the '.' with a '_'.
    #ifdef と #define による「ヘッダガード」(二重読み込み防止用のマクロ)は、ファイル名と同じ名前にします(大文字/小文字の対応も含めて)。 '.' は '_' に置き換えます。

    Right:

    // HTMLDocument.h
    #ifndef HTMLDocument_h
    #define HTMLDocument_h
    

    Wrong:

    // HTMLDocument.h
    #ifndef _HTML_DOCUMENT_H_
    #define _HTML_DOCUMENT_H_
    

その他の作法 Other Punctuation

  1. Constructors for C++ classes should initialize all of their members using C++ initializer syntax. Each member (and superclass) should be indented on a separate line, with the colon or comma preceding the member on that line.
    C++ クラスのコンストラクターは C++ の初期化構文を使ってすべてのメンバーを初期化するようにします。 メンバー(やスーパークラス)ごとに一行を使ってインデントを行い、コロンやコンマはメンバーの前につけます。

    Right:

    MyClass::MyClass(Document* doc)
        : MySuperClass()
        , m_myMember(0)
        , m_doc(doc)
    {
    }
    
    MyOtherClass::MyOtherClass()
        : MySuperClass()
    {
    }
    

    Wrong:

    MyClass::MyClass(Document* doc) : MySuperClass()
    {
        m_myMember = 0;
        m_doc = doc;
    }
    
    MyOtherClass::MyOtherClass() : MySuperClass() {}
    
  2. Pointer types in non-C++ code — Pointer types should be written with a space between the type and the * (so the * is adjacent to the following identifier if any).
    C++ ではないコード内にあるポインタの場合、ポインタ型は、型名と * の間にスペースをひとつ空けて書きます(ので、* は直後の識別子にぴったりくっつくことになります)。
  3. Pointer and reference types in C++ code — Both pointer types and reference types should be written with no space between the type name and the * or &.
    C++ コード内のポインタの場合、ポインタ型、参照型ともに、型名と * や & の間にスペースを空けずに書きます。

    Right:

    Image* SVGStyledElement::doSomething(PaintInfo& paintInfo)
    {
        SVGStyledElement* element = static_cast<SVGStyledElement*>(node());
        const KCDashArray& dashes = dashArray();
    

    Wrong:

    Image *SVGStyledElement::doSomething(PaintInfo &paintInfo)
    {
        SVGStyledElement *element = static_cast<SVGStyledElement *>(node());
        const KCDashArray &dashes = dashArray();
    

#include 文 #include Statements

  1. All implementation files must #include "config.h" first. Header files should never include "config.h".
    すべての実装ファイル(implementation file)は、必ず最初に #include "config.h" を行ってください。 ヘッダファイルでは "config.h" を一切インクルードしないようにします。

    Right:

    // RenderLayer.h
    #include "Node.h"
    #include "RenderObject.h"
    #include "RenderView.h"
    

    Wrong:

    // RenderLayer.h
    #include "config.h"
    
    #include "RenderObject.h"
    #include "RenderView.h"
    #include "Node.h"
    
  2. All implementation files must #include the primary header second, just after "config.h". So for example, Node.cpp should include Node.h first, before other files. This guarantees that each header's completeness is tested. This also assures that each header can be compiled without requiring any other header files be included first.
    すべての実装ファイルは、基本ヘッダー(primary header)の #include を必ず二番目、すなわち "config.h" の直後に行ってください。 たとえば、Node.cpp ではまず Node.h を他のファイルよりも先にインクルードします。 これによりヘッダーの完全性が間違いなく検査されるようになります。 さらにこれで、各ヘッダーが他のヘッダーを先にインクルードせずにコンパイルできることも保証されます。
  3. Other #include statements should be in sorted order (case sensitive, as done by the command-line sort tool or the Xcode sort selection command). Don't bother to organize them in a logical order.
    それ以外の #include は(コマンドラインのソートツールや Xcode のソートコマンドなどが行うように、大文字/小文字を区別する形で)ソートしておきます。 論理的な依存順にまとめる必要はありません。

    Right:

    // HTMLDivElement.cpp
    #include "config.h"
    #include "HTMLDivElement.h"
    
    #include "Attribute.h"
    #include "HTMLElement.h"
    #include "QualifiedName.h"
    
    

    Wrong:

    // HTMLDivElement.cpp
    #include "HTMLElement.h"
    #include "HTMLDivElement.h"
    #include "QualifiedName.h"
    #include "Attribute.h"
    
  4. Includes of system headers must come after includes of other headers.
    システムヘッダーのインクルードは必ず、それ以外のヘッダーの後につけます。

    Right:

    // ConnectionQt.cpp
    #include "ArgumentEncoder.h"
    #include "ProcessLauncher.h"
    #include "WebPageProxyMessageKinds.h"
    #include "WorkItem.h"
    #include <QApplication>
    #include <QLocalServer>
    #include <QLocalSocket>
    

    Wrong:

    // ConnectionQt.cpp
    #include "ArgumentEncoder.h"
    #include "ProcessLauncher.h"
    #include <QApplication>
    #include <QLocalServer>
    #include <QLocalSocket>
    #include "WebPageProxyMessageKinds.h"
    #include "WorkItem.h"
    

using 文 "using" Statements

  1. In header files, do not use "using" statements in namespace (or global) scope.
    ヘッダーファイル中では、ネームスペースのスコープ(あるいはグローバルスコープ)で using 文を使わないでください。

    Right:

    // wtf/Vector.h
    
    namespace WTF {
    
    class VectorBuffer {
        using std::min;
        ...
    };
    
    } // namespace WTF
    

    Wrong:

    // wtf/Vector.h
    
    namespace WTF {
    
    using std::min;
        
    class VectorBuffer {
        ...
    };
    
    } // namespace WTF
    
  2. In header files in the WTF sub-library, however, it is acceptable to use "using" declarations at the end of the file to import one or more names in the WTF namespace into the global scope.
    ただし、WTF サブライブラリ内のヘッダーファイル中では、ファイルの最後で using 宣言を使い、WTF ネームスペース内の名前をグローバルスコープにインポートすることが認められています。

    Right:

    // wtf/Vector.h
    
    namespace WTF {
    
    } // namespace WTF
    
    using WTF::Vector;
    

    Wrong:

    // wtf/Vector.h
    
    namespace WTF {
    
    } // namespace WTF
    
    using namespace WTF;
    

    Wrong:

    // runtime/UString.h
    
    namespace WTF {
    
    } // namespace WTF
    
    using WTF::PlacementNewAdopt;
    
  3. In C++ implementation files, do not use statements of the form "using std::foo" to import names in the standard template library. Use "using namespace std" instead.
    C++ の実装ファイル中では、標準テンプレートライブラリ内の名前のインポートに "using std::foo" 形式の use 文を使わないでください。 そのかわりに "using namespace std" を使います。

    Right:

    // HTMLBaseElement.cpp
    
    using namespace std;
    
    namespace WebCore {
    
    } // namespace WebCore
    

    Wrong:

    // HTMLBaseElement.cpp
    
    using std::swap;
    
    namespace WebCore {
    
    } // namespace WebCore
    
  4. In implementation files, if a "using namespace" statement is for a nested namespace whose parent namespace is defined in the file, put the statement inside that namespace definition.
    実装ファイル中で、"using namespace" 文がネストしたネームスペースを指していて、それの元になるネームスペースが同じファイル中で定義されている場合、using 文はそのネームスペース定義内に入れます。

    Right:

    // HTMLBaseElement.cpp
    
    namespace WebCore {
    
    using namespace HTMLNames;
    
    } // namespace WebCore
    

    Wrong:

    // HTMLBaseElement.cpp
    
    using namespace WebCore::HTMLNames;
    
    namespace WebCore {
    
    } // namespace WebCore
    
  5. In implementation files, put all other "using" statements at the beginning of the file, before any namespace definitions and after any "include" statements.
    実装ファイル中では、それ以外の using 文はすべてファイルの先頭位置、つまり include 文の後かつ namespace 定義の前に置きます。

    Right:

    // HTMLSelectElement.cpp
    
    using namespace std;
    
    namespace WebCore {
    
    } // namespace WebCore
    

    Wrong:

    // HTMLSelectElement.cpp
    
    namespace WebCore {
    
    using namespace std;
    
    } // namespace WebCore
    

クラス Classes

  1. Use a constructor to do an implicit conversion when the argument is reasonably thought of as a type conversion and the type conversion is fast. Otherwise, use the explicit keyword or a function returning the type. This only applies to single argument constructors.
    (クラスが)引数を型変換するようなものであり、なおかつその型変換が高速であるときは、コンストラクタを使って暗黙の型変換を行います。 そうでないときは explicit キーワード、もしくはしかるべき型を返す関数を使います。 これが適用されるのは、引数がひとつのコンストラクタのみです。

    Right:

    class LargeInt {
    public:
        LargeInt(int);
    ...
    
    class Vector {
    public:
        explicit Vector(int size); // Not a type conversion. (型変換ではない)
        PassOwnPtr<Vector> create(Array); // Costly conversion. (変換コストが大きい)
    ...
    
    

    Wrong:

    class Task {
    public:
        Task(ScriptExecutionContext*); // Not a type conversion. (型変換ではない)
        explicit Task(); // No arguments. (引数なし)
        explicit Task(ScriptExecutionContext*, Other); // More than one argument. (引数ふたつ以上)
    ...
    

コメント Comments

  1. Use only one space before end of line comments and in between sentences in comments.
    行末コメントの前やコメント内の語の間には、スペースを「1文字だけ」空けます。

    Right:

    f(a, b); // This explains why the function call was done. This is another sentence.
    

    Wrong:

    int i;    // This is a comment with several spaces before it, which is a non-conforming style.
    double f; // This is another comment.  There are two spaces before this sentence which is a non-conforming style.
    
  2. Make comments look like sentences by starting with a capital letter and ending with a period (punctation). One exception may be end of line comments like this "if (x == y) // false for NaN".
    コメントは大文字で始めてピリオド(句点)で終わらせ、文章のようにします。 "if (x == y) // false for NaN" のような行末コメントは例外としてもかまいません。
  3. Use FIXME: (without attribution) to denote items that need to be addressed in the future.
    将来の必要事項を示すには FIXME: を使います(それが誰によるものかは書きません)。
  4. Right:

    drawJpg(); // FIXME: Make this code handle jpg in addition to the png support.
    

    Wrong:

    drawJpg(); // FIXME(joe): Make this code handle jpg in addition to the png support.
    
    drawJpg(); // TODO: Make this code handle jpg in addition to the png support.