Chapter 3 study ice 3.0-slice Language

Source: Internet
Author: User
Slice Language

First, read the slice language chapter in the ice Chinese manual. In addition to the model (module), this part is described in the ice 1.3 Chinese manual.


Figure 2.1. Ice network programming (server and client adopt the sameProgramming LanguageC ++)


Figure 2.2. Ice network programming (server and client use different programming languages)

Basic knowledge

Files with slice definitions must end with the. Ice extension. For example, clock. Ice is a valid file name. The compiler rejects other extensions.

Slice supports # ifndef, # define, # endif, and # include
Preprocessing command. They are strictly restricted in usage: You can only use the # ifndef, # define, and # endif commands to create double-include blocks. For example:

 
# Ifndef _ clock_ice
# DEFINE _ clock_ice
// # Include file here...
// Define here...
# Endif _ clock_ice

We strongly recommend that you use double-include blocks in all slice definitions to prevent multiple accesses to the same file.

# The include command can only appear at the beginning of the slice source file, that is, it must appear before all other slice definitions. In addition, # include
Command, you can only use <> syntax to specify the file name, not "". For example:

# Include <file1.ice> // OK
# Include "file2.ice" // not supported!

You cannot use these pre-processing commands for other purposes, or use other C ++ pre-processing commands (such as using \ characters to connect rows, Token pasting, macro expansion, and so on ).

In the slice definition, both C and C ++ annotation styles can be used:

The Slice keyword must be in lower case. For example, both Class and dictionary are keywords and must be spelled as shown in. This rule has two exceptions: Object
And localobject are also keywords. The first letter must be capitalized as shown in.

An identifier starts with a letter and can be followed by any number of letters or numbers. The Slice identifier is limited to ASCII characters and cannot contain non-English letters. It is different from the C ++ identifier,
The Slice identifier cannot contain underscores. This restriction seems harsh at the beginning, but it is necessary to keep the underline, The ing of various languages will get a namespace, not with the legal slice
Identifier conflict. Therefore, this namespace can be used to store native language identifiers derived from slice identifiers, without worrying that other legal slice identifiers will happen to be the same, thus causing a conflict.

Identifiers (variable names, etc.) are case-insensitive, but the spelling of the variables must be the same (if you have followed the instructions, try again ). For example, in a single scope, timeofday
The same identifier as timeofday. However, slice
It requires that you maintain case-sensitivity consistency. After you introduce an identifier, you must always spell it in uppercase and lowercase letters; otherwise, the compiler will reject it as illegal. The reason why this rule exists is to make slice
It can be mapped to languages that ignore the case sensitivity of identifiers, and can be mapped to languages that treat identifiers with different cases as different identifiers. (It can be understood that the variable name is case sensitive and cannot be the same word)

Is the keyword identifier: You can define the slice that is the keyword in one or more implementation languages.
Identifier. For example, switch is a completely legal slice identifier, but it is also a keyword of C ++ and Java. Language ing defines rules to process such identifiers. To solve this problem, a prefix is usually used to make the mapped identifier no longer a keyword. For example,
The Slice identifier switch is mapped to the _ cpp_switch of C ++ and Java
. Rules for keyword processing may produce unreadable source code. Identifiers such as native, throw, or export will
Or Java (or both) KEYWORDS conflict. To make life easier for you and others, you should avoid using slice identifiers that are keywords that implement language. Remember
In addition to C ++ and Java
Language ing. Although it is not reasonable to expect you to summarize all the keywords of all popular programming languages, you should at least try to avoid using common keywords. Such as self, import, and while
Such an identifier is definitely not a good idea.

Escape identifier: Add a backslash before the keyword. You can use the slice keyword as the identifier. For example:

 
Struct dictionary {// error!
//...
};
Struct \ dictionary {// OK
//...
};

The backslash will change the general meaning of the keyword. In the previous example, \ dictionary
Used as the identifier dictionary. The reason why the escape mechanism exists is that we will be able
To minimize the impact on existing Specifications: if an existing specification happens to use a new keyword, you only need to add a backslash before the new keyword, the specification can be modified. Note that you should avoid using slice.
Keyword identifier (even if the backslash escape permits you to do so ).

Reserved identifier: Slice retains the identifier ice and all the identifiers starting with ICE (in any case. For example, if you try to define an object named icecream
Slice compiler will issue error warning 3. The Slice identifier ending with any of the following suffixes is also retained: helper, holder, PRx, and PTR. Java
These suffixes are used for ing with C ++ to preventCode.

(Note: Ice
In the 1.3 Chinese manual, there is no "MODULE".) The module organizes a set of related statements to resolve name conflicts. The module can contain all valid slice statements and submodules. You can use uncommon words to name the outermost module, such as the company name and product name.

 
Module zeroc {

Module client {
// Definitions here...
};

Module SERVER {
// Definitions here...
};
};

Slice requires that all definitions are part of the module. For example, the following statement is invalid.

 
Interface I {// error: Only modules can exist in the global space
//...
};

Multiple files can share the same module, for example:

 
Module zeroc {
// Definitions here...
};

// In another file:
Module zeroc {// OK, reopened Module
// More definitions here...
};

Put a large module into several files to facilitate compilation (you only need to re-compile the modified file without compiling the entire module ).

The module maps the corresponding structures in the language, such as C ++, C #, and Visual Basic,
The Slice modules is mapped to namespaces; in Java, It is mapped to package.

Except for minority and specificProgramIn addition to language-related calls, most of ice APIs (application interfaces) are defined by slice. The advantage of doing so is that you can use an ice
API definition file to support all programming languages.

Note:
To ensure the code is conciseArticleThe Slice definition mentioned in does not write included modules. Assume that the statement is in a module.

Table 2.1. Slice Data Types

Type Value Range Size (unit: Bit)
Bool False or true ≥1
Byte -128-127 or 0-255 ≥8
Short 2-15 to 215-1 ≥ 16
Int 2-31 to 231-1 ≥32
Long 2-63 to 263-1 ≥ 64
Float IEEE precision ≥32 bits
Double IEEE dual-precision ≥ 64 bits
String All Unicode characters except all characters with zero bits Variable Length
User-Defined type
  • enumeration: Enum fruit {apple, pear, orange};

    This definition introduces a type named fruit, this is a new type of ownership. Slice
    does not define how to assign the order value (ordinal values) to the enumeration operator. For example, you cannot assume that in various implementation languages, the enumerated orange value is 2. Slice ensures that the sequential values of enumeration characters increase from left to right, So Apple
    is smaller than pear in all implementation languages. Unlike C ++, slice does not allow you to control the sequential values of enumerators (because many implementation languages do not support this feature ):

     Enum fruit {Apple = 0, pear = 7, Orange = 2 }; // error 

    in practice, as long as you do not transmit the sequential values of enumeration characters between address spaces, you don't need to worry about the value of the enumerator. For example, sending a value of 0 to the server indicates Apple
    may cause problems, because the server may not use 0 to indicate apple. Instead, you should send the value to Apple itself. If Apple uses another sequential value in the recipient's address space,
    ice run time translates the value as appropriate.

    like in C ++, the slice enumerator also enters the namespace around it, so the following definition is invalid:

     Enum fruit {apple, pear, orange}; 
    Enum computerbrands {apple, IBM, sun, HP }; // Apple has been defined!

    slice does not allow null enumeration.

  • Structure

    Slice supports structures that contain one or more named members. These members can be of any type, including user-defined complex types. For example:

    Struct timeofday {
    Short hour; // 0-23
    Short minute; // 0-59
    Short second; // 0-59
    };

    Like in C ++, this definition introduces
    . Structure Definition forms a namespace, so the name of a structure member only needs to be unique in the structure around them. Only data member definitions can appear within the structure. These definitions must use the type with a name. For example, you cannot define a structure within the structure:

    Struct twopoints {
    Struct point {// error!
    Short X;
    Short y;
    };
    Point coord1;
    Point coord2;
    };

    This rule applies to slice in general: the type definition cannot be nested (except that the module supports nesting ). The reason is that for some target languages, nested type definitions may be difficult to implement, and even if they can be implemented, they will greatly complicate the scope parsing rules. For slice-like
    In such a standard language, nested type definitions are not necessary-you can always write the above definitions in the following ways (this method is more neat in style ):

    Struct point {
    Short X;
    Short y;
    };
    Struct twopoints {// legal (and cleaner !)
    Point coord1;
    Point coord2;
    }
  • Sequence

    The sequence is a variable element vector:

     
    Sequence <fruit> fruitplatter;

    The sequence can be empty-that is, it can not contain elements; it can also hold any number of elements until the memory limit of your platform is reached.
    The elements contained in a sequence can also be sequences. This design allows you to create a list:

     
    Sequence <fruitplatter> fruitbanquet;

    Sequences can be used to construct many Collection types, such as vectors, lists, queues, sets, packages, or trees (whether the order is important depends on the application; if the order is ignored, A sequence acts as a set and a package ).

    A special usage of sequences has become a conventional method, that is, to represent optional values using sequences. For example, we may have a part
    Structure, used to record detailed information about the parts of a car. This structure records information such as the part name, description, weight, price, and other details. The spare parts usually have serial numbers. We use a long
    Value. But some parts, such as common screws, often do not have serial numbers. So what should we put in the serial number field of the screw? To handle this situation, you have the following options:

    • Use a tag value, such as zero, to indicate "no serial number.

      This method is feasible as long as there is a tag value available. Although it does not seem likely that some people use parts as serial numbers, this is not impossible. In addition, for other values, such as temperature values, all values in the range of their types may be valid, so no labeled value is available.

    • Change the type of the serial number from long to string.

      The string itself has a built-in tag value, that is, an empty string. Therefore, we can use an empty string to indicate the situation where "no serial number" exists. This is also feasible, but it will make most people feel unhappy: we should not convert the natural data type of a thing into a string to get a tag Value

    • Add an indicator to indicate whether the content of the serial number is valid.

      Struct part {
      String name;
      String description;
      //...
      Bool serialisvalid; // true if part has serial number
      Long serialnumber;
      };

      This is also annoying for most people, and it will eventually cause you to have trouble: Sooner or later programmers forget to check whether the serial number is valid before using it, causing catastrophic consequences.

    • Use sequences to create optional fields

      This technology uses the following conventional techniques:

      Sequence <long> serialopt;
      Struct part {
      String name;
      String description;
      //...
      Serialopt serialnumber; // Optional: zero or one element
      };

      By convention, OPT
      The suffix indicates that this sequence is used to create optional values. If the sequence is empty, the value is obviously not there; if it contains an element, this element is the value. The obvious disadvantage of this solution is that someone may put more than one element into the sequence. Add a dedicated slice for the optional values
      The component can correct this problem. But the optional value is not so common and is not worth adding a special language feature for it (we will see that you can also use the class hierarchy to create optional fields ).

  • Dictionary

    A dictionary is a ing from the key type to the value type. For example:

     
    Struct employee {
    Long number;
    String firstname;
    String lastname;
    };
    Dictionary <long, employee> employeemap;

    This definition creates a dictionary called employeemap that maps employee numbers to a structure containing employee details. You can determine the key type by yourself (in this example, it is long
    Type employee number) is a part of the value type (in this example it is part of the employee structure)-In slice, you do not need to make the key part of the value.

    A dictionary can be used to implement sparse arrays or any data structures used for searching that have non-integer keys. Although sequences of structures containing key-value pairs can be used to create the same thing, the dictionary should be more appropriate:

      • The dictionary clearly expresses the intent of the designer, that is, to provide the range from the value domain to the value) (The sequence of structures containing key-value pairs does not clearly express the same intent ).

      • At the programming language level, sequences are implemented as vectors (or lists). That is to say, sequences are not suitable for sparse fields, and elements with specific values must be located, linear search is required. The dictionary is implemented into a data structure (usually a hash table or a red/black tree) that supports efficient search. The average search time is O (Log
        N), or better. The dictionary key type does not need to be an integer. For example, we can use the following definition to translate the name of each day of a week:

        Dictionary <string, string> weekdaysenglishtogerman;

        The server can use the key-value pair to initialize the Monday-Montag and Tuesday-dienstag ing table.

      • The Value Type of a dictionary can be any type defined by the user. However, the dictionary key type can only be one of the following:

        • INTEGER (byte, short, Int, long, bool, and enumeration type)

        • String

        • Sequence of integer or string element type

        • The data member type is only an integer or string structure.

        Complex nested types, such as nested structures or dictionaries, and floating point types (float and double) cannot be used as key types. Complex nested types are not allowed because the Dictionary language ing is complicated. Floating-point types are not allowed because floating-point values change when they span machine boundaries, it may cause the problem of equality semantics.

  • Constant definition and direct quantity

    Slice allows you to define constants. The constant must be one of the following types:

      • INTEGER (bool, byte, short, Int, long, or enumeration type)

      • Float or double

      • String

    The following are some examples:

     
    Const bool appendbydefault = true;
    Const byte lowernibble = 0x0f;
    Const string advice = "Don't panic! ";
    Const short theanswer = 42;
    Const double Pi = 3.1416;
    Enum fruit {apple, pear, orange };
    Const fruit favoritefruit = pear;

    The syntax of literals is the same as that of C ++ and Java (with some minor exceptions ):

    • Boolean constants can only be initialized with the keywords "false" and "true" (you cannot use "0" or "1" to indicate "false" and "true ).

    • like C ++, you can specify the direct integer quantity in decimal, octal, or hexadecimal notation. Example:

       const byte theanswer = 42; 
      const byte theanswerinoctal = 052;
      const byte theanswerinhex = 0x2a; // or 0x2a
      note
      If you interpret a byte as a number rather than a bit, you may get different results in different languages. For example, in C ++,
      byte ing to Char depends on the target platform. Char may be signed or unsigned.
      note
      used to indicate the suffixes of long constants and unsigned constants (l, l, U, and u used by C ++) illegal:

       const long wrong = 0u; // syntax error 
      const long wrongtoo = 000000l; // syntax error
      • The value of the integer value must fall within the range of its constant type. Otherwise, the compiler will send a diagnosis message.

      • The direct floating point usage uses the C ++ syntax, except that you cannot use the L or l suffix to represent Extended Floating Point constants. However, F and F are legal (but will be ignored ). The following are some examples:

        Const float p1 =-3.14f; // integer & fraction, with suffix
        Const float P2 = + 3.1e-3; // integer, fraction, and Exponent
        Const float P3 =. 1; // fraction part only
        Const float P4 = 1.; // integer part only
        Const float P5 =. 9e5; // fraction part and Exponent
        Const float P6 = 5e2; // integer part and Exponent
      • The floating point must fall within the range of its constant type (float or double); otherwise, the compiler will issue a diagnostic warning.

      • The number of strings can be the same as the escape sequence of C ++. The following are some examples:

         const string anordinarystring = "Hello world! "; 
        const string doublequote =" \ "";
        const string twosinglequotes = "'\'"; // 'and \' are OK
        const string newline = "\ n";
        const string carriagereturn = "\ r ";
        const string horizontaltab = "\ t";
        const string verticaltab = "\ v";
        const string formfeed = "\ f ";
        const string Alert = "\ A";
        const string backspace = "\ B";
        const string questionmark = "\? ";
        const string backslash =" \ ";
        70 slice language
        const string octalescape =" \ 007 "; // same as \ A
        const string hexescape = "\ x07"; // ditto
        const string universalcharname = "\ u03a9 "; // Greek Omega
        similar to C ++, the number of adjacent strings is directly connected:
        const string msg1 = "Hello world! ";
        const string msg2 =" hello "world! "; // Same message
        /*
        * escape sequences are processed before concatenation,
        * so the string below contains two characters,
        * '\ XA' and 'c '.
        */
        const string S = "\ xa" "C";
        Note:
        Slice does not have the concept of a Null String

        Const string nullstring = 0; // illegal!

        The Null String does not exist in slice. Therefore, it cannot be used as a legal string value anywhere on the ice platform. The reason for this decision is that Null
        Strings do not exist in many programming languages.

Interfaces, operations, and exceptions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.