Участник:Колесников П.А./Черновик

Материал из Seo Wiki - Поисковая Оптимизация и Программирование

Перейти к: навигация, поиск
Это личная страница участника русской Bикипeдии.

Это не энциклопедическая статья.

Если вы видите эту страницу не на сайте русской Bикипeдии (http://ru.wikipеdia.org), то вы просматриваете зеркало сайта. Это означает, что эта страница могла устареть, и человек, которому принадлежит эта страница, может не иметь какого-либо отношения к другим проектам, кроме Bикипeдии.

Оригинал страницы находится по адресу http://ru.wikipеdia.org/wikі/User:Колесников П.А..

Eiffel
Класс языка:

объектно-ориентированный

Появился в:

1986 г.

Автор(ы):

Bertrand Meyer

Последняя версия:

4.2 (Feb 6, 1998)

Типизация данных:

строгая, статическая

Основные реализации:

en:EiffelStudio, en:SmartEiffel, en:Visual Eiffel , Gobo Eiffel, "The Eiffel Compiler" tecomp

Испытал влияние:

Ada, Simula, Z

Повлиял на:

C#, D, Java, Lisaac, Ruby, Sather

Эйфель — это стандартизованный ISO объектно-ориентированный язык программирования, созданный с целью эффективной разработки расширяемого, многократно используемого, надежного программного обеспечения. Эйфель используется в учебных заведениях как язык изучения обектно-ориентированных принципов программирования. Эйфель используется в финансовой, аэрокосмической сфере, здравоохранении, видео играх и других отраслях, как платформа разработки. С 1985 года многие поставщики ПО разработали свои среды программирования на Эйфеле.

Язык Эйфель тесно связан с методикой программирования Эйфель. Оба основаны на следующем наборе принципов:

Многие концепции, изначально появившиеся в Эйфеле, нашли свое отражение в таких языках как Java, C# и других. Новые идей языкового дизайна продолжают вводится в язык через процесс стандартизации в ECMA/ISO.


Содержание

Характеристики

Ключевыми характерисстиками языка Эйфель являются:

  • объектно-ориентированная структура программмы, в которой класс является единицей декомпозиции;
  • контрактное программирование тесно переплетено с другими конструкциями языка;
  • автоматическое управление памятью, обычно реализуемое cборщиком мусора;
  • наследование, включая множественное, переименование, переопредленение, «выбор», «некорректное наследование» (англ. non-conforming inheritance) и другие механизмы для реализации «безопасного» наследования;
  • ограниченное и неограниченное обобщенное программирование;
  • унифицированная система типов, базирующаяся на классах и использующая как знаковую, так и ссылочную семантику для всех типов, включая базовые типы (например, INTEGER);
  • безопасная статическая типизация;
  • полная безопасность (англ. void safety) или статическая защита (англ. static protection) от вызовов по пустым ссылкам (англ. null references), реализванную с помощью механизма «привязанных типов» (англ. attached-types mechanism);
  • агенты или объекты, инкапсулирующие вычисления; близки по смыслу к замыканиям (англ. closures) и лямбда-исчислению;
  • едничные методы (англ. once routines); или методы, выполняемые только один раз и применяющиеся для реализации объектов общего пользования (так называемый шаблон Одиночка) и децентрализованной инициализации;
  • Алгол-/Паскаль- подобный синтаксис, без обязательной разделительной точки с запятой. Для методов возможна операторная форма записи;
  • Язык не чувствителен к регистру.

Особенности дизайна

В языке Эйфель предпочтение отадется декларативным утверждениям нежели процедурному коду. Дизайн языка нацелен на исключение необходимости отдельного документирования кода.

Язык избегает использования трюков и техник программирования используемых для оптимизации программы под компилятор. Цель состоит не только в стремлении сделать код программы более читаемым, но и позволить программистам сконцентрироваться на действительно важных аспектах разрабатываемой программы и не увязать в деталях реализации. Простота языка Эйфель предназначена для создания простых, расширяемых, многократно используемых и надежных вычислительных решений. Компиляторы программ, написанных на Эйфеле, предоставляют обширную оптимизацию, такую как автоматичекое встраивание функций[1].

История развития

Язык Эйфель был разработан копанией Eiffel Software основанной Бертраном Мэйером (Bertrand Meyer), называвшейся тогда «Interactive Software Engineering Inc.» (ISE). Книга Мэйера «Object-Oriented Software Construction» содержит детальное описание концепций и теории объектной технологии, положенной в основу разработки языка Эйфель.[2]

Цель разработки самого языка Эйфель, библиотек и методов программирования состоит в предоставлении программистам эффективных иснтрументов создания надежных, повторно иcпользуемых программных модулей. Эйфель поддерживает множественное наследование, обобщенное программирование, полиморфизм, инкапсуляцию, безопасное приведение типов и en:parameter covariance. Наиболее значимым вкладом языка Эйфель в технологию разработки программного обеспечения является контрактное программирование.

Дизайн языка основан на теории обектно-ориентированного программирования с незначительными влияниями других парадигм и обратной совместимости со старым кодом. Формально Эйфель поддерживает абстрактные типы данных. По задумке, текст програмы должен быть способен воспроизвести свою документацию-дизайн из кода, используя формальную реализацию «Абстрактных типов данных».

Реализации и среды разработки

EiffelStudio -- cреда разработки программного обеспечения, доступная как под свободной (open source) или коммерческой лицензиями.

Several other programming languages incorporate elements first introduced in Eiffel. Sather, for example, was originally based on Eiffel but has since diverged, and now includes several functional programming features. The interactive-teaching language Blue, forerunner of BlueJ, is also Eiffel-based. The Apple Media Tool includes an Eiffel-based Apple Media Language.


Спецификация и стандарты

The Eiffel language definition is an international standard of the ISO. The standard was developed by ECMA International, which first approved the standard on 21 June 2005 as ECMA standard 367, Eiffel: Analysis, Design and Implementation Language. In June 2006, ECMA and ISO adopted the second version. In November 2006, ISO first published that version. The standard can be found and used free of charge on the ECMA site.[3] The ISO version[4] is identical in all respects except formatting.

Eiffel Software, «The Eiffel Compiler» tecomp and Eiffel-library-developer Gobo have committed to implementing the standard; Eiffel Software’s EiffelStudio 6.1 implements some of the major new mechanisms—in particular, inline agents, assigner commands, bracket notation, non-conforming inheritance, and attached types. The SmartEiffel team has turned away from this standard to create its own version of the language, which they believe to be closer to the original style of Eiffel. Object Tools has not disclosed whether future versions of its Eiffel compiler will comply with the standard.

The standard cites the following, predecessor Eiffel-language specifications:

  • Bertrand Meyer: Eiffel: The Language, Prentice Hall, second printing, 1992 (first printing: 1991)
  • Bertrand Meyer: Standard Eiffel (revision of preceding entry), ongoing, 1997-present, at Bertrand Meyer’s ETL3 page, and
  • Bertrand Meyer: Object-Oriented Software Construction, Prentice Hall: first edition, 1988; second edition, 1997.


Синтакс и семантика

An Eiffel "system" or "program" is a collection of classes. Above the level of classes, Eiffel defines cluster, which are essentially a group of classes, and possibly of subclusters (nested clusters). Clusters are not a syntactic language construct, but rather a standard organizational convention. Typically an Eiffel application will be organized with each class in a separate file, and each cluster in a directory containing class files. In this organization, subclusters are subdirectories. For example, under standard organizational and casing conventions, x.e might be the name of a file that defines a class called X.

A class contains features, which are similar to "members", "attributes" or "methods" in other object-oriented programming languages. A class also defines its invariants, and contains other properties, such as a "notes" section for documentation and metadata. Eiffel's standard data types, such as INTEGER, STRING and ARRAY, are all themselves classes.

Every system must have a class designated as "root", with one of its creation procedures designated as "root procedure". Executing a system consists of creating an instance of the root class and executing its root procedure. Generally, doing so creates new objects, calls new features, and so on.

Eiffel has five basic executable instructions: assignment, object creation, routine call, condition, and iteration. Eiffel's control structures are strict in enforcing structured programming: every block has exactly one entry and exactly one exit.

Область видимости

Unlike many object-oriented languages, but like Smalltalk, Eiffel does not permit any assignment into fields of objects, except within the features of an object. Eiffel emphasizes information hiding and data abstraction, by requiring formal interfaces to data mutation. To put it in the language of other object-oriented programming languages, all Eiffel fields are "private", and "setters" are needed to modify values. An upshot of this is that "setters" can, and normally do, implement the invariants Eiffel provides syntax for.

"Hello, world!"

A programming language's look and feel is often conveyed using a "Hello, world!" program. Such a program written in Eiffel might be:

class
    HELLO_WORLD
create
    make
feature
    make
        do
            print ("Hello, world!%N")
        end
end


Контрактное программирование

The concept of design by contract is central to Eiffel. The mechanisms are tightly integrated with the language. Contracts guide redefinition of features in inheritance.

  • Routine precondition: The precondition may only be weakened by inheritance; any call that meets the requirements of the ancestor meets those of the descendant.
  • Routine postcondition: The postcondition can only be strengthened by inheritance; any result guaranteed by the ancestor is still provided by the descendant.
  • Class invariant

In addition, the language supports a "check instruction" (a kind of "assert") and loop invariants.

Свойства, комманды и запросы

The primary characteristic of a class is that it contains a set of features. As a class represents a set of run-time objects, or "instances", a feature is an operation on these objects. There are two kinds of features: queries and commands. A query provides information about an instance. A command modifies an instance.

The command-query distinction is important to the Eiffel method. In particular:

  • Uniform-Access Principle: from the point of view of a software client making a call to a class feature, whether a query is an attribute (field in each object) or a function (algorithm) should not make any difference. For example a_vehicle.speed could be an attribute, accessed from the object's representation; or it could be computed by a function that divides distance by time. The notation is the same in both cases, so that it's easy to change representation without affecting the rest of the software.
  • Command-Query Separation Principle: Queries must not modify the instance. This is not a language rule but a methodological principle. So in good Eiffel style, one does not find "get" functions that change something and return a result; instead there are commands (procedures) to change objects, and queries to obtain information about the object, resulting from preceding changes.

Перегрузка методов

Eiffel does not allow argument overloading. Each feature name within a class always maps to a specific feature within the class. One name, within one class, means one thing.

This design choice helps the readability of classes, by avoiding a cause of ambiguity about which routine will be invoked by a call. It also simplifies the language mechanism; in particular, this is what makes Eiffel's multiple inheritance mechanism possible.[5]

Names can, of course, be reused in different classes. For example the "+" operator is defined in several classes: INTEGER, REAL, STRING, etc.

Обобщённое программирование

Classes can be generic, to express that they are parameterized by types. Generic parameters appear in square brackets:

class LIST [G] ...

G is known as a "formal generic parameter". (Eiffel reserves "argument" for routines, and uses "parameter" only for generic classes.) With such a declaration G represents within the class an arbitrary type; so a function can return a value of type G, and a routine can take an argument of that type:

item: G do ... end
put (x: G) do ... end

The LIST [INTEGER] and LIST [WORD] are "generic derivations" of this class. Permitted combinations (with n: INTEGER, w: WORD, il: LIST [INTEGER], wl: LIST [WORD]) are

n := il.item
wl.put (w)

INTEGER resp. WORD are the "actual generic parameters" in these generic derivations.

It is also possible to have 'constrained' formal parameters, for which the actual parameter must inherit from a given class, the "constraint". For example in

   class HASH_TABLE [G, KEY -> HASHABLE]

a derivation HASH_TABLE [INTEGER, STRING] is valid only if STRING inherits from HASHABLE (as it indeed does in typical Eiffel libraries). Within the class, having KEY constrained by HASHABLE means that for x: KEY it is possible to apply to x all the features of HASHABLE, as in x.hash_code.

Наследование

To inherit from one or more others, a class will include an inherit clause at the beginning:

class C inherit
   A
   B
 
-- ... Rest of class declaration ...

The class may redefine (override) some or all of the inherited features. This must be explicitly announced at the beginning of the class through a redefine subclause of the inheritance clause, as in

class C inherit
    A
        redefine f, g, h end
    B
        redefine u, v end

Отложенные классы и свойства

Classes may be defined with deferred class rather than with class to indicate that the class may not be directly instantiated. Non-instantiatable classes are called abstract classes in some other object-oriented programming languages. In Eiffel parlance, only an "effective" class can be instantiated (it may be a descendent of a deferred class). A feature can also be deferred by using the deferred keyword in place of a do clause. If a class has any deferred features it must be declared as deferred; however, a class with no deferred features may nonetheless itself be deferred.

Deferred classes play some of the same role as interfaces in languages such as Java, though many object-oriented programming theorists believe interfaces are themselves largely an answer to Java's lack of multiple inheritance (which Eiffel has).

Переименование

A class that inherits from one or more others gets all its features, by default under their original names. It may, however, change their names through rename clauses. This is required in the case of multiple inheritance if there are name clashes between inherited features; without renaming, the resulting class would violate the no-overloading principle noted above and hence would be invalid.

Кортежи

Tuples types may be viewed as a simple form of class, providing only attributes and the corresponding "setter" procedure. A typical tuple type reads

   TUPLE [name: STRING; weight: REAL; date: DATE]

and could be used to describe a simple notion of birth record if a class is not needed. An instance of such a tuple is simply a sequence of values with the given types, given in brackets, such as

   ["Brigitte", 3.5, Last_night]

Components of such a tuple can be accessed as if the tuple tags were attributes of a class, for example if t has been assigned the above tuple then t.weight has value 3.5.

Thanks to the notion of assigner command (see below), dot notation can also be used to assign components of such a tuple, as in

   t.weight := t.weight + 0.5

The tuple tags are optional, so that it is also possible to write a tuple type as TUPLE [STRING, REAL, DATE]. (In some compilers this is the only form of tuple, as tags were introduced with the ECMA standard.)

The precise specification of e.g. TUPLE [A, B, C] is that it describes sequences of at least three elements, the first three being of types A, B, C respectively. As a result TUPLE [A, B, C] conforms to (may be assigned to) TUPLE [A, B], to TUPLE [A] and to TUPLE (without parameters), the topmost tuple type to which all tuple types conform.

Агенты

Eiffel's "agent" mechanism wraps operations into objects. This mechanism can be used for iteration, event-driven programming, and other contexts in which it is useful to pass operations around the program structure. Other programming languages, especially ones that emphasize functional programming, allow a similar pattern using continuations, closures, or generators; Eiffel's agents emphasize the language's object-oriented paradigm, and use a syntax and semantics similar to code blocks in Smalltalk and Ruby.

For example, to execute the my_action block for each element of my_list, one would write:

   my_list.do_all (agent my_action)

To execute my_action only on elements satisfying my_condition, a limitation/filter can be added:

   my_list.do_if (agent my_action, agent my_condition)

In these examples, my_action and my_condition are routines. Prefixing them with agent yields an object that represents the corresponding routine with all its properties, in particular the ability to be called with the appropriate arguments. So if a represents that object (for example because a is the argument to do_all), the instruction

   a.call ([x])

will call the original routine with the argument x, as if we had directly called the original routine: my_action (x). Arguments to call are passed as a tuple, here [x].

It is possible to keep some arguments to an agent open and make others closed. The open arguments are passed as arguments to call: they are provided at the time of agent use. The closed arguments are provided at the time of agent definition. For example, if action2 has two arguments, the iteration

   my_list.do_all (agent action2 (?, y))

iterates action2 (x, y) for successive values of x, where the second arguments remained set to y. The question mark ? indicates an open argument; y is a closed argument of the agent. Note that the basic syntax agent f is a short hand for agent f (?, ?, ...) with all arguments open. It is also possible to make the target of an agent open through the notation {T}? where T is the type of the target.

The distinction between open and closed operands (operands = arguments + target) corresponds to the distinction between bound and free variables in lambda calculus. An agent expression such as action2 (?, y) with some operands closed and some open corresponds to a version of the original operation curried on the closed operands.

The agent mechanism has been recently generalized to allow defining an agent without reference to an existing routine (such as my_action, my_condition, action2), through inline agents as in

my_list.do_all (agent (s: STRING)
     require
         not_void: s /= Void
     do
         s.append_character (',')
     ensure
         appended: s.count = old s.count + 1
     end)

The inline agent passed here can have all the trappings of a normal routine, including precondition, postcondition, rescue clause (not used here), and a full signature. This avoids defining routines when all that's needed is a computation to be wrapped in an agent. This is useful in particular for contracts, as in an invariant clause that expresses that all elements of a list are positive:

   my_list.for_all (agent (x: INTEGER): BOOLEAN do Result := (x > 0) end)

The current agent mechanism leaves a possibility of run-time type error (if a routine with n arguments is passed to an agent expecting m arguments with m < n). This can be avoided by a run-time check through the precondition valid_arguments of call. Several proposals for a purely static correction of this problem are available, including a language change proposal by Ribet et al.[6].

Подпрограммы, выполянемые единожды

A routine's result can be cached using the once keyword in place of do. Non-first calls to a routine require no additional computation or resource allocation, but simply return a previously computed result. A common pattern for "once functions" is to provide shared objects; the first call will create the object, subsequent ones will return the reference to that object. The typical scheme is:

shared_object: SOME_TYPE
    once
        create Result.make (args)
             -- This creates the object and returns a reference to it through `Result'.
    end

The returned object—Result in the example—can itself be mutable, but its reference remains the same.

Often "once routines" perform a required initialization: multiple calls to a libraries can include a call to the initialization procedure, but only the first such call will perform the required actions. Using this pattern initialization can be decentralized, avoiding the need for a special initialization module. "Once routines" are similar in purpose and effect to the singleton pattern in many programming languages, and to the Borg pattern used in Python.

The ECMA specification allows variants of "once" (qualified by a keyword in parentheses, e.g. once (THREAD): once per process, once per thread, once per object. However, this is not yet fully implemented by current compilers (typically, only PROCESS and THREAD).

Приведение типов

Eiffel provides a mechanism to allow conversions between various types. The mechanisms coexists with inheritance and complements it. To avoid any confusion between the two mechanisms, the design enforces the following principle:

(Conversion principle) A type may not both conform and convert to another.

For example NEWSPAPER may conform to PUBLICATION, but INTEGER converts to REAL (and does not inherit from it).

The conversion mechanism simply generalizes the ad hoc conversion rules (such as indeed between INTEGER and REAL) that exist in most programming languages, making them applicable to any type as long as the above principle is observed. For example a DATE class may be declared to convert to STRING; this makes it possible to create a string from a date simply through

   my_string := my_date

as a shortcut for using an explicit object creation with a conversion procedure:

   create my_string.make_from_date (my_date)

To make the first form possible as a synonym for the second, it suffices to list the creation procedure (constructor) make_from_date in a convert clause at the beginning of the class.

As another example, if there is such a conversion procedure listed from TUPLE [day: INTEGER; month: STRING; year: INTEGER], then one can directly assign a tuple to a date, causing the appropriate conversion, as in

      Bastille_day := [14, "July", 1789]

Обработка исключений

Exception handling in Eiffel is based on the principles of design by contract. For example, an exception occurs when a routine's caller fails to satisfy a precondition, or when a routine cannot ensure a promised postcondition. In Eiffel, exception handling is not used for control flow or to correct data-input mistakes.

An Eiffel exception handler is defined using the rescue keyword. Within the rescue section, the retry keyword executes the routine again. For example, the following routine tracks the number of attempts at executing the routine, and only retries a certain number of times:

connect_to_server (server: SOCKET)
      -- Connect to a server or give up after 10 attempts.
    require
        server /= Void and then server.address /= Void
    local
        attempts: INTEGER
    do
        server.connect
    ensure
      connected: server.is_connected
    rescue
        if attempts < 10 then
            attempts := attempts + 1
            retry
        end
    end

This example is arguably flawed for anything but the simplest programs, however, because connection failure is to be expected. For most programs a routine name like attempt_connecting_to_server would be better, and the postcondition would not promise a connection, leaving it up to the caller to take appropriate steps if the connection was not opened.

Параллельные вычисления

A number of networking and threading libraries are available, such as EiffelNet and EiffelThreads. A concurrency model for Eiffel, based on the concepts of design by contract, is SCOOP (software), or Simple Concurrent Object-Oriented Programming, not yet part of the official language definition but available as an add-on from ETH Zurich.

Операторный и блочный синтаксис, команда присваивания

Eiffel's view of computation is completely object-oriented in the sense that every operation is relative to an object, the "target". So for example an addition

  [1] a + b

is conceptually understood as if it were a function call

  [2] a.plus (b)

with target a, feature plus and argument b.

Of course [1] is the conventional syntax and usually preferred. Operator syntax makes it possible to use either form by declaring the feature (for example in INTEGER, but this applies to other basic classes and can be used in any other for which such an operator appropriate):

plus alias "+" (other: INTEGER): INTEGER
        -- ... Normal function declaration...
    end

The range of operators that can be used as "alias" is quite broad; they include predefined operators such as "+" but also "free operators" made of non-alphanumeric symbols. This makes it possible to design special infix and prefix notations, for example in mathematics and physics applications.

Every class may in addition have one function aliased to "[]", the "bracket" operator, allowing the notation a [i, ...] as a synonym for a.f (i, ...) where f is the chosen function. This is particularly useful for container structures such as arrays, hash tables, lists etc. For example access to an element of a hash table with string keys can be written

   number := phone_book ["JILL SMITH"]

"Assigner commands" are a companion mechanism designed in the same spirit of allowing well-established, convenient notation reinterpreted in the framework of object-oriented programming. Assigner commands allow assignment-like syntax to call "setter" procedures. An assignment proper can never be of the form a.x := v as this violates information hiding; you have to go for a setter command (procedure). For example the hash table class can have the function and the procedure

item alias "[]" (key: STRING): ELEMENT         [3]
      -- The element of key `key'.
      -- ("Getter" query)
    do
        ...
    end
 
put (e: ELEMENT; key: STRING)
      -- Insert the element `e', associating it with the key `key'.
      -- ("Setter" command)
    do
        ...
    end

Then to insert an element you have to use an explicit call to the setter command:

   [4] phone_book.put (New_person, "JILL SMITH")

It is possible to write this equivalently as

   [5] phone_book ["JILL SMITH"] := New_person

(in the same way that phone_book ["JILL SMITH"] is a synonym for number := phone_book.item ("JILL SMITH")), provided the declaration of item now starts (replacement for [3]) with

   item alias "[]" (key: STRING): ELEMENT assign put

This declares put as the assigner command associated with item and, combined with the bracket alias, makes [5] legal and equivalent to [4]. (It could also be written, without taking advantage of the bracket, as phone_book.item ("JILL SMITH") := New_person.

note: The argument list of a's assigner is constrained to be: (a's return type;all of a's argument list...)

Лексические и синатксические своства

Eiffel is not case-sensitive. The tokens make, maKe and MAKE all denote the same identifier. See, however, the "style rules" below.

Comments are introduced by -- (two consecutive dashes) and extend to the end of the line.

The semicolon, as instruction separator, is optional. Most of the time the semicolon is just omitted, except to separate multiple instructions on a line. This results in less clutter on the program page.

There is no nesting of feature and class declarations. As a result the structure of an Eiffel class is simple: some class-level clauses (inheritance, invariant) and a succession of feature declarations, all at the same level.

It is customary to group features into separate "feature clauses" for more readability, with a standard set of basic feature tags appearing in a standard order, for example:

class HASH_TABLE [ELEMENT, KEY -> HASHABLE] inherit TABLE [ELEMENT]
 
    feature -- Initialization
         -- ... Declarations of initialization commands (creation procedures/constructors) ...
 
    feature -- Access
         -- ... Declarations of non-boolean queries on the object state, e.g. item ...
 
    feature -- Status report
         -- ... Declarations of boolean queries on the object state, e.g. is_empty ...
 
    feature -- Element change
         -- ... Declarations of commands that change the structure, e.g. put ...
 
    -- etc.
end

In contrast to most curly bracket programming languages, Eiffel makes a clear distinction between expressions and instructions. This is in line with the Command-Query Separation principle of the Eiffel method.

Соглашения о форматировании кода

Бо́льшая часть документации Эйфеля использует строгие правила форматирования кода, разработанные для приведения её к единообразному виду. Некоторые из соглашений применяются к самому формату кодирования, другие — к типографскому отображению кода Эйфеля в публикациях, где такие соглашения применимы/возможны.

Хотя язык и не чувствителен к регистру, стилевые стандарты предписывают имена классов записывать заглавными буквами (LIST), свойства и методы — строчными (make), константы начинать с заглавной буквы (Avogadro). Рекомендованый стиль также предлагает использование знака подчеркивания для разделения компонентов составных идентификаторов, например average_temperature.

Спецификация языка включает правила для отображения текстов программ: зарезервированные слова оформляются жирным, идентификаторы и константы пользователя — наклонным, комментарии, операторы и пунктуация — используют не-моноширинный шрифт, текст программы окрашивается в синий цвет, для отделения его от текста пояснений. Например, программа «Hello, world!», показанная выше, в документации к Эйфелю выглядела бы примерно так:

class 
    HELLO_WORLD
create
    make
feature
   make
      do
         print ("Hello, world!")
      end
end


Взаимодействие с другими языками и инструментариями

Язык Эйфель — строгий объектно-ориентированный язык, который предоставляет открытую архитектуру для взаимодействия с «внешним» программным обеспечением, написанным на любом другом языке программирования.

Например, возможно написание программы на уровне аппаратного обеспечения или операционной системы с помощью кода на Си. Эйфель предоставляет простой интерфейс для взаимодействия с процедурам Си, включая вставку Си кода в тело методов Эйфеля. Обычно, это короткие низкоуровневые вставки.

Хотя не существует прямой связи между Эйфелем и Си, многие компиляторы Эйфеля (за исключением Visual Eiffel) выдают код Си в качестве промежуточного языка, перенаправляя его потом компилятору Си. Это сделано для оптимизации кода и переносимости. Компилятор Эйфеля tecomp может выполнять код Эйфеля как интерпретатор, без использования промежуточного языка или может выдавать код Си, который будет далее перенаправлен компилятору Си для получения оптимизированного родного кода платформы исполнения. На базе .Net, компилятор EiffelStudio генерирует код CIL (англ. Common Intermediate Language). Компилятор SmartEiffel может генерировать байткод Java.


См. также

Примечания

  1. Подробнее смотри Оптимизация компилятора
  2. Object-Oriented Software Construction, Second Edition, by Bertrand Meyer, Prentice Hall, 1997, ISBN 0-13-629155-4
  3. ECMA International: Standard ECMA-367 —Eiffel: Analysis, Design and Programming Language 2nd edition (June 2006); available online at www.ecma-international.org/publications/standards/Ecma-367.htm
  4. International Organisation for Standardisation: Standard ISO/IEC DIS 25436, available online at [1]
  5. Bertrand Meyer: Overloading vs Object Technology, in Journal of Object-Oriented Programming (JOOP), vol. 14, no. 4, October-November 2001, available online
  6. Philippe Ribet, Cyril Adrian, Olivier Zendra, Dominique Colnet: Conformance of agents in the Eiffel language, in Journal of Object Technology, vol. 3, no. 4, April 2004, Special issue: TOOLS USA 2003, pp. 125-143. Available on line from the JOT article page


Дополнительная информация

an:Luengache de programazión Eiffel

cs:Eiffel da:Eiffel (programmeringssprog) de:Eiffel (Programmiersprache) es:Lenguaje de programación Eiffel eo:Eiffel (programlingvo) fr:Eiffel (langage) gl:Linguaxe de programación Eiffel it:Eiffel (linguaggio) hu:Eiffel (programozási nyelv) nl:Eiffel (programmeertaal) ja:Eiffel pl:Eiffel (język programowania) pt:Eiffel (linguagem de programação) sk:Eiffel (programovací jazyk) fi:Eiffel (ohjelmointikieli) uk:Eiffel

Личные инструменты

Served in 0.767 secs.