求助:出现错误multiple storage classes in declaration of 'rdbmsState'

cugege 2003-09-12 04:04:07
开发语言: C
操作系统:UNIX

我在文件a.c中使用了"static int rdbmsState = 0;",在另外一个文件b.c中使用了
"extern static int rdbmsState;",但是编译时出现如下错误:

b.c:172: multiple storage classes in declaration of `rdbmsState'
*** Error code 1
make: Fatal error: Command failed for target `b.o'

请赐教如何修改。
谢谢!

...全文
3610 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhumerchant 2003-09-12
  • 打赏
  • 举报
回复
MSDN上的解释:
“When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared).”
用static修饰一个变量或者函数时,表示该名字只能在文件内部使用,文件外部是看不到该名字的。
louguoqiang 2003-09-12
  • 打赏
  • 举报
回复
b.c中的extern static int rdbmsState;
改为
extern int rdbmsState;
Table of Contents Header Files The #define Guard Header File Dependencies Inline Functions The -inl.h Files Function Parameter Ordering Names and Order of Includes Scoping Namespaces Nested Classes Nonmember, Static Member, and Global Functions Local Variables Static and Global Variables Classes Doing Work in Constructors Default Constructors Explicit Constructors Copy Constructors Structs vs. Classes Inheritance Multiple Inheritance Interfaces Operator Overloading Access Control Declaration Order Write Short Functions Google-Specific Magic Smart Pointers cpplint Other C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and Predecrement Use of const Integer Types 64-bit Portability Preprocessor Macros 0 and NULL sizeof Boost C++0x Naming General Naming Rules File Names Type Names Variable Names Constant Names Function Names Namespace Names Enumerator Names Macro Names Exceptions to Naming Rules Comments Comment Style File Comments Class Comments Function Comments Variable Comments Implementation Comments Punctuation, Spelling and Grammar TODO Comments Deprecation Comments Formatting Line Length Non-ASCII Characters Spaces vs. Tabs Function Declarations and Definitions Function Calls Conditionals Loops and Switch Statements Pointer and Reference Expressions Boolean Expressions Return Values Variable and Array Initialization Preprocessor Directives Class Format Constructor Initializer Lists Namespace Formatting Horizontal Whitespace Vertical Whitespace Exceptions to the Rules Existing Non-conformant Code Windows Code Important Note Displaying Hidden Details in this Guide link ▶This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below. Hooray! Now you know you can expand points to get more details. Alternatively, there's an "expand all" at the top of this document. Background C++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain. The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively. Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting. One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency. Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted. Open-source projects developed by Google conform to the requirements in this guide. Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language. Header Files In general, every .cc file should have an associated .h file. There are some common exceptions, such as unittests and small .cc files containing just a main() function. Correct use of header files can make a huge difference to the readability, size and performance of your code. The following rules will guide you through the various pitfalls of using header files. The #define Guard link ▶All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be ___H_. To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file foo/src/bar/baz.h in project foo should have the following guard: #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_ ... #endif // FOO_BAR_BAZ_H_ Header File Dependencies link ▶Don't use an #include when a forward declaration would suffice. When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, we prefer to minimize includes, particularly includes of header files in other header files. You can significantly minimize the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having to #include "file/base/file.h". How can we use a class Foo in a header file without access to its definition? We can declare data members of type Foo* or Foo&. We can declare (but not define) functions with arguments, and/or return values, of type Foo. (One exception is if an argument Foo or const Foo& has a non-explicit, one-argument constructor, in which case we need the full definition to support automatic type conversion.) We can declare static data members of type Foo. This is because static data members are defined outside the class definition. On the other hand, you must include the header file for Foo if your class subclasses Foo or has a data member of type Foo. Sometimes it makes sense to have pointer (or better, scoped_ptr) members instead of object members. However, this complicates code readability and imposes a performance penalty, so avoid doing this transformation if the only purpose is to minimize includes in header files. Of course, .cc files typically do require the definitions of the classes they use, and usually have to include several header files. Note: If you use a symbol Foo in your source file, you should bring in a definition for Foo yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if Foo is used in myfile.cc, it's ok to #include (or forward-declare) Foo in myfile.h, instead of myfile.cc. Inline Functions link ▶Define functions inline only when they are small, say, 10 lines or less. Definition: You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism. Pros: Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions. Cons: Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. Decision: A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls! Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed). It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators. The -inl.h Files link ▶You may use file names with a -inl.h suffix to define complex inline functions when needed. The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sites. However, implementation code properly belongs in .cc files, and we do not like to have much actual code in .h files unless there is a readability or performance advantage. If an inline function definition is short, with very little, if any, logic in it, you should put the code in your .h file. For example, accessors and mutators should certainly be inside a class definition. More complex inline functions may also be put in a .h file for the convenience of the implementer and callers, though if this makes the .h file too unwieldy you can instead put that code in a separate -inl.h file. This separates the implementation from the class definition, while still allowing the implementation to be included where necessary. Another use of -inl.h files is for definitions of function templates. This can be used to keep your template definitions easy to read. Do not forget that a -inl.h file requires a #define guard just like any other header file. Function Parameter Ordering link ▶When defining a function, parameter order is: inputs, then outputs. Parameters to C/C++ functions are either input to the function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will be non-const pointers. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. Parameters that are both input and output (often classes/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule. Names and Order of Includes link ▶Use standard order for readability and to avoid hidden dependencies: C library, C++ library, other libraries' .h, your project's .h. All of a project's header files should be listed as descentants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory). For example, google-awesome-project/src/base/logging.h should be included as #include "base/logging.h" In dir/foo.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows: dir2/foo2.h (preferred location — see details below). C system files. C++ system files. Other libraries' .h files. Your project's .h files. The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The easiest way to achieve this is to make sure that every one of them is the first .h file #included in some .cc. dir/foo.cc and dir2/foo2.h are often in the same directory (e.g. base/basictypes_test.cc and base/basictypes.h), but can be in different directories too. Within each section it is nice to order the includes alphabetically. For example, the includes in google-awesome-project/src/foo/internal/fooserver.cc might look like this: #include "foo/public/fooserver.h" // Preferred location. #include #include #include #include #include "base/basictypes.h" #include "base/commandlineflags.h" #include "foo/public/bar.h" Scoping Namespaces link ▶Unnamed namespaces in .cc files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a using-directive. Definition: Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope. Pros: Namespaces provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. For example, if two different projects have a class Foo in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, project1::Foo and project2::Foo are now distinct symbols that do not collide. Cons: Namespaces can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. Use of unnamed spaces in header files can easily cause violations of the C++ One Definition Rule (ODR). Decision: Use namespaces according to the policy described below. Unnamed Namespaces Unnamed namespaces are allowed and even encouraged in .cc files, to avoid runtime naming conflicts: namespace { // This is in a .cc file. // The content of a namespace is not indented enum { kUnused, kEOF, kError }; // Commonly used tokens. bool AtEof() { return pos_ == kEOF; } // Uses our namespace's EOF. } // namespace However, file-scope declarations that are associated with a particular class may be declared in that class as types, static data members or static member functions rather than as members of an unnamed namespace. Terminate the unnamed namespace as shown, with a comment // namespace. Do not use unnamed namespaces in .h files. Named Namespaces Named namespaces should be used as follows: Namespaces wrap the entire source file after includes, gflags definitions/declarations, and forward declarations of classes from other namespaces: // In the .h file namespace mynamespace { // All declarations are within the namespace scope. // Notice the lack of indentation. class MyClass { public: ... void Foo(); }; } // namespace mynamespace // In the .cc file namespace mynamespace { // Definition of functions is within scope of the namespace. void MyClass::Foo() { ... } } // namespace mynamespace The typical .cc file might have more complex detail, including the need to reference classes in other namespaces. #include "a.h" DEFINE_bool(someflag, false, "dummy flag"); class C; // Forward declaration of class C in the global namespace. namespace a { class A; } // Forward declaration of a::A. namespace b { ...code for b... // Code goes against the left margin. } // namespace b Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file. You may not use a using-directive to make all names from a namespace available. // Forbidden -- This pollutes the namespace. using namespace foo; You may use a using-declaration anywhere in a .cc file, and in functions, methods or classes in .h files. // OK in .cc files. // Must be in a function, method or class in .h files. using ::foo::bar; Namespace aliases are allowed anywhere in a .cc file, anywhere inside the named namespace that wraps an entire .h file, and in functions and methods. // Shorten access to some commonly used names in .cc files. namespace fbz = ::foo::bar::baz; // Shorten access to some commonly used names (in a .h file). namespace librarian { // The following alias is available to all files including // this header (in namespace librarian): // alias names should therefore be chosen consistently // within a project. namespace pd_s = ::pipeline_diagnostics::sidetable; inline void my_inline_function() { // namespace alias local to a function (or method). namespace fbz = ::foo::bar::baz; ... } } // namespace librarian Note that an alias in a .h file is visible to everyone #including that file, so public headers (those available outside a project) and headers transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible. Nested Classes link ▶Although you may use public nested classes when they are part of an interface, consider a namespace to keep declarations out of the global scope. Definition: A class can define another class within it; this is also called a member class. class Foo { private: // Bar is a member class, nested within Foo. class Bar { ... }; }; Pros: This is useful when the nested (or member) class is only used by the enclosing class; making it a member puts it in the enclosing class scope rather than polluting the outer scope with the class name. Nested classes can be forward declared within the enclosing class and then defined in the .cc file to avoid including the nested class definition in the enclosing class declaration, since the nested class definition is usually only relevant to the implementation. Cons: Nested classes can be forward-declared only within the definition of the enclosing class. Thus, any header file manipulating a Foo::Bar* pointer will have to include the full class declaration for Foo. Decision: Do not make nested classes public unless they are actually part of the interface, e.g., a class that holds a set of options for some method. Nonmember, Static Member, and Global Functions link ▶Prefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely. Pros: Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace. Cons: Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies. Decision: Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead. Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library. If you must define a nonmember function and it is only needed in its .cc file, use an unnamed namespace or static linkage (eg static int Foo() {...}) to limit its scope. Local Variables link ▶Place a function's variables in the narrowest scope possible, and initialize variables in the declaration. C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g. int i; i = f(); // Bad -- initialization separate from declaration. int j = g(); // Good -- declaration has initialization. Note that gcc implements for (int i = 0; i < 10; ++i) correctly (the scope of i is only the scope of the for loop), so you can then reuse i in another for loop in the same scope. It also correctly scopes declarations in if and while statements, e.g. while (const char* p = strchr(str, '/')) str = p + 1; There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope. // Inefficient implementation: for (int i = 0; i < 1000000; ++i) { Foo f; // My ctor and dtor get called 1000000 times each. f.DoSomething(i); } It may be more efficient to declare such a variable used in a loop outside that loop: Foo f; // My ctor and dtor get called once each. for (int i = 0; i < 1000000; ++i) { f.DoSomething(i); } Static and Global Variables link ▶Static or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and destruction. Objects with static storage duration, including global variables, static variables, static class member variables, and function static variables, must be Plain Old Data (POD): only ints, chars, floats, or pointers, or arrays/structs of POD. The order in which class constructors and initializers for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class type, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals. Likewise, the order in which destructors are called is defined to be the reverse of the order in which the constructors were called. Since constructor order is indeterminate, so is destructor order. For example, at program-end time a static variable might have been destroyed, but code still running -- perhaps in another thread -- tries to access it and fails. Or the destructor for a static 'string' variable might be run prior to the destructor for another variable that contains a reference to that string. As a result we only allow static variables to contain POD data. This rule completely disallows vector (use C arrays instead), or string (use const char []). If you need a static or global variable of a class type, consider initializing a pointer (which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw pointer, not a "smart" pointer, since the smart pointer's destructor will have the order-of-destructor issue that we are trying to avoid. Classes Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class. Doing Work in Constructors link ▶In general, constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. Definition: It is possible to perform initialization in the body of the constructor. Pros: Convenience in typing. No need to worry about whether the class has been initialized or not. Cons: The problems with doing work in constructors are: There is no easy way for constructors to signal errors, short of using exceptions (which are forbidden). If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state. If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion. If someone creates a global variable of this type (which is against the rules, but still), the constructor code will be called before main(), possibly breaking some implicit assumptions in the constructor code. For instance, gflags will not yet have been initialized. Decision: If your object requires non-trivial initialization, consider having an explicit Init() method. In particular, constructors should not call virtual functions, attempt to raise errors, access potentially uninitialized global variables, etc. Default Constructors link ▶You must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly. Definition: The default constructor is called when we new a class object with no arguments. It is always called when calling new[] (for arrays). Pros: Initializing structures by default, to hold "impossible" values, makes debugging much easier. Cons: Extra work for you, the code writer. Decision: If your class defines member variables and has no other constructors you must define a default constructor (one that takes no arguments). It should preferably initialize the object in such a way that its internal state is consistent and valid. The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly. If your class inherits from an existing class but you add no new member variables, you are not required to have a default constructor. Explicit Constructors link ▶Use the C++ keyword explicit for constructors with one argument. Definition: Normally, if a constructor takes one argument, it can be used as a conversion. For instance, if you define Foo::Foo(string name) and then pass a string to a function that expects a Foo, the constructor will be called to convert the string into a Foo and will pass the Foo to your function for you. This can be convenient but is also a source of trouble when things get converted and new objects created without you meaning them to. Declaring a constructor explicit prevents it from being invoked implicitly as a conversion. Pros: Avoids undesirable conversions. Cons: None. Decision: We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the class definition: explicit Foo(string name); The exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments. Copy Constructors link ▶Provide a copy constructor and assignment operator only when necessary. Otherwise, disable them with DISALLOW_COPY_AND_ASSIGN. Definition: The copy constructor and assignment operator are used to create copies of objects. The copy constructor is implicitly invoked by the compiler in some situations, e.g. passing objects by value. Pros: Copy constructors make it easy to copy objects. STL containers require that all contents be copyable and assignable. Copy constructors can be more efficient than CopyFrom()-style workarounds because they combine construction with copying, the compiler can elide them in some contexts, and they make it easier to avoid heap allocation. Cons: Implicit copying of objects in C++ is a rich source of bugs and of performance problems. It also reduces readability, as it becomes hard to track which objects are being passed around by value as opposed to by reference, and therefore where changes to an object are reflected. Decision: Few classes need to be copyable. Most should have neither a copy constructor nor an assignment operator. In many situations, a pointer or reference will work just as well as a copied value, with better performance. For example, you can pass function parameters by reference or pointer instead of by value, and you can store pointers rather than objects in an STL container. If your class needs to be copyable, prefer providing a copy method, such as CopyFrom() or Clone(), rather than a copy constructor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your class needs to be stored by value in an STL container), provide both a copy constructor and assignment operator. If your class does not need a copy constructor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy constructor and assignment operator in the private: section of your class, but do not provide any corresponding definition (so that any attempt to use them results in a link error). For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used: // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) Then, in class Foo: class Foo { public: Foo(int f); ~Foo(); private: DISALLOW_COPY_AND_ASSIGN(Foo); }; Structs vs. Classes link ▶Use a struct only for passive objects that carry data; everything else is a class. The struct and class keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-type you're defining. structs should be used for passive objects that carry data, and may have associated constants, but lack any functionality other than access/setting the data members. The accessing/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., constructor, destructor, Initialize(), Reset(), Validate(). If more functionality is required, a class is more appropriate. If in doubt, make it a class. For consistency with STL, you can use struct instead of class for functors and traits. Note that member variables in structs and classes have different naming rules. Inheritance link ▶Composition is often more appropriate than inheritance. When using inheritance, make it public. Definition: When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and interface inheritance, in which only method names are inherited. Pros: Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API. Cons: For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. The base class may also define some data members, so that specifies physical layout of the base class. Decision: All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead. Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: Bar subclasses Foo if it can reasonably be said that Bar "is a kind of" Foo. Make your destructor virtual if necessary. If your class has virtual methods, its destructor should be virtual. Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that data members should be private. When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived class. Rationale: If virtual is omitted, the reader has to check all ancestors of the class in question to determine if the function is virtual or not. Multiple Inheritance link ▶Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be pure interface classes tagged with the Interface suffix. Definition: Multiple inheritance allows a sub-class to have more than one base class. We distinguish between base classes that are pure interfaces and those that have an implementation. Pros: Multiple implementation inheritance may let you re-use even more code than single inheritance (see Inheritance). Cons: Only very rarely is multiple implementation inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution. Decision: Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are pure interfaces. In order to ensure that they remain pure interfaces, they must end with the Interface suffix. Note: There is an exception to this rule on Windows. Interfaces link ▶Classes that satisfy certain conditions are allowed, but not required, to end with an Interface suffix. Definition: A class is a pure interface if it meets the following requirements: It has only public pure virtual ("= 0") methods and static methods (but see below for destructor). It may not have non-static data members. It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected. If it is a subclass, it may only be derived from classes that satisfy these conditions and are tagged with the Interface suffix. An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed correctly, they must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See Stroustrup, The C++ Programming Language, 3rd edition, section 12.4 for details. Pros: Tagging a class with the Interface suffix lets others know that they must not add implemented methods or non static data members. This is particularly important in the case of multiple inheritance. Additionally, the interface concept is already well-understood by Java programmers. Cons: The Interface suffix lengthens the class name, which can make it harder to read and understand. Also, the interface property may be considered an implementation detail that shouldn't be exposed to clients. Decision: A class may end with Interface only if it meets the above requirements. We do not require the converse, however: classes that meet the above requirements are not required to end with Interface. Operator Overloading link ▶Do not overload operators except in rare, special circumstances. Definition: A class can define that operators such as + and / operate on the class as if it were a built-in type. Pros: Can make code appear more intuitive because a class will behave in the same way as built-in types (such as int). Overloaded operators are more playful names for functions that are less-colorfully named, such as Equals() or Add(). For some template functions to work correctly, you may need to define operators. Cons: While operator overloading can make code more intuitive, it has several drawbacks: It can fool our intuition into thinking that expensive operations are cheap, built-in operations. It is much harder to find the call sites for overloaded operators. Searching for Equals() is much easier than searching for relevant invocations of ==. Some operators work on pointers too, making it easy to introduce bugs. Foo + 4 may do one thing, while &Foo + 4 does something totally different. The compiler does not complain for either of these, making this very hard to debug. Overloading also has surprising ramifications. For instance, if a class overloads unary operator&, it cannot safely be forward-declared. Decision: In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them. Likewise, avoid the dangerous unary operator& at all costs, if there's any possibility the class might be forward-declared. However, there may be rare cases where you need to overload an operator to interoperate with templates or "standard" C++ classes (such as operator<<(ostream&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container. Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why. See also Copy Constructors and Function Overloading. Access Control link ▶Make data members private, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class to be protected when using Google Test). Typically a variable would be called foo_ and the accessor function foo(). You may also want a mutator function set_foo(). Exception: static const data members (typically called kFoo) need not be private. The definitions of accessors are usually inlined in the header file. See also Inheritance and Function Names. Declaration Order link ▶Use the specified order of declarations within a class: public: before private:, methods before data members (variables), etc. Your class definition should start with its public: section, followed by its protected: section and then its private: section. If any of these sections are empty, omit them. Within each section, the declarations generally should be in the following order: Typedefs and Enums Constants (static const data members) Constructors Destructor Methods, including static methods Data Members (except static const data members) Friend declarations should always be in the private section, and the DISALLOW_COPY_AND_ASSIGN macro invocation should be at the end of the private: section. It should be the last thing in the class. See Copy Constructors. Method definitions in the corresponding .cc file should be the same as the declaration order, as much as possible. Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See Inline Functions for more details. Write Short Functions link ▶Prefer small and focused functions. We recognize that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program. Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code. You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces. Google-Specific Magic There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere. Smart Pointers link ▶If you actually need pointer semantics, scoped_ptr is great. You should only use std::tr1::shared_ptr under very specific conditions, such as when objects need to be held by STL containers. You should never use auto_ptr. "Smart" pointers are objects that act like pointers but have added semantics. When a scoped_ptr is destroyed, for instance, it deletes the object it's pointing to. shared_ptr is the same way, but implements reference-counting so only the last pointer to an object deletes it. Generally speaking, we prefer that we design code with clear object ownership. The clearest object ownership is obtained by using an object directly as a field or local variable, without using pointers at all. On the other extreme, by their very definition, reference counted pointers are owned by nobody. The problem with this design is that it is easy to create circular references or other strange conditions that cause an object to never be deleted. It is also slow to perform atomic operations every time a value is copied or assigned. Although they are not recommended, reference counted pointers are sometimes the simplest and most elegant way to solve a problem. cpplint link ▶Use cpplint.py to detect style errors. cpplint.py is a tool that reads a source file and identifies many style errors. It is not perfect, and has both false positives and false negatives, but it is still a valuable tool. False positives can be ignored by putting // NOLINT at the end of the line. Some projects have instructions on how to run cpplint.py from their project tools. If the project you are contributing to does not, you can download cpplint.py separately. Other C++ Features Reference Arguments link ▶All parameters passed by reference must be labeled const. Definition: In C, if a function needs to modify a variable, the parameter must use a pointer, eg int foo(int *pval). In C++, the function can alternatively declare a reference parameter: int foo(int &val). Pros: Defining a parameter as reference avoids ugly code like (*pval)++. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that NULL is not a possible value. Cons: References can be confusing, as they have value syntax but pointer semantics. Decision: Within function parameter lists all references must be const: void Foo(const string &in, string *out); In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters. One case when you might want an input parameter to be a const pointer is if you want to emphasize that the argument is not copied, so it must exist for the lifetime of the object; it is usually best to document this in comments as well. STL adapters such as bind2nd and mem_fun do not permit reference parameters, so you must declare functions with pointer parameters in these cases, too. Function Overloading link ▶Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called. Definition: You may write a function that takes a const string& and overload it with another that takes const char*. class MyClass { public: void Analyze(const string &text); void Analyze(const char *text, size_t textlen); }; Pros: Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors. Cons: If a function is overloaded by the argument types alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function. Decision: If you want to overload a function, consider qualifying the name with some information about the arguments, e.g., AppendString(), AppendInt() rather than just Append(). Default Arguments link ▶We do not allow default function parameters, except in a few uncommon situations explained below. Pros: Often you have a function that uses lots of default values, but occasionally you want to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions. Cons: People often figure out how to use an API by looking at existing code that uses it. Default parameters are more difficult to maintain because copy-and-paste from previous code may not reveal all the parameters. Copy-and-pasting of code segments can cause major problems when the default arguments are not appropriate for the new code. Decision: Except as described below, we require all arguments to be explicitly specified, to force programmers to consider the API and the values they are passing for each argument rather than silently accepting defaults they may not be aware of. One specific exception is when default arguments are used to simulate variable-length argument lists. // Support up to 4 params by using a default empty AlphaNum. string StrCat(const AlphaNum &a, const AlphaNum &b = gEmptyAlphaNum, const AlphaNum &c = gEmptyAlphaNum, const AlphaNum &d = gEmptyAlphaNum); Variable-Length Arrays and alloca() link ▶We do not allow variable-length arrays or alloca(). Pros: Variable-length arrays have natural-looking syntax. Both variable-length arrays and alloca() are very efficient. Cons: Variable-length arrays and alloca are not part of Standard C++. More importantly, they allocate a data-dependent amount of stack space that can trigger difficult-to-find memory overwriting bugs: "It ran fine on my machine, but dies mysteriously in production". Decision: Use a safe allocator instead, such as scoped_ptr/scoped_array. Friends link ▶We allow use of friend classes and functions, within reason. Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of friend is to have a FooBuilder class be a friend of Foo so that it can construct the inner state of Foo correctly, without exposing this state to the world. In some cases it may be useful to make a unittest class a friend of the class it tests. Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is better than making a member public when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members. Exceptions link ▶We do not use C++ exceptions. Pros: Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes. Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with. Some third-party C++ libraries use exceptions, and turning them off internally makes it harder to integrate with those libraries. Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an Init() method, but these require heap allocation or a new "invalid" state, respectively. Exceptions are really handy in testing frameworks. Cons: When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program terminating as a result. For instance, if f() calls g() calls h(), and h throws an exception that f catches, g has to be careful or it may not clean up properly. More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don't expect. This causes maintainability and debugging difficulties. You can minimize this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand. Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it. Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure. The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document these restrictions! Decision: On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions. Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden. Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch. There is an exception to this rule (no pun intended) for Windows code. Run-Time Type Information (RTTI) link ▶We do not use Run Time Type Information (RTTI). Definition: RTTI allows a programmer to query the C++ class of an object at run time. Pros: It is useful in some unittests. For example, it is useful in tests of factory classes where the test has to verify that a newly created object has the expected dynamic type. In rare circumstances, it is useful even outside of tests. Cons: A query of type during run-time typically means a design problem. If you need to know the type of an object at runtime, that is often an indication that you should reconsider the design of your class. Decision: Do not use RTTI, except in unittests. If you find yourself in need of writing code that behaves differently based on the class of an object, consider one of the alternatives to querying the type. Virtual methods are the preferred way of executing different code paths depending on a specific subclass type. This puts the work within the object itself. If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system. If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. :-) Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags. Casting link ▶Use C++ casts like static_cast(). Do not use other cast formats like int y = (int)x; or int y = int(x);. Definition: C++ introduced a different cast system from C that distinguishes the types of cast operations. Pros: The problem with C casts is the ambiguity of the operation; sometimes you are doing a conversion (e.g., (int)3.5) and sometimes you are doing a cast (e.g., (int)"hello"); C++ casts avoid this. Additionally C++ casts are more visible when searching for them. Cons: The syntax is nasty. Decision: Do not use C-style casts. Instead, use these C++-style casts. Use static_cast as the equivalent of a C-style cast that does value conversion, or when you need to explicitly up-cast a pointer from a class to its superclass. Use const_cast to remove the const qualifier (see const). Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if you know what you are doing and you understand the aliasing issues. Do not use dynamic_cast except in test code. If you need to know type information at runtime in this way outside of a unittest, you probably have a design flaw. Streams link ▶Use streams only for logging. Definition: Streams are a replacement for printf() and scanf(). Pros: With streams, you do not need to know the type of the object you are printing. You do not have problems with format strings not matching the argument list. (Though with gcc, you do not have that problem with printf either.) Streams have automatic constructors and destructors that open and close the relevant files. Cons: Streams make it difficult to do functionality like pread(). Some formatting (particularly the common format string idiom %.*s) is difficult if not impossible to do efficiently using streams without using printf-like hacks. Streams do not support operator reordering (the %1s directive), which is helpful for internationalization. Decision: Do not use streams, except where required by a logging interface. Use printf-like routines instead. There are various pros and cons to using streams, but in this case, as in many other cases, consistency trumps the debate. Do not use streams in your code. Extended Discussion There has been debate on this issue, so this explains the reasoning in greater depth. Recall the Only One Way guiding principle: we want to make sure that whenever we do a certain type of I/O, the code looks the same in all those places. Because of this, we do not want to allow users to decide between using streams or using printf plus Read/Write/etc. Instead, we should settle on one or the other. We made an exception for logging because it is a pretty specialized application, and for historical reasons. Proponents of streams have argued that streams are the obvious choice of the two, but the issue is not actually so clear. For every advantage of streams they point out, there is an equivalent disadvantage. The biggest advantage is that you do not need to know the type of the object to be printing. This is a fair point. But, there is a downside: you can easily use the wrong type, and the compiler will not warn you. It is easy to make this kind of mistake without knowing when using streams. cout << this; // Prints the address cout << *this; // Prints the contents The compiler does not generate an error because << has been overloaded. We discourage overloading for just this reason. Some say printf formatting is ugly and hard to read, but streams are often no better. Consider the following two fragments, both with the same typo. Which is easier to discover? cerr << "Error connecting to '" hostname.first << ":" hostname.second << ": " hostname.first, foo->bar()->hostname.second, strerror(errno)); And so on and so forth for any issue you might bring up. (You could argue, "Things would be better with the right wrappers," but if it is true for one scheme, is it not also true for the other? Also, remember the goal is to make the language smaller, not add yet more machinery that someone has to learn.) Either path would yield different advantages and disadvantages, and there is not a clearly superior solution. The simplicity doctrine mandates we settle on one of them though, and the majority decision was on printf + read/write. Preincrement and Predecrement link ▶Use prefix form (++i) of the increment and decrement operators with iterators and other template objects. Definition: When a variable is incremented (++i or i++) or decremented (--i or i--) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement). Pros: When the return value is ignored, the "pre" form (++i) is never less efficient than the "post" form (i++), and is often more efficient. This is because post-increment (or decrement) requires a copy of i to be made, which is the value of the expression. If i is an iterator or other non-scalar type, copying i could be expensive. Since the two types of increment behave the same when the value is ignored, why not just always pre-increment? Cons: The tradition developed, in C, of using post-increment when the expression value is not used, especially in for loops. Some find post-increment easier to read, since the "subject" (i) precedes the "verb" (++), just like in English. Decision: For simple scalar (non-object) values there is no reason to prefer one form and we allow either. For iterators and other template types, use pre-increment. Use of const link ▶We strongly recommend that you use const whenever it makes sense to do so. Definition: Declared variables and parameters can be preceded by the keyword const to indicate the variables are not changed (e.g., const int foo). Class functions can have the const qualifier to indicate the function does not change the state of the class member variables (e.g., class Foo { int Bar(char c) const; };). Pros: Easier for people to understand how variables are being used. Allows the compiler to do better type checking, and, conceivably, generate better code. Helps people convince themselves of program correctness because they know the functions they call are limited in how they can modify your variables. Helps people know what functions are safe to use without locks in multi-threaded programs. Cons: const is viral: if you pass a const variable to a function, that function must have const in its prototype (or the variable will need a const_cast). This can be a particular problem when calling library functions. Decision: const variables, data members, methods and arguments add a level of compile-time type checking; it is better to detect errors as soon as possible. Therefore we strongly recommend that you use const whenever it makes sense to do so: If a function does not modify an argument passed by reference or by pointer, that argument should be const. Declare methods to be const whenever possible. Accessors should almost always be const. Other methods should be const if they do not modify any data members, do not call any non-const methods, and do not return a non-const pointer or non-const reference to a data member. Consider making data members const whenever they do not need to be modified after construction. However, do not go crazy with const. Something like const int * const * const x; is likely overkill, even if it accurately describes how const x is. Focus on what's really useful to know: in this case, const int** x is probably sufficient. The mutable keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first. Where to put the const Some people favor the form int const *foo to const int* foo. They argue that this is more readable because it's more consistent: it keeps the rule that const always follows the object it's describing. However, this consistency argument doesn't apply in this case, because the "don't go crazy" dictum eliminates most of the uses you'd have to be consistent with. Putting the const first is arguably more readable, since it follows English in putting the "adjective" (const) before the "noun" (int). That said, while we encourage putting const first, we do not require it. But be consistent with the code around you! Integer Types link ▶Of the built-in C++ integer types, the only one used is int. If a program needs a variable of a different size, use a precise-width integer type from , such as int16_t. Definition: C++ does not specify the sizes of its integer types. Typically people assume that short is 16 bits, int is 32 bits, long is 32 bits and long long is 64 bits. Pros: Uniformity of declaration. Cons: The sizes of integral types in C++ can vary based on compiler and architecture. Decision: defines types like int16_t, uint32_t, int64_t, etc. You should always use those in preference to short, unsigned long long and the like, when you need a guarantee on the size of an integer. Of the C integer types, only int should be used. When appropriate, you are welcome to use standard types like size_t and ptrdiff_t. We use int very often, for integers we know are not going to be too big, e.g., loop counters. Use plain old int for such things. You should assume that an int is at least 32 bits, but don't assume that it has more than 32 bits. If you need a 64-bit integer type, use int64_t or uint64_t. For integers we know can be "big", use int64_t. You should not use the unsigned integer types such as uint32_t, unless the quantity you are representing is really a bit pattern rather than a number, or unless you need defined twos-complement overflow. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this. On Unsigned Integers Some people, including some textbook authors, recommend using unsigned types to represent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider: for (unsigned int i = foo.Length()-1; i >= 0; --i) ... This code will never terminate! Sometimes gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variables. Basically, C's type-promotion scheme causes unsigned types to behave differently than one might expect. So, document that a variable is non-negative using assertions. Don't use an unsigned type. 64-bit Portability link ▶Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing, comparisons, and structure alignment. printf() specifiers for some types are not cleanly portable between 32-bit and 64-bit systems. C99 defines some portable format specifiers. Unfortunately, MSVC 7.1 does not understand some of these specifiers and the standard is missing a few, so we have to define our own ugly versions in some cases (in the style of the standard include file inttypes.h): // printf macros for size_t, in the style of inttypes.h #ifdef _LP64 #define __PRIS_PREFIX "z" #else #define __PRIS_PREFIX #endif // Use these macros after a % in a printf format string // to get correct 32/64 bit behavior, like this: // size_t size = records.size(); // printf("%"PRIuS"\n", size); #define PRIdS __PRIS_PREFIX "d" #define PRIxS __PRIS_PREFIX "x" #define PRIuS __PRIS_PREFIX "u" #define PRIXS __PRIS_PREFIX "X" #define PRIoS __PRIS_PREFIX "o" Type DO NOT use DO use Notes void * (or any pointer) %lx %p int64_t %qd, %lld %"PRId64" uint64_t %qu, %llu, %llx %"PRIu64", %"PRIx64" size_t %u %"PRIuS", %"PRIxS" C99 specifies %zu ptrdiff_t %d %"PRIdS" C99 specifies %zd Note that the PRI* macros expand to independent strings which are concatenated by the compiler. Hence if you are using a non-constant format string, you need to insert the value of the macro into the format, rather than the name. It is still possible, as usual, to include length specifiers, etc., after the % when using the PRI* macros. So, e.g. printf("x = %30"PRIuS"\n", x) would expand on 32-bit Linux to printf("x = %30" "u" "\n", x), which the compiler will treat as printf("x = %30u\n", x). Remember that sizeof(void *) != sizeof(int). Use intptr_t if you want a pointer-sized integer. You may need to be careful with structure alignments, particularly for structures being stored on disk. Any class/structure with a int64_t/uint64_t member will by default end up being 8-byte aligned on a 64-bit system. If you have such structures being shared on disk between 32-bit and 64-bit code, you will need to ensure that they are packed the same on both architectures. Most compilers offer a way to alter structure alignment. For gcc, you can use __attribute__((packed)). MSVC offers #pragma pack() and __declspec(align()). Use the LL or ULL suffixes a
NativeXml-master This file contains a list of all bugfixes, additions and enhancements to NativeXml. Maintained by Nils Haeck (SimDesign BV) ! = bugfix * = enhancement + = addition Version 4.07 (03oct2012) ! Improved canonicalization (c14n), now works recursively and returns # expanded entities ! Fixed up a rangecheck warning in sdUtf8ToWideBuffer ! cleaned up some compiler directives Version 4.06 (16aug2012) + Added TXmlNode.NodeRemoveEx (allows removal of the line with the node instead of just the node itself) - experimental Version 4.05 (11aug2012) ! Reimplemented/Fixed sdNormaliseEol function + Readded (hex) character replacement Version 4.04 (06aug2012) ! Updated simdesign.inc to add DXE2 ! Fixed bug in DirectNodeCount ! Fixed (removed) erratic un-normalisation ! removed erratic $ifdef in NativeXmlObjectStorage.pas Version 4.03 (13jul2012) * Core End-Of-Line style is LF, defaults CR-LF, LF and CR for Windows, Linux, Mac respectively ! Fixed EOL bug in source (thx Christian) * TsdChardata.GetCoreValue and .GetPlatformValue Version 4.02 (05nov2011) * default end-of-line style now esCRLF (uses CR-LF combination by default for Windows) + form storage in editor (both default and XE versions) uses NativeXml itself :) + added support for EolStyle = esCR (for use with the Mac) + added separator when writing declaration, skip separator when parsing declaration ! fixed problems in binary xml. Consequence: New binary xml version v2. * NativeXml (and binary xml) now supports xml-stylesheet correctly * binary xml now supports doctype correctly * fixed attribute processing in NativeXmlStorage.pas (thanks RKS) Version 4.01 (27jul2011) + added binary xml to the TNativeXml class itself + added methods BinaryMethod and AesKeyHex * improved FixStructuralErrors.. NativeXml can now load html usually * improved method sdUnNormalizeEol (faster now) ! fixed property handlers for ExternalEncoding and ExternalCodepage + updated DtpEditor XE Version 4.00 (23jul2011) + implemented binary xml (BXM) + added ValueAsDate and ValueAsTime besides ValueAsDateTime + added SplitSecondDigits parameter (default = 0) * constructor CreateParentNear instead of CreateParentBefore/After to avoid clash with CppBuilder + added zlib compression and AES encryption for BXM in the demo Version 3.32 (07jul2011) ! re-added D5 compatibility ! fixed TNativeXml.New method Version 3.31 (29jun2011) ! fixed string table (part of lowlevel string processing of NativeXml) * integrated End-Of-Line normalisation in the XML parser * placed NativeXmlC14N.pas in NativeXml.pas, TNativeXml.Canonicalize integrated Version 3.30 (20may2011) * reimplemented DropCommentsOnParse * reimplemented AttributesClear + added property Charset ! reworked write FExternalEncoding * readded EncodeBinHex / DecodeBinHex + sdNodeList with default Create * alphabetized NativeXml bool options + Linux: allow many codepage conversions, using NativeXmlWin32Compat.pas (largely untested tho) * added class methods TNativeXml.EncodeBase64 / DecodeBase64 next to the global base64 coding methods. ! corrected ranges of arrays in the coders, so rangechecking does not need to be disabled * slightly more verbose error messages (line + pos instead of just pos) Version 3.29 (01apr2011) ! fixed last part of the file processing (final chunk) so NormalizeEOL works correctly now ! fix: changed boolean value strings 'True' and 'False' to 'true' and 'false' according to W3 spec + Added some helper functions for Linux (still experimental), this does not affect Win32 * Joined TsdBufferParser and TsdXmlParser (now just TsdXmlParser) * Updated OnProgress and added progress bar in XmlEditor Version 3.28 (21mar2011) + Re-added NodeNewAtIndex * Verified and fixed demos Version 3.27 (19mar2011) ! fixed Delphi XE-related bug in sdEscapeString + Re-added method NodesClear + Re-added methods ValueUnicode, AttributeValueByNameWide, IndexInParent, SortChildNodes + made AttributeIndexByName public + Re-added constructors TXmlNode.CreateName, CreateNameValue Version 3.26 (16mar2011) * TCustomXml and TNativeXml joined + Added property TXmlNode.Document (type TNativeXml) + Added ReadUnicodeString / WriteUnicodeString * Made NodeFindOrCreate public ! Fixed FWriteOnDefault + Added ReadAttributeBool, ReadAttributeString, ReadUnicodeString and WriteUnicodeString Version 3.25 (03mar2011) * enhanced function sdEscapeString (contributor: Michael Cessna) ! Fixed function sdReplaceString (new implementation) + Added Test16 to verify sdEscapeString and sdReplaceString Version 3.24 (24feb2011) + Added function TCustomXml.InsertDocType to hide the complexity of inserting a TsdDocType manually ! fixed small leak in class TsdDocType + Added Test15 to diagnose TCustomXml.InsertDocType ! fixed major bug where parser does not use ansi + 65001 codepage but really utf8, so the writer also uses utf8 (and added Test14 to check) * Added speed comparison between old TNativeXml and new TNativeXml: new TNativeXml is ca 3 times faster than old. + TNativeXmlObjectStorage: Added storage of TCollectionItem and removed some "with" statements and replaced some raise statements by DoDebugOut * Tested successfully with D5, D7 and DXE Version 3.23 (13feb2011) * Reimplemented TXmlNode.IsEqualTo + Added Test12 (to check IsEqualTo) + Added D5 compatibility (through sdDebug.pas) + Option "FixStructuralErrors" is functional: With this option you can fix the structure in HTML files (eg a <meta> tag without closing tag). Version 3.22 (08feb2011) ! fixed accidental switch of TCustomXml(FOwner).DoNodeLoaded/DoNodeNew; ! fixed attribute handling of values (added sdReplaceString) + Added UTF16BE support in SaveToStream ! Renamed WriteToString/WideString to WriteToLocalString/Widestring for Utf8 and Utf16, and added generic WriteToString for "string" type + Added readonly property TXmlNode.DirectNodeCount + Added properties TXmlNode.ChildContainers[i] and TXmlNode.ChildContainerCount + Added Test5, Test6 and Test7 functions in XmlTest demo app * placed sdStringEncoding and sdBufferParser in NativeXml (no longer needs separate units) + Minor improvements in writing xml elements with XmlFormat := xfReadable Version 3.21 (04feb2011) ! Re-added sdStringToDateTime functions instead of non-functional StrToDateTime ! Fixed function sdNormaliseEOL + Re-added TXmlNode.Delete + Added Test3 and Test4 functions in XmlTest demo app Version 3.20 (31jan2011) * Combined NativeXmlEx, NativeXmlNodes, NativeXmlParser and NativeXmlUtils into one new unit NativeXml - Removed old NativeXml + Added WriteToString method for the TXmlNode classes + Added Assign and CopyFrom methods for the TXmlNode classes + Added a few methods from the old NativeXml (e.g. DeleteEmptyNodes) * sdStreams no longer needs sdStreamsPlatform * Generalized include files Version 3.14 (24jan2011) + Added LINQ-like methods and example (contributor: Marius Z) + Reimplemented ValueAsXYZ methods in NativeXmlEx * Added and enhanced XmlFormat = xfPreserve + Verified successful working in both D7 and DXE Version 3.13 (16jan2011) + NativeXmlObjectStorage now works with NativeXmlEx * Many improvements in the writer (NativeXmlNodes) ! Fixed Utf8 to Ansi (sdStringEncoding) * Dual version of XmlEditorEx demo for D7 and DXE by use of {$ifdef}'s Version 3.12 (31dec2010) + Experimental unit NativeXmlC14n.pas (for canonicalization) ! Many bugfixes in NativeXmlEx parser + normalize end-of-line * NativeXmlEx html online docu * XmlEditorEx demo with versions for Delphi7 and DelphiXE Version 3.11 (28nov2010) + Implemented NativeXmlEx: NativeXmlEx.pas (TCustomXmlEx and TNativeXmlEx components) NativeXmlNodes.pas (TXmlNode and descendant nodes like TsdAttribute and TsdElement) NativeXmlUtils.pas (lowlevel types and consts of nativexml, codepage constants, low-level string handling functions) NativeXmlParser.pas (TsdXmlParser and TsdXmlWriter components) sdStringTable.pas in /general sdStringEncoding.pas in /general sdStreams.pas in /general sdStreamsPlatform.pas in /general sdBufferParser.pas in /general sdDebug.pas in /general sdSortedLists.pas in /general ! fixed WriteAttributeInt64 and WriteInt64 (NativeXml.pas) Version 3.10 (21sep2010) ! fixed local bias in datetime processing (contributor Stefan Glienke) ! XML without encoding should be UTF-8 ! default values In ReadAttributeXXX when empty strings instead of exceptions ! Allow multiple defined properties ! fixed bug in varCurrency values when reading variants ! No info stored in stream in procedure ObjectSaveToXmlXXXX ! Problem with saving/reading collections (contributor Adam Siwon) Version 3.09 (21jul2010) ! allow "utf-8" as well as "UTF-8" as encodingstring (NativeXml.pas) ! trim string values in normal elements (NativeXml.pas hack) ! RawByteString instead of UTF8String in TsdXmlObjectWriter (NativeXmlObjectStorage) + exception 'Unregistered classtype encountered in nodename' instead of general exception (NativeXmlObjectStorage) ! Local bias (daylightsaving) and time zone designator in date/time conversion (contributor Stefan Glienke) Version 3.08 (25jun2010) ! do not write BOM when encoding="UTF-8" Version 3.07 (10Mar2010) ! fixed TXmlNode.SetValueAsInt64 Version 3.06 (03Feb2010) * Added compiler directives for NativeXmlStorage.pas ! Fixed "implicit string conversion" warnings in examples Version 3.05 (19Dec2009) * Added some compiler directives for D2009/D2010 Version 3.04 (28Nov2009) * Changed license of NativeXml to very liberal and comprehensible BSD-Style Open-Source Version 3.03 ! Added {$ELSE} directive and declarations for UnicodeChar and PUnicodeChar Version 3.02 ! Bugfix in attribute value code Version 3.00 (20Sep2009) * Made compatible with D2009 and its convention that string is unicode (2bytes/char) Version 2.39 * Replaced all widestring by WideString (conform to case used in Delphi) Version 2.38 (07March2008) + Added TXmlNode.ReadAttributeDateTime + Added TXmlNode.WriteAttributeDateTime + Support for D2007-NET (version 190) ! ReadFromStream now first clears subnodes Version 2.37 (18Dec2007) + Added ByAttribute function to TXmlNodeList ! Fixed problem with NodeAdd from another tree (Document reference gets updated now) ! Fixed deletion of empty attributes Version 2.36 (11Nov2007) ! Do not save empty encoding (e.g. encoding=""). * Renamed some local variables * Code re-formatted Version 2.35 (17Aug2007) * Bugfix in sdWriteNumber Version 2.34 (31May2007) + Added WriteAttributeInt64 ! Made check for UTF-8 case insensitive * Fixed bug with stringtable (removed "gaps") + Added AttributeValueDirect prop Version 2.31 (03May2007) * Verified compatibility with Delphi2 and 3 * Fixed 2 harmless compiler warnings Version 2.30 (30Apr2007) + Added stringbuilder class for faster creation of strings. This should make NativeXml parse documents with large value strings faster. + Patches to allow compilation under freepascal ! Fixed bug with ' and " inside quotes (now "bla'bla'bla" is allowed) * ReadAttributeBool/WriteAttributeBool allow empty elements * Made changes to assure NativeXml works well with "boolean evaluation" compile flag on ! Fixed bug in WriteWidestrProp ! Fixed bug in SetValueAsFloat ! Fixed bug in SetAttributeByNameWide Version 2.26 (05Dec2006) + Added ReadAttributeInt64 property ! Fixed bugs with StrToInt which should be StrToInt64. ! Fixed bug with tag parsing where tags like "bla>bla" caused the parser to stop on the ">". Version 2.23 (02Dec2005) ! Fixed bug in entity resolving for attributes ! Bugfix: Take into account default value in WriteAttributeString/-Integer ! Bugfix: Never write empty attributes to the XML file + Added TotalNodeCount property * Removed TNativeXml.StyleSheetString, replaced by TNativeXml.StyleSheetNode * WriteFloat now uses proprietary routine (threadsafe), always using a dot as decimal separator and settings from NativeXml.FloatSignificantDigits and FloatAllowScientific Version 2.20 (19Sep2005) + Added SortAttributes property + Added ParserWarnings property * Added RootNodeList property, to allow easier access to XML nodes in the header, and removed ExtraNodes and Comments properties. + Added TXmlNode.IsEqualTo function to compare nodes in documents ! Fixed bug in FullPath property (one slash too much at start) * FindNodes can now also be used with full paths ! Bugfix: no longer adds CRLF after ENTITY declarations ! Bugfix: AttributeName[] setter now no longer strips quotes from attribute value. + Added AttributeValueAsWidestring[] property + Added AttributeValueAsInteger[] property Version 2.13 (25Jul2005) ! Fixed bug with begin-tag reading (only seldom, with <?..?> nodes) Version 2.12 (25Jul2005) * Changed order of DoNodeLoaded and DoProgress, to avoid bug when freeing in OnNodeLoaded. + Added SortAttributes property + Added ParserWarnings property * Added RootNodeList property, to allow easier access to XML nodes in the header - Removed ExtraNodes and Comments properties * Changed Assign methods (faster now) + Added function TXmlNode.NodeByElementType + Added boolean property TNativeXml.AbortParsing ! Fixed bug with end-tag reading (when reading CDATA sections with \"]\" in the data string) Version 1.00 (01Apr2003) - Initial release
Drag and Drop Component Suite Version 4.1 Field test 5, released 16-dec-2001 ?1997-2001 Angus Johnson & Anders Melander http://www.melander.dk/delphi/dragdrop/ ------------------------------------------- Table of Contents: ------------------------------------------- 1. Supported platforms 2. Installation 3. Getting started 4. Known problems 5. Support and feedback 6. Bug reports 7. Upgrades and bug fixes 8. Missing in this release 9. New in version 4.x 10. TODO 11. Licence, Copyright and Disclaimer 12. Release history ------------------------------------------- 1. Supported platforms: ------------------------------------------- This release supports Delphi 4-6 and C++ Builder 4-5. Earlier versions of Delphi and C++ Builder will not be supported. If you need Delphi 3 or C++ Builder 3 support you will have to revert to version 3.7 of the Drag and Drop Component Suite. The library has been tested on NT4 service pack 5 and Windows 2000. Windows 95, 98, ME and XP should be supported, but has not been tested. Linux and Kylix are not supported. There are *NO* plans to port the library to Kylix. The drag and drop protocols available on Linux are too much of a mess at this time. ------------------------------------------- 2. Installation: ------------------------------------------- 1) Before you do anything else, read the "Known problems" section of this document. 2) Install the source into a directory of your choice. The files are installed into three directories: DragDrop DragDrop\Components DragDrop\Demo 3) Install and compile the appropriate design time package. The design time packages are located in the Components directory. Each version of Delphi and C++ Builder has its own package; DragDropD6.dpk for Delphi 6, DragDropD5.dpk for Delphi 5, DragDropC5.bpk for C++ Builder 5, etc. 4) Add the Drag and Drop Component Suite components directory to your library path. 5) Load the demo project group: demo\dragdrop_delphi.bpg for Delphi 5 and 6 demo\dragdrop_bcb4.bpg for C++ Builder 4 demo\dragdrop_bcb5.bpg for C++ Builder 5 The project group contains all the demo applications. 6) If your version of Delphi does not support text format DFM files (e.g. Delphi 4 doesn't), you will have to use the convert.exe utility supplied with Delphi to convert all the demo form files to binary format. A batch file, convert_forms_to delphi_4_format.bat, is supplied in the demo directory which automates the conversion process. The C++ Builder demo forms are distributed in binary format. 7) If upgrading from a previous version of the Drag and Drop Component Suite, please read the document "upgrading_to_v4.txt" before you begin working on your existing projects. Note about "Property does not exist" errors: Since all demos were developed with the latest version of Delphi, most of the demo forms probably contains references to properties that doesn't exist in earlier versions of Delphi and C++ Builder. Because of this you will get fatal run-time errors (e.g. "Error reading blahblahblah: Property does not exist.") if you attemt to run the demos without fixing this problem. Luckily it is very easy to make the forms work again; Just open the forms in the IDE, then select "Ignore All" when the IDE complains that this or that property doesn't exist and finally save the forms. ------------------------------------------- 3. Getting started: ------------------------------------------- It is recommended that you start by running each of the demo applications and then look through the demo source. Each demo application is supplied with a readme.txt file which briefly describes what the demo does and what features it uses. The demos should be run in the order in which they are listed in the supplied project group. Even if you have used previous versions of the Drag and Drop Component Suite it would be a good idea to have a quick look at the demos. The library has been completely rewritten and a lot of new features has been added. ------------------------------------------- 4. Known problems: ------------------------------------------- * The Shell Extension components does not support C++ Builder 4. For some strange reason the components causes a link error. * There appear to be sporadic problems compiling with C++ Builder 5. Several user have reported that they occasionally get one or more of the following compiler errors: [C++ Error] DragDropFile.hpp(178): E2450 Undefined structure '_FILEDESCRIPTORW' [C++ Error] DropSource.hpp(135): E2076 Overloadable operator expected I have not been able to reproduce these errors, but I believe the following work around will fix the problem: In the project options of *all* projects which uses these components, add the following conditional define: NO_WIN32_LEAN_AND_MEAN The define *must* be made in the project options. It is not sufficient to #define it in the source. If you manage to compile with C++ Builder (any version), I would very much like to know about it. * Delphi's and C++ Builder's HWND and THandle types are not compatible. For this reason it might be nescessary to cast C++ Builder's HWND values to Delphi's THandle type when a HWND is passed to a function. E.g.: if (DragDetectPlus(THandle(MyControl->Handle), Point(X, Y))) { ... } * Virtual File Stream formats can only be pasted from the clipboard with live data (i.e. FlushClipboard/OleFlushClipboard hasn't been called on the data source). This problem affects TFileContentsStreamOnDemandClipboardFormat and the VirtualFileStream demo. This is believed to be a bug in the Windows clipboard and a work around hasn't been found yet. * Asynchronous targets appears to be broken in the current release. * When TDropFileTarget.GetDataOnEnter is set to True, the component doesn't work with WinZip. Although the file names are received correctly by TDropFileTarget, WinZip doesn't extract the files and the files thus can't be copied/moved. This is caused by a quirk in WinZip; Apparently WinZip doesn't like IDataObject.GetData to be called before IDropTarget.Drop is called. ------------------------------------------- 5. Support and feedback: ------------------------------------------- Since these components are freeware they are also unsupported. You are welcome to ask for help via email, but I cannot guarantee that I will have time to help you or even reply to your mail. If you absolytely can't live without my help, you can alway try bribing me. You can also try asking for help in the Delphi newsgroups. Since the Drag and Drop Component Suite is in widespread use, there's a good chance another user can help you. I recommend the following newsgroups for issues regarding this library (or COM based Drag/Drop in general): borland.public.delphi.winapi borland.public.delphi.thirdparty-tools borland.public.delphi.oleautomation borland.public.cppbuilder.winapi borland.public.cppbuilder.thirdparty-tools Please choose the most appropiate newsgroup for your question. Do not cross post to them all. Before posting to the newsgroups, I suggest you try to search for an answer on the Google (DejaNews) search engine: http://groups.google.com Chances are that your question has been asked and answered before. If you have suggestions for improvements please mail them to me: anders@melander.dk Please include the words "Drag Drop" in the subject of any email regarding these components. ------------------------------------------- 6. Bug reports: ------------------------------------------- Bugs can either be reported at my home page (http://www.melander.dk/) or mailed directly to me: anders@melander.dk. When reporting a bug, please provide the following information: * The exact version of the Drag and Drop Component Suite you are using. * The exact version of Delphi or C++ Builder you are using. * The name and exact version of your operating system (e.g. NT4 SP5). * The exact version of the Internet Explorer installed on your system. If you can provide me with a minimal application which reproduces the problem, I can almost guarantee that I will be able to fix the problem in very short time. Please supply only the source files (pas, dfm, dpr, dof, res, etc.) and mail them as a single zip file. If I need a compiled version I will ask for it. If you feel you need to send me a screen shot, please send it in GIF or PNG format. If you mail a bug report to me, please include the words "Drag Drop" in the subject of your email. ------------------------------------------- 7. Upgrades and bug fixes: ------------------------------------------- Upgrades can be downloaded from my home page: http://www.melander.dk/delphi/dragdrop/ Bug fixes will also be posted to the above page. If you have registered for update notification via the installation program, you will receive email notification when a new release is available. You will not be notified of bug fixes. You can use the installation program to check for and download new releases and to check for known bugs. Note: If a new release is made available and you are not notified even though you registered for notification, you probably mistyped your email address during installation; About 10% of all registrations supply an invalid email address. ------------------------------------------- 8. Missing in this release: ------------------------------------------- * On-line help has not been updated and included in the kit due to late changes in the Delphi 6 help system and lack of time. If time permits, I will update the help and include it in a future release. ------------------------------------------- 9. New in version 4.x: ------------------------------------------- * Completely redesigned and rewritten. Previous versions of the Drag and Drop Component Suite used a very monolithic design and flat class hierachy which made it a bit cumbersome to extend the existing components or implement new ones. Version 4 is a complete rewrite and redesign, but still maintains compatibility with previous versions. The new V4 design basically separates the library into three layers: 1) Clipboard format I/O. 2) Data format conversion and storage. 3) COM Drag/Drop implementation and VCL component interface. The clipboard format layer is responsible for reading and writing data in different formats to and from an IDataObject interface. For each different clipboard format version 4 implements a specialized class which knows exactly how to interpret the clipboard format. For example the CF_TEXT (plain text) clipboard format is handled by the TTextClipboardFormat class and the CF_FILE (file names) clipboard format is handled by the TFileClipboardFormat class. The data format layer is primarily used to render the different clipboard formats to and from native Delphi data types. For example the TTextDataFormat class represents all text based clipboard formats (e.g. TTextClipboardFormat) as a string while the TFileDataFormat class represents a list of file names (e.g. TFileClipboardFormat) as a string list. The conversion between different data- and clipboard formats is handled by the same Assign/AssignTo mechanism as the VCLs TPersistent employes. This makes it possible to extend existing data formats with support for new clipboard formats without modification to the existing classes. The drag/drop component layer has several tasks; It implements the actual COM drag/drop functionality (i.e. it implements the IDropSource, IDropTarget and IDataObject interfaces (along with several other related interfaces)), it surfaces the data provided by the data format layer as component properties and it handles the interaction between the whole drag/drop framework and the users code. The suite provides a multitude of different components. Most are specialized for different drag/drop tasks (e.g. the TDropFileTarget and TDropFilesSource components for drag/drop of files), but some are either more generic, handling multiple unrelated formats, or simply helper components which are used to extend the existing components or build new ones. * Support for Delphi 6. Version 4.0 was primarily developed on Delphi 6 and then ported back to previous versions of Delphi and C++ Builder. * Support for Windows 2000 inter application drag images. On Windows platforms which supports it, drag images are now displayed when dragging between applications. Currently only Windows 2000 supports this feature. On platforms which doesn't support the feature, drag images are only displayed whithin the source application. * Support for Windows 2000 asynchronous data transfers. Asynchronous data tranfers allows the drop source and targets to perform slow transfers or to transfer large amounts of data without blocking the user interface while the data is being transfered. For platforms other than Windows 2000, the new TDropSourceThread class can be used to provide similar (but more limited) asynchronous data transfer capabilities. * Support for optimized and non-optimized move. When performing drag-move operations, it is now possible to specify if the target (optimized move) or the source (non-optimized move) is responsible for deleting the source files. * Support for delete-on-paste. When data is cut to the clipboard, it is now possible to defer the deletion of the source data until the target actually pastes the data. The source is notified by an event when the target pastes the data. * Extended clipboard support. All formats and components (both source and target) now support clipboard operations (copy/cut/paste) and the VCL clipboard object. * Support for shell drop handlers. The new TDropHandler component can be used to write drop handler shell extensions. A drop handler is a shell extension which is executed when a user drags and drops one or more files on a file associated wth your application. * Support for shell drag drop handlers. The new TDragDropHandler component can be used to write drag drop handler shell extensions. A drag drop handler is a shell extension which can extend the popup menu which is displayed when a user drag and drops files with the right mouse button. * Support for shell context menu handlers. The new TDropContextMenu component can be used to write context menu handler shell extensions. A context menu handler is a shell extension which can extend the popup menu which is displayed when a user right-clicks a file in the shell. * Drop sources can receive data from drop targets. It is now possible for drop targets to write data back to the drop source. This is used to support optimized-move, delete-on-paste and inter application drag images. * Automatic re-registration of targets when the target window handle is recreated. In previous versions, target controls would loose their ability to accept drops when their window handles were recreated by the VCL (e.g. when changing the border style or docking a form). This is no longer a problem. * Support for run-time definition of custom data formats. You can now add support for new clipboard formats without custom components. * Support for design-time extension of existing source and target components. Using the new TDataFormatAdapter component it is now possible to mix and match data formats and source and target components at design time. E.g. the TDropFileTarget component can be extended with URL support. * It is now possible to completely customize the target auto-scroll feature. Auto scroling can now be completely customized via the OnDragEnter, OnDragOver, OnGetDropEffect and OnScroll events and the public NoScrollZone and published AutoScroll properties. * Multiple target controls per drop target component. In previous versions you had to use one drop target component per target control. With version 4, each drop target component can handle any number of target controls. * It is now possible to specify the target control at design time. A published Target property has been added to the drop target components. * Includes 20 components: - TDropFileSource and TDropFileTarget Used for drag and drop of files. Supports recycle bin and PIDLs. - TDropTextSource and TDropTextTarget Used for drag and drop of text. - TDropBMPSource and TDropBMPTarget Used for drag and drop of bitmaps. - TDropPIDLSource and TDropPIDLTarget Used for drag and drop of PIDLs in native format. - TDropURLSource and TDropURLTarget Used for drag and drop of internet shortcuts. - TDropDummyTarget Used to provide drag/drop cursor feedback for controls which aren't registered as drop targets. - TDropComboTarget (new) Swiss-army-knife target. Accepts text, files, bitmaps, meta files, URLs and file contents. - TDropMetaFileTarget (new) Target which can accept meta files and enhanced meta files. - TDropImageTarget (new) Target which can accept bitmaps, DIBs, meta files and enhanced meta files. - TDragDropHandler (new) Used to implement Drag Drop Handler shell extensions. - TDropHandler (new) Used to implement Shell Drop Handler shell extensions. - TDragDropContext (new) Used to implement Shell Context Menu Handler shell extensions. - TDataFormatAdapter (new) Extends the standard source and target components with support for extra data formats. An alternative to TDropComboTarget. - TDropEmptySource and TDropEmptyTarget (new) Target and source components which doesn't support any formats, but can be extended with TDataFormatAdapter components. * Supports 27 standard clipboard formats: Text formats: - CF_TEXT (plain text) - CF_UNICODETEXT (Unicode text) - CF_OEMTEXT (Text in the OEM characterset) - CF_LOCALE (Locale specification) - 'Rich Text Format' (RTF text) - 'CSV' (Tabular spreadsheet text) File formats: - CF_HDROP (list of file names) - CF_FILEGROUPDESCRIPTOR, CF_FILEGROUPDESCRIPTORW and CF_FILECONTENTS (list of files and their attributes and content). - 'Shell IDList Array' (PIDLs) - 'FileName' and 'FileNameW' (single filename, used for 16 bit compatibility). - 'FileNameMap' and 'FileNameMapW' (used to rename files, usually when dragging from the recycle bin) Image formats: - CF_BITMAP (Windows bitmap) - CF_DIB (Device Independant Bitmap) - CF_METAFILEPICT (Windows MetaFile) - CF_ENHMETAFILE (Enhanced Metafile) - CF_PALETTE (Bitmap palette) Internet formats: - 'UniformResourceLocator' and 'UniformResourceLocatorW' (Internet shortcut) - 'Netscape Bookmark' (Netscape bookmark/URL) - 'Netscape Image Format' (Netscape image/URL) - '+//ISBN 1-887687-00-9::versit::PDI//vCard' (V-Card) - 'HTML Format' (HTML text) - 'Internet Message (rfc822/rfc1522)' (E-mail message in RFC822 format) Misc. formats: - CF_PREFERREDDROPEFFECT and CF_PASTESUCCEEDED (mostly used by clipboard) - CF_PERFORMEDDROPEFFECT and CF_LOGICALPERFORMEDDROPEFFECT (mostly used for optimized-move) - 'InShellDragLoop' (used by Windows shell) - 'TargetCLSID' (Mostly used when dragging to recycle-bin) * New source events: - OnGetData: Fired when the target requests data. - OnSetData: Fired when the target writes data back to the source. - OnPaste: Fired when the target pastes data which the source has placed on the clipboard. - OnAfterDrop: Fired after the drag/drop operation has completed. * New target events: - OnScroll: Fires when the target component is about to perform auto-scroll on the target control. - OnAcceptFormat: Fires when the target component needs to determine if it will accept a given data format. Only surfaced in the TDropComboTarget component. * 8 new demo applications, 19 in total. ------------------------------------------- 10. TODO (may or may not be implemented): ------------------------------------------- * Async target demo (with and without IAsyncOperation support). * Scrap file demo. * Native Outlook message format. * Structured storage support (IStorage encapsulation). ------------------------------------------- 11. Licence, Copyright and Disclaimer: ------------------------------------------- The Drag and Drop Component Suite is Copyright ?1997-2001 Angus Johnson and Anders Melander. All rights reserved. The software is copyrighted as noted above. It may be freely copied, modified, and redistributed, provided that the copyright notice(s) is preserved on all copies. The Drag and Drop Component Suite is freeware and we would like it to remain so. This means that it may not be bundled with commercial libraries or sold as shareware. You are welcome to use it in commercial and shareware applications providing you do not charge for the functionality provided by the Drag and Drop Component Suite. There is no warranty or other guarantee of fitness for this software, it is provided solely "as is". You are welcome to use the source to make your own modified components, and such modified components may be distributed by you or others if you include credits to the original components, and do not charge anything for your modified components. ------------------------------------------- 12. Version 4 release history: ------------------------------------------- 16-dec-2001 * Ported to C++ Builder 4. * Released for test as v4.1 FT5. 12-dec-2001 * Fixed C++ Builder name clash between TDropComboTarget.GetMetaFile and the GetMetaFile #define in wingdi.h 1-dec-2001 * The IAsyncOperation interface is now also declared as IAsyncOperation2 and all references to IAsyncOperation has been replaced with IAsyncOperation2. This was done to work around a bug in C++ Builder. Thanks to Jonathan Arnold for all his help with getting the components to work with C++ Builder. Without Jonathan's help version 4.1 would prabably have shipped witout C++ Builder support and certainly without any C++ Builder demos. * Demo applications for C++ Builder. The C++ Builder demos were contributed by Jonathan Arnold. 27-nov-2001 * TCustomDropTarget.Droptypes property renamed to DropTypes (notice the case). Thanks to Krystian Brazulewicz for spotting this. 24-nov-2001 * The GetURLFromString function in the DragDropInternet unit has been made public due to user request. 21-nov-2001 * Modified MakeHTML function to comply with Microsoft's description of the CF_HTML clipboard format. * Added MakeTextFromHTML function to convert CF_HTML data to plain HTML. Provides the reverse functionality of MakeHTML. * Added HTML support to TTextDataFormat class and TDropTextSource and TDropTextTarget components. * Fixed C++ Builder 5 problem with IAsyncOperation. * Released for test as v4.1 FT4. 10-nov-2001 * Added NetscapeDemo demo application. Demonstrates how to receive messages dropped from Netscape. This demo was sponsored by ThoughtShare Communications Inc. * Released for test as v4.1 FT3. 23-oct-2001 * Conversion priority of TURLDataFormat has been changed to give the File Group Descritor formats priority over the Internet Shortcut format. This resolves a problem where dropping an URL on the desktop would cause the desktop to assume that an Active Desktop item was to be created instead of an Internet Shortcut. Thanks to Allen Martin for reporting this problem. By luck this modification also happens to work around a bug in Mozilla and Netscape 6; Mozilla incorrectly supplies the UniformResourceLocator clipboard format in unicode format instead of ANSI format. Thanks to Florian Kusche for reporting this problem. * Added support for TFileGroupDescritorWClipboardFormat to TURLDataFormat. * Added declaration of FD_PROGRESSUI to DragDropFormats. * Added TURLWClipboardFormat which implements the "UniformResourceLocatorW" (a.k.a. CFSTR_INETURLW) clipboard format. Basically a Unicode version of CFSTR_SHELLURL/CFSTR_INETURL. The TURLWClipboardFormat class isn't used anywhere yet but will probably be supported by TURLDataFormat (and thus TDropURLTarget/TDropURLSource) in a later release. * Added experimental Shell Drag Image support. This relies on undodumented shell32.dll functions and probably won't be fully support before v4.2 (if ever). See InitShellDragImage in DropSource.pas. Thanks to Jim Kueneman for bringning these functions to my attention. 13-oct-2001 * TCustomDropSource.Destroy and TCustomDropMultiSource.Destroy changed to call FlushClipboard instead of EmptyClipboard. This means that clipboard contents will be preserved when the source application/component is terminated. * Added clipboard support to VirtualFileStream demo. * Modified VirtualFileStream demo to work around clipboard quirk with IStream medium. * Modified TCustomSimpleClipboardFormat to disable TYMED_ISTORAGE support by default. At present TYMED_ISTORAGE is only supported for drop targets and enabling it by default in TCustomSimpleClipboardFormat.Create caused a lot of clipboard operations (e.g. copy/paste of text) to fail. Thanks to Michael J Marshall for bringing this problem to my attention. * Modified TCustomSimpleClipboardFormat to read from the the TYMED_ISTREAM medium in small (1Mb) chunks and via a global memory buffer. This has resultet in a huge performance gain (several orders of magnitude) when transferring large amounts of data via the TYMED_ISTREAM medium. 3-oct-2001 * Fixed bug in TCustomDropSource.SetImageIndex. Thanks to Maxim Abramovich for spotting this. * Added missing default property values to TCustomDropSource. Thanks to Maxim Abramovich for spotting this. * DragDrop.pas and DragDropContext.pas updated for Delphi 4. * Reimplemented utility to convert DFM form files from Delphi 5/6 test format to Delphi 4/5 binary format. * Improved unregistration of Shell Extensions. Shell extension now completely (and safely) remove their registry entries when unregistered. * Deprecated support for C++ Builder 3. * Released for test as v4.1 FT2. 25-sep-2001 * Rewritten ContextMenuHandlerShellExt demo. The demo is now actually a quite useful utility which can be used to register and unregister ActiveX controls, COM servers and type libraries. It includes the same functionality as Borland's TRegSvr utility. 20-sep-2001 * Added support for cascading menus, ownerdraw and menu bitmaps to TDropContextMenu component. * Modified TFileContentsStreamOnDemandClipboardFormat to handle invalid parameter value (FormatEtcIn.lindex) when data is copied to clipboard. This works around an apparent bug in the Windows clipboard. Thanks to Steve Moss for reporting this problem. * Modified TEnumFormatEtc class to not enumerate empty clipboard formats. Thanks to Steve Moss for this improvement. 1-sep-2001 * Introduced TCustomDropTarget.AutoRegister property. The AutoRegister property is used to control if drop target controls should be automatically unregistered and reregistered when their window handle is recreated by the VCL. If AutoRegister is True, which is the default, then automatic reregistration will be performed. This property was introduced because the hidden child control, which is used to monitor the drop target control's window handle, can have unwanted side effects on the drop target control (e.g. TToolBar). * Deprecated support for Delphi 3. 22-jun-2001 * Redesigned TTextDataFormat to handle RTF, Unicode, CSV and OEM text without conversion. Moved TTextDataFormat class to DragDropText unit. Added support for TLocaleClipboardFormat. * Surfaced new text formats as properties in TDropTextSource and TDropTextTarget. Previous versions of the Text source and target components represented all supported text formats via the Text property. In order to enable users to handle the different text formats independantly, the text source and target components now has individual properties for ANSI, OEM, Unicode and RTF text formats. The text target component can automatically synthesize some of the formats from the others (e.g. OEM text from ANSI text), but applications which previously relied on all formats being represented by the Text property will have to be modified to handle the new properties. * Added work around for problem where TToolBar as a drop target would display the invisible target proxy window. * Fixed wide string bug in WriteFilesToZeroList. Thanks to Werner Lehmann for spotting this. 15-jun-2001 * Added work-around for Outlook Express IDataObject.QueryGetData quirk. 3-jun-2001 * Ported to C++ Builder 4 and 5. * Added missing DragDropDesign.pas unit to design time packages. * First attempt at C++ Builder 3 port.... failed. * Improved handling of oversized File Group Descriptor data. * Added support for IStorage medium to TFileContentsStreamClipboardFormat. This allows the TDropComboTarget component to accept messages dropped from Microsoft Outlook. This work was sponsored by ThoughtShare Communications Inc. 23-may-2001 * Ported to Delphi 4. * First attempt at C++ Builder 5 port.... failed. 18-may-2001 * Released as version 4.0. Note: Version 4.0 was released exclusively on the Delphi 6 Companion CD. * ContextMenuDemo and DropHandlerDemo application has been partially rewritten and renamed. ContextMenuDemo is now named ContextMenuHandlerShellExt. DropHandlerDemo is now named DropHandlerShellExt. * TDropContextMenu component has been rewitten. The TDropContextMenu now implements a context menu handler shell extension. In previous releases it implemented a drag drop handler shell extension. * The DragDropHandler.pas unit which implements the TDropHandler component has been renamed to DropHandler.pas. * Added new TDragDropHandler component. The new component, which lives in the DragDropHandler unit, is used to implement drag drop handler shell extensions. * Added DragDropHandlerShellExt demo application. * Removed misc incomplete demos from kit. * Fixed minor problem in VirtualFileStream demo which caused drops from the VirtualFile demo not to transfer content correctly. 11-may-2001 * Converted all demo forms to text DFM format. This has been nescessary to maintain compatibility between all supported versions of Delphi. * Fixed a bug in GetPIDLsFromFilenames which caused drag-link of files (dtLink with TDropFileSource) not to work. * Added readme.txt files to some demo applications. * Added missing tlb and C++ Builder files to install kit. * Released as FT4. 6-may-2001 * Added missing dfm files to install kit. * Tested with Delphi 5. Fixed Delphi 5 compatibility error in main.dfm of DragDropDemo. * Removed misc compiler warnings. * The AsyncTransferTarget and OleObjectDemo demos were incomplete and has been removed from the kit for the V4.0 release. The demos will be included in a future release. * Released as FT3. 3-may-2001 * Added missing dpr and bpg files to install kit. * Updated readme.txt with regard to lack of C++ Builder demos. * Released as FT2. 29-apr-2001 * Cleaned up for release. * Released as FT1. 23-feb-2001 * Modified TCustomDropTarget.FindTarget to handle overlapping targets (e.g. different targets at the same position but on different pages of a page control or notebook). Thanks to Roger Moe for spotting this problem. 13-feb-2001 * Renamed AsyncTransfer2 demo to AsyncTransferSource. * Added AsyncTransferTarget demo. * Replaced TChart in AsyncTransfer2 demo with homegrown pie-chart-thing. * Modified all IStream based target formats to support incremental transfer. * URW533 problem has finally been fixed. The cause of the problem, which is a bug in Delphi, was found by Stefan Hoffmeister. * Fixed free notification for TDropContextmenu and TDataFormatAdapter. 27-dec-2000 * Moved TVirtualFileStreamDataFormat and TFileContentsStreamOnDemandClipboardFormat classes from VirtualFileStream demo to DragDropFormats unit. * Added TClipboardFormat.DataFormat and TClipboardFormats.DataFormat property. * Added TDropEmptySource and TDropEmptyTarget components. These are basically do-nothing components for use with TDataFormatAdapter. * Rewritten AsyncTransfer2 demo. The demo now uses TDropEmptySource, TDataFormatAdapter and TVirtualFileStreamDataFormat to transfer 10Mb of data with progress feedback. * Rewritten VirtualFileStream demo. The demo now uses TDropEmptySource, TDropEmptyTarget, TDataFormatAdapter and TVirtualFileStreamDataFormat. * Fixed memory leak in TVirtualFileStreamDataFormat. This leak only affected the old VirtualFileStream demo. * Added support for full File Descriptor attribute set to TVirtualFileStreamDataFormat. It is now possible to specify file attributes such as file size and last modified time in addition to the filename. I plan to add similar features to the other classes which uses FileDescriptors (e.g. TDropFileSource and TDropFileTarget). 21-dec-2000 * Ported to Delphi 4. * Added workaround for design bug in either Explorer or the clipboard. Explorer and the clipboard's requirements to the cursor position of an IStream object are incompatible. Explorer requires the cursor to be at the beginning of stream and the clipboard requires the cursor to be at the end of stream. 15-dec-2000 * Fixed URW533 problem. I'll leave the description of the workaround in here for now in case the problem resurfaces. 11-dec-2000 * Fixed bug in filename to PIDL conversion (GetPIDLsFromFilenames) which affected TDropFileTarget. Thanks to Poul Halgaard J鴕gensen for reporting this. 4-dec-2000 * Added THTMLDataFormat. * Fixed a a few small bugs which affected clipboard operations. * Added {$ALIGN ON} to dragdrop.inc. Apparently COM drag/drop requires some structures to be word alligned. This change fixes problems where some of the demos would suddenly stop working. * The URW533 problem has resurfaced. See the "Known problems" section below. 13-nov-2000 * TCopyPasteDataFormat has been renamed to TFeedbackDataFormat. * Added support for the Windows 2000 "TargetCLSID" format with the TTargetCLSIDClipboardFormat class and the TCustomDropSource.TargetCLSID property. * Added support for the "Logical Performed DropEffect" format with the TLogicalPerformedDropEffectClipboardFormat class. The class is used internally by TCustomDropSource. 30-oct-2000 * Added ContextMenu demo and TDropContextMenu component. Demonstrates how to customize the context menu which is displayed when a file is dragged with the right mouse button and dropped in the shell. * Added TCustomDataFormat.GetData. With the introduction of the GetData method, Data Format classes can now be used stand-alone to extract data from an IDataObject. 20-oct-2000 * Added VirtualFileStream demo. Demonstrates how to use the "File Contents" and "File Group Descritor" clipboard formats to drag and drop virtual files (files which doesn't exist physically) and transfer the data on-demand via a stream. 14-oct-2000 * Added special drop target registration of TCustomRichEdit controls. TCustomRichEdit needs special attention because it implements its own drop target handling which prevents it to work with these components. TCustomDropTarget now disables a rich edit control's built in drag/drop handling when the control is registered as a drop target. * Added work around for Windows bug where IDropTarget.DragOver is called regardless that the drop has been rejected in IDropTarget.DragEnter. 12-oct-2000 * Fixed bug that caused docking to interfere with drop targets. Thanks to G. Bradley MacDonald for bringing the problem to my attention. 30-sep-2000 * The DataFormats property has been made public in the TCustomDropMultiTarget class. * Added VirtualFile demo. Demonstrates how to use the TFileContentsClipboardFormat and TFileGroupDescritorClipboardFormat formats to drag and drop a virtual file (a file which doesn't exist physically). 28-sep-2000 * Improved drop source detection of optimized move. When an optimized move is performed by a drop target, the drop source's Execute method will now return drDropMove. Previously drCancel was returned. The OnAfterDrop event must still be used to determine if a move operation were optimized or not. * Modified TCustomDropTarget.GetPreferredDropEffect to get data from the current IDataObject instead of from the VCL global clipboard. 18-sep-2000 * Fixed bug in DropComboTarget caused by the 17-sep-2000 TStreams modification. 17-sep-2000 * Added AsyncTransfer2 demo to demonstrate use of TDropSourceThread. * Renamed TStreams class to TStreamList. 29-aug-2000 * Added TDropSourceThread. TDropSourceThread is an alternative to Windows 2000 asynchronous data transfers but also works on other platforms than Windows 2000. TDropSourceThread is based on code contributed by E. J. Molendijk. 24-aug-2000 * Added support for Windows 2000 asynchronous data transfers. Added IAsyncOperation implementation to TCustomDropSource. Added TCustomDropSource.AllowAsyncTransfer and AsyncTransfer properties. 5-aug-2000 * Added work around for URW533 compiler bug. * Fixed D4 and D5 packages and updated a few demos. Obsolete DropMultiTarget were still referenced a few places. * Documented work around for C++ Builder 5 compiler error. See the Known Problems section later in this document for more information. 2-aug-2000 * The package files provided in the kit is now design-time only packages. In previous versions, the packages could be used both at design- and run-time. The change was nescessary because the package now contains design-time code. * Added possible work around for suspected C++ Builder bug. The bug manifests itself as a "Overloadable operator expected" compile time error. See the "Known problems" section of this document. * Rewrote CustomFormat1 demo. * Added CustomFormat2 demo. * TDataDirection members has been renamed from ddGet and ddSet to ddRead and ddWrite. * All File Group Descritor and File Contents clipboard formats has been moved from the DragDropFile unit to the DragDropFormats unit. * File Contents support has been added to TTextDataFormat. The support is currently only enabled for drop sources. * Renamed TDropMultiTarget component to TDropComboTarget. Note: This will break applications which uses the TDropMultiTarget component. You can use the following technique to port application from previous releases: 1) Install the new components. 2) Repeat step 3-8 for all units which uses the TDropMultiTarget component. 3) Make a backup of the unit (both pas and dfm file) just in case... 4) Open the unit in the IDE. 5) In the .pas file, replace all occurances of "TDropMultiTarget" with "TDropComboTarget". 6) View the form as text. 7) Replace all occurances of "TDropMultiTarget" with "TDropComboTarget". 8) Save the unit. * Renamed a lot of demo files and directories. * Added work around for yet another bug in TStreamAdapter. * Added TCustomStringClipboardFormat as new base class for TCustomTextClipboardFormat. This changes the class hierachy a bit for classes which previously descended from TCustomTextClipboardFormat: All formats which needs zero termination now descend from TCustomTextClipboardFormat and the rest descend from TCustomStringClipboardFormat. Added TrimZeroes property. Fixed zero termination bug in TCustomTextClipboardFormat and generally improved handling of zero terminated strings. Disabled zero trim in TCustomStringClipboardFormat and enabled it in TCustomTextClipboardFormat. 23-jul-2000 * Improved handling of long file names in DropHandler demo. Added work around for ParamStr bug. * Added TDataFormatAdapter component and adapter demo. TDataFormatAdapter is used to extend the existing source and target components with additional data format support without modifying them. It can be considered an dynamic alternative to the current TDropMultiTarget component. 17-jul-2000 * TDropHandler component and DropHandler demo fully functional. 14-jul-2000 * Tested with C++ Builder 5. * Fixed sporadic integer overflow bug in DragDetectPlus function. * Added shell drop handler support with TDropHandler component. This is a work in progress and is not yet functional. 1-jul-2000 * Tested with Delphi 4. * Support for Windows 2000 inter application drag images. * TRawClipboardFormat and TRawDataFormat classes for support of arbitrary unknown clipboard formats. The classes are used internally in the TCustomDropSource.SetData method to support W2K drag images.
包含英文和中文两个版本附有本书源码. Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Introduction to JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Core JavaScript 4 1.2 Client-Side JavaScript 8 Part I. Core JavaScript 2. Lexical Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 2.1 Character Set 21 2.2 Comments 23 2.3 Literals 23 2.4 Identifiers and Reserved Words 23 2.5 Optional Semicolons 25 3. Types, Values, and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 3.1 Numbers 31 3.2 Text 36 3.3 Boolean Values 40 3.4 null and undefined 41 3.5 The Global Object 42 3.6 Wrapper Objects 43 3.7 Immutable Primitive Values and Mutable Object References 44 3.8 Type Conversions 45 3.9 Variable Declaration 52 3.10 Variable Scope 53 4. Expressions and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.1 Primary Expressions 57 4.2 Object and Array Initializers 58 4.3 Function Definition Expressions 59 vii 4.4 Property Access Expressions 60 4.5 Invocation Expressions 61 4.6 Object Creation Expressions 61 4.7 Operator Overview 62 4.8 Arithmetic Expressions 66 4.9 Relational Expressions 71 4.10 Logical Expressions 75 4.11 Assignment Expressions 77 4.12 Evaluation Expressions 79 4.13 Miscellaneous Operators 82 5. Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 5.1 Expression Statements 88 5.2 Compound and Empty Statements 88 5.3 Declaration Statements 89 5.4 Conditionals 92 5.5 Loops 97 5.6 Jumps 102 5.7 Miscellaneous Statements 108 5.8 Summary of JavaScript Statements 112 6. Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 6.1 Creating Objects 116 6.2 Querying and Setting Properties 120 6.3 Deleting Properties 124 6.4 Testing Properties 125 6.5 Enumerating Properties 126 6.6 Property Getters and Setters 128 6.7 Property Attributes 131 6.8 Object Attributes 135 6.9 Serializing Objects 138 6.10 Object Methods 138 7. Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 7.1 Creating Arrays 141 7.2 Reading and Writing Array Elements 142 7.3 Sparse Arrays 144 7.4 Array Length 144 7.5 Adding and Deleting Array Elements 145 7.6 Iterating Arrays 146 7.7 Multidimensional Arrays 148 7.8 Array Methods 148 7.9 ECMAScript 5 Array Methods 153 7.10 Array Type 157 viii | Table of Contents 7.11 Array-Like Objects 158 7.12 Strings As Arrays 160 8. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 8.1 Defining Functions 164 8.2 Invoking Functions 166 8.3 Function Arguments and Parameters 171 8.4 Functions As Values 176 8.5 Functions As Namespaces 178 8.6 Closures 180 8.7 Function Properties, Methods, and Constructor 186 8.8 Functional Programming 191 9. Classes and Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 9.1 Classes and Prototypes 200 9.2 Classes and Constructors 201 9.3 Java-Style Classes in JavaScript 205 9.4 Augmenting Classes 208 9.5 Classes and Types 209 9.6 Object-Oriented Techniques in JavaScript 215 9.7 Subclasses 228 9.8 Classes in ECMAScript 5 238 9.9 Modules 246 10. Pattern Matching with Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 10.1 Defining Regular Expressions 251 10.2 String Methods for Pattern Matching 259 10.3 The RegExp Object 261 11. JavaScript Subsets and Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 11.1 JavaScript Subsets 266 11.2 Constants and Scoped Variables 269 11.3 Destructuring Assignment 271 11.4 Iteration 274 11.5 Shorthand Functions 282 11.6 Multiple Catch Clauses 283 11.7 E4X: ECMAScript for XML 283 12. Server-Side JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 12.1 Scripting Java with Rhino 289 12.2 Asynchronous I/O with Node 296 Table of Contents | ix Part II. Client-Side JavaScript 13. JavaScript in Web Browsers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 13.1 Client-Side JavaScript 307 13.2 Embedding JavaScript in HTML 311 13.3 Execution of JavaScript Programs 317 13.4 Compatibility and Interoperability 325 13.5 Accessibility 332 13.6 Security 332 13.7 Client-Side Frameworks 338 14. The Window Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 14.1 Timers 341 14.2 Browser Location and Navigation 343 14.3 Browsing History 345 14.4 Browser and Screen Information 346 14.5 Dialog Boxes 348 14.6 Error Handling 351 14.7 Document Elements As Window Properties 351 14.8 Multiple Windows and Frames 353 15. Scripting Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 15.1 Overview of the DOM 361 15.2 Selecting Document Elements 364 15.3 Document Structure and Traversal 371 15.4 Attributes 375 15.5 Element Content 378 15.6 Creating, Inserting, and Deleting Nodes 382 15.7 Example: Generating a Table of Contents 387 15.8 Document and Element Geometry and Scrolling 389 15.9 HTML Forms 396 15.10 Other Document Features 405 16. Scripting CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 16.1 Overview of CSS 414 16.2 Important CSS Properties 419 16.3 Scripting Inline Styles 431 16.4 Querying Computed Styles 435 16.5 Scripting CSS Classes 437 16.6 Scripting Stylesheets 440 17. Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 17.1 Types of Events 447 x | Table of Contents 17.2 Registering Event Handlers 456 17.3 Event Handler Invocation 460 17.4 Document Load Events 465 17.5 Mouse Events 467 17.6 Mousewheel Events 471 17.7 Drag and Drop Events 474 17.8 Text Events 481 17.9 Keyboard Events 484 18. Scripted HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 18.1 Using XMLHttpRequest 494 18.2 HTTP by <script>: JSONP 513 18.3 Comet with Server-Sent Events 515 19. The jQuery Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523 19.1 jQuery Basics 524 19.2 jQuery Getters and Setters 531 19.3 Altering Document Structure 537 19.4 Handling Events with jQuery 540 19.5 Animated Effects 551 19.6 Ajax with jQuery 558 19.7 Utility Functions 571 19.8 jQuery Selectors and Selection Methods 574 19.9 Extending jQuery with Plug-ins 582 19.10 The jQuery UI Library 585 20. Client-Side Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 20.1 localStorage and sessionStorage 589 20.2 Cookies 593 20.3 IE userData Persistence 599 20.4 Application Storage and Offline Webapps 601 21. Scripted Media and Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613 21.1 Scripting Images 613 21.2 Scripting Audio and Video 615 21.3 SVG: Scalable Vector Graphics 622 21.4 Graphics in a 630 22. HTML5 APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 22.1 Geolocation 668 22.2 History Management 671 22.3 Cross-Origin Messaging 676 22.4 Web Workers 680 Table of Contents | xi 22.5 Typed Arrays and ArrayBuffers 687 22.6 Blobs 691 22.7 The Filesystem API 700 22.8 Client-Side Databases 705 22.9 Web Sockets 712 Part III. Core JavaScript Reference Core JavaScript Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719 Part IV. Client-Side JavaScript Reference Client-Side JavaScript Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 859 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1019
``Crafting a Compiler'' by Charles N. Fisher & Richard J. LeBlanc, Jr. 1988. Benjamin/Cummings Publishing Company. Menlo Park, CA. Brief Contents xvi 1 Introduction 1 2 A Simple Compiler 31 3 Scanning—Theory and Practice 57 4 Grammars and Parsing 113 5 Top-Down Parsing 143 6 Bottom-Up Parsing 179 7 Syntax-Directed Translation 235 8 Symbol Tables and Declaration Processing 279 9 Semantic Analysis 343 10 Intermediate Representations 391 11 Code Generation for a Virtual Machine 417 12 Runtime Support 445 13 Target Code Generation 489 14 Program Optimization 547 Contents xvii 1 Introduction 1 1.1 History of Compilation 2 1.2 What Compilers Do 4 1.2.1 Machine Code Generated by Compilers 4 1.2.2 Target Code Formats 7 1.3 Interpreters 9 1.4 Syntax and Semantics 10 1.4.1 Static Semantics 11 1.4.2 Runtime Semantics 12 1.5 Organization of a Compiler 14 1.5.1 The Scanner 16 1.5.2 The Parser 16 1.5.3 The Type Checker (Semantic Analysis) 17 1.5.4 Translator (Program Synthesis) 17 1.5.5 Symbol Tables 18 1.5.6 The Optimizer 18 1.5.7 The Code Generator 19 1.5.8 Compiler Writing Tools 19 1.6 Programming Language and Compiler Design 20 1.7 Computer Architecture and Compiler Design 21 1.8 Compiler Design Considerations 22 1.8.1 Debugging (Development) Compilers 22 1.8.2 Optimizing Compilers 23 1.8.3 Retargetable Compilers 23 1.9 Integrated Development Environments 24 1.10 Exercises 26 2 A Simple Compiler 31 2.1 An Informal Definition of the ac Language 32 2.2 Formal Definition of ac 33 2.2.1 Syntax Specification 33 2.2.2 Token Specification 36 2.3 Phases of a Simple Compiler 37 2.4 Scanning 38 2.5 Parsing 39 2.5.1 Predicting a Parsing Procedure 41 2.5.2 Implementing the Production 43 2.6 Abstract Syntax Trees 45 2.7 Semantic Analysis 46 2.7.1 Symbol Tables 47 2.7.2 Type Checking 48 2.8 Code Generation 51 2.9 Exercises 54 3 Scanning—Theory and Practice 57 3.1 Overview of a Scanner 58 3.2 Regular Expressions 60 3.3 Examples 62 3.4 Finite Automata and Scanners 64 3.4.1 Deterministic Finite Automata 65 3.5 The Lex Scanner Generator 69 3.5.1 Defining Tokens in Lex 70 3.5.2 The Character Class 71 3.5.3 Using Regular Expressions to Define Tokens 73 3.5.4 Character Processing Using Lex 76 3.6 Other Scanner Generators 77 3.7 Practical Considerations of Building Scanners 79 3.7.1 Processing Identifiers and Literals 79 3.7.2 Using Compiler Directives and Listing Source Lines 83 3.7.3 Terminating the Scanner 85 3.7.4 Multicharacter Lookahead 86 3.7.5 Performance Considerations 87 3.7.6 Lexical Error Recovery 89 3.8 Regular Expressions and Finite Automata 92 3.8.1 Transforming a Regular Expression into an NFA 93 3.8.2 Creating the DFA 94 3.8.3 Optimizing Finite Automata 97 3.8.4 Translating Finite Automata into Regular Expressions 100 3.9 Summary 103 3.10 Exercises 106 4 Grammars and Parsing 113 4.1 Context-Free Grammars 114 4.1.1 Leftmost Derivations 116 4.1.2 Rightmost Derivations 116 4.1.3 Parse Trees 117 4.1.4 Other Types of Grammars 118 4.2 Properties of CFGs 120 4.2.1 Reduced Grammars 120 4.2.2 Ambiguity 121 4.2.3 Faulty Language Definition 122 4.3 Transforming Extended Grammars 122 4.4 Parsers and Recognizers 123 4.5 Grammar Analysis Algorithms 127 4.5.1 Grammar Representation 127 4.5.2 Deriving the Empty String 128 4.5.3 First Sets 130 4.5.4 Follow Sets 134 4.6 Exercises 138 5 Top-Down Parsing 143 5.1 Overview 144 5.2 LL(k) Grammars 145 5.3 Recursive-Descent LL(1) Parsers 149 5.4 Table-Driven LL(1) Parsers 150 5.5 Obtaining LL(1) Grammars 154 5.5.1 Common Prefixes 156 5.5.2 Left Recursion 157 5.6 A Non-LL(1) Language 159 5.7 Properties of LL(1) Parsers 161 5.8 Parse Table Representation 163 5.8.1 Compaction 164 5.8.2 Compression 165 5.9 Syntactic Error Recovery and Repair 168 5.9.1 Error Recovery 169 5.9.2 Error Repair 169 5.9.3 Error Detection in LL(1) Parsers 171 5.9.4 Error Recovery in LL(1) Parsers 171 5.10 Exercises 173 6 Bottom-Up Parsing 179 6.1 Overview 180 6.2 Shift-Reduce Parsers 181 6.2.1 LR Parsers and Rightmost Derivations 182 6.2.2 LR Parsing as Knitting 182 6.2.3 LR Parsing Engine 184 6.2.4 The LR Parse Table 185 6.2.5 LR(k) Parsing 187 6.3 LR(0) Table Construction 191 6.4 Conflict Diagnosis 197 6.4.1 Ambiguous Grammars 199 6.4.2 Grammars that are not LR(k) 202 6.5 Conflict Resolution and Table Construction 204 6.5.1 SLR(k) Table Construction 204 6.5.2 LALR(k) Table Construction 209 6.5.3 LALR Propagation Graph 211 6.5.4 LR(k) Table Construction 219 6.6 Exercises 224 7 Syntax-Directed Translation 235 7.1 Overview 235 7.1.1 Semantic Actions and Values 236 7.1.2 Synthesized and Inherited Attributes 237 7.2 Bottom-Up Syntax-Directed Translation 239 7.2.1 Example 239 7.2.2 Rule Cloning 243 7.2.3 Forcing Semantic Actions 244 7.2.4 Aggressive Grammar Restructuring 246 7.3 Top-Down Syntax-Directed Translation 247 7.4 Abstract Syntax Trees 250 7.4.1 Concrete and Abstract Trees 250 7.4.2 An Efficient AST Data Structure 251 7.4.3 Infrastructure for Creating ASTs 252 7.5 AST Design and Construction 254 7.5.1 Design 256 7.5.2 Construction 258 7.6 AST Structures for Left and Right Values 261 7.7 Design Patterns for ASTs 264 7.7.1 Node Class Hierarchy 264 7.7.2 Visitor Pattern 265 7.7.3 Reflective Visitor Pattern 268 7.8 Exercises 272 8 Symbol Tables and Declaration Processing 279 8.1 Constructing a Symbol Table 280 8.1.1 Static Scoping 282 8.1.2 A Symbol Table Interface 282 8.2 Block-Structured Languages and Scopes 284 8.2.1 Handling Scopes 284 8.2.2 One Symbol Table or Many? 285 8.3 Basic Implementation Techniques 286 8.3.1 Entering and Finding Names 286 8.3.2 The Name Space 289 8.3.3 An Efficient Symbol Table Implementation 290 8.4 Advanced Features 293 8.4.1 Records and Typenames 294 8.4.2 Overloading and Type Hierarchies 294 8.4.3 Implicit Declarations 296 8.4.4 Export and Import Directives 296 8.4.5 Altered Search Rules 297 8.5 Declaration Processing Fundamentals 298 8.5.1 Attributes in the Symbol Table 298 8.5.2 Type Descriptor Structures 299 8.5.3 Type Checking Using an Abstract Syntax Tree 300 8.6 Variable and Type Declarations 303 8.6.1 Simple Variable Declarations 303 8.6.2 Handling Type Names 304 8.6.3 Type Declarations 305 8.6.4 Variable Declarations Revisited 308 8.6.5 Static Array Types 311 8.6.6 Struct and Record Types 312 8.6.7 Enumeration Types 313 8.7 Class and Method Declarations 316 8.7.1 Processing Class Declarations 317 8.7.2 Processing Method Declarations 321 8.8 An Introduction to Type Checking 323 8.8.1 Simple Identifiers and Literals 327 8.8.2 Assignment Statements 328 8.8.3 Checking Expressions 328 8.8.4 Checking Complex Names 329 8.9 Summary 334 8.10 Exercises 336 9 Semantic Analysis 343 9.1 Semantic Analysis for Control Structures 343 9.1.1 Reachability and Termination Analysis 345 9.1.2 If Statements 348 9.1.3 While, Do, and Repeat Loops 350 9.1.4 For Loops 353 9.1.5 Break, Continue, Return, and Goto Statements 356 9.1.6 Switch and Case Statements 364 9.1.7 Exception Handling 369 9.2 Semantic Analysis of Calls 376 9.3 Summary 384 9.4 Exercises 385 10 Intermediate Representations 391 10.1 Overview 392 10.1.1 Examples 393 10.1.2 The Middle-End 395 10.2 Java Virtual Machine 397 10.2.1 Introduction and Design Principles 398 10.2.2 Contents of a Class File 399 10.2.3 JVM Instructions 401 10.3 Static Single Assignment Form 410 10.3.1 Renaming and φ-functions 411 10.4 Exercises 414 11 Code Generation for a Virtual Machine 417 11.1 Visitors for Code Generation 418 11.2 Class and Method Declarations 420 11.2.1 Class Declarations 422 11.2.2 Method Declarations 424 11.3 The MethodBodyVisitor 425 11.3.1 Constants 425 11.3.2 References to Local Storage 426 11.3.3 Static References 427 11.3.4 Expressions 427 11.3.5 Assignment 429 11.3.6 Method Calls 430 11.3.7 Field References 432 11.3.8 Array References 433 11.3.9 Conditional Execution 435 11.3.10 Loops 436 11.4 The LHSVisitor 437 11.4.1 Local References 437 11.4.2 Static References 438 11.4.3 Field References 439 11.4.4 Array References 439 11.5 Exercises 441 12 Runtime Support 445 12.1 Static Allocation 446 12.2 Stack Allocation 447 12.2.1 Field Access in Classes and Structs 449 12.2.2 Accessing Frames at Runtime 450 12.2.3 Handling Classes and Objects 451 12.2.4 Handling Multiple Scopes 453 12.2.5 Block-Level Allocation 455 12.2.6 More About Frames 457 12.3 Arrays 460 12.3.1 Static One-Dimensional Arrays 460 12.3.2 Multidimensional Arrays 465 12.4 Heap Management 468 12.4.1 Allocation Mechanisms 468 12.4.2 Deallocation Mechanisms 471 12.4.3 Automatic Garbage Collection 472 12.5 Region-Based Memory Management 479 12.6 Exercises 482 13 Target Code Generation 489 13.1 Translating Bytecodes 490 13.1.1 Allocating memory addresses 493 13.1.2 Allocating Arrays and Objects 493 13.1.3 Method Calls 496 13.1.4 Example of Bytecode Translation 498 13.2 Translating Expression Trees 501 13.3 Register Allocation 505 13.3.1 On-the-Fly Register Allocation 506 13.3.2 Register Allocation Using Graph Coloring 508 13.3.3 Priority-Based Register Allocation 516 13.3.4 Interprocedural Register Allocation 517 13.4 Code Scheduling 519 13.4.1 Improving Code Scheduling 523 13.4.2 Global and Dynamic Code Scheduling 524 13.5 Automatic Instruction Selection 526 13.5.1 Instruction Selection Using BURS 529 13.5.2 Instruction Selection Using Twig 531 13.5.3 Other Approaches 532 13.6 Peephole Optimization 532 13.6.1 Levels of Peephole Optimization 533 13.6.2 Automatic Generation of Peephole Optimizers 536 13.7 Exercises 538 14 Program Optimization 547 14.1 Overview 548 14.1.1 Why Optimize? 549 14.2 Control Flow Analysis 555 14.2.1 Control Flow Graphs 556 14.2.2 Program and Control Flow Structure 559 14.2.3 Direct Procedure Call Graphs 560 14.2.4 Depth-First Spanning Tree 560 14.2.5 Dominance 565 14.2.6 Simple Dominance Algorithm 567 14.2.7 Fast Dominance Algorithm 571 14.2.8 Dominance Frontiers 581 14.2.9 Intervals 585 14.3 Introduction to Data Flow Analysis 598 14.3.1 Available Expressions 598 14.3.2 Live Variables 601 14.4 Data Flow Frameworks 604 14.4.1 Data Flow Evaluation Graph 604 14.4.2 Meet Lattice 606 14.4.3 Transfer Functions 608 14.5 Evaluation 611 14.5.1 Iteration 611 14.5.2 Initialization 615 14.5.3 Termination and Rapid Frameworks 616 14.5.4 Distributive Frameworks 620 14.6 Constant Propagation 623 14.7 SSA Form 627 14.7.1 Placing φ-Functions 629 14.7.2 Renaming 631 14.8 Exercises 636 Bibliography 651 Abbreviations 661 Pseudocode Guide 663 Index 667

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧