FPC JVM/Language/ru

This is an old revision of FPC JVM/Language/ru, edited by Skalogryz at . The current revision is 76527.

/* Частично поддерживаемые конструкции */

Общая информация

Поддержка JVM это пока лишь изменения в компиляторе. А это значит, что портирован только модуль System и модули которые импортируют лишь некоторые JDK классы. Другие RTL модули не доступны. Функционал модуля System так же очень ограничен (подробности ниже).

Со временем, вполне возможно реализовать большинство стандартных модулей RTL таким образом, чтобы они компилировались для JVM платформы. Но это не является целью и баг-репорты о том что какого-то модуля не хватает - особой пользы не принесут. (Но конечно, патчи приветствуются!)

Компиляция в JVM код на данный момент довольно медленная. Причина - используемый Ява ассемблер Jasmin - медленный. И причина не в том, что сам ассемблер написан на Java, а просто потому что он так написан.

Минимальная требуемая версия JDK для программ скомпилированных FPC - 1.5.

Терминология и соглашения

Базовое поведение платформы

По устройству компилятора платформа Java/JVM рассматривается как 32-битная. Это лишь означает, что вся арифметика ориентируется, по умолчанию, на 32-бита, а не 64. Точно так же, как и на нативных платформах, созданный код будет без проблем запускаться и на 64-битных ява-машинах. Компилятор так же будет использовать 64-битные инструкции (опкоды) для 64-битных вычислений.

Причина такого выбора:

Тип extended приравнен к типу double, точно так же, как и на других платформах, не поддерживающих 80-битовые числа с плавающей точкой.

Языковая поддержка

В связи с разницей между JVM и нативными платформами, не все особенности языка FPC могут быть поддержаны на JVM. Языковая конструкция не указанная ниже, при компиляции в JVM работает точно так же и при обычной компиляции. Однако может возникать некоторая разница в производительности и внутренней реализации.

Основные конструкции языка

Неподдерживаемые конструкции

Частично поддерживаемые конструкции

New language features

<delphi> type JavaClassName = class [external ['package.name'] [name 'ExternalClassName']] [(JavaSuperClassName|ProtocolName [, ProtocolName, ProtocolName])] [strict][private, protected, public]

[variables declarations]
[method declarations]

end; </delphi>

Overloading

A number of different Pascal types and parameter passing conventions map to the same type signature in the JVM. The reason is that the JVM supports less primitive types than Pascal, and because some parameter passing constructs have to be emulated using other types.

This means that certain overloads that are valid for native targets are invalid when targeting the JVM, because the internal method name has to encode the parameter types on that target. The compiler will detect such situations and print an error when they occur.

Cases that you may encounter include:

Specific language features information

Classes

Classes are implemented as Java classes:

Issues to take into account when using FPC-defined classes from Java code:

<delphi> type TMyClass = class constructor Create(l: longint); virtual; end; </delphi>

becomes

<java> class TMyClass { TMyClass(int l) { ... }

// the generic parameter declaration means "any class reference // type for TMyClass or one of its descendants") static TMyClass Create(java.lang.Class<? extends TMyClass> self, int l) { ... } </java>

Interfaces

Interfaces are implemented as Java interfaces:

Implicit pointer types

As mentioned in the #Used_terminology_and_conventions, certain types that are not pointer-based in the Pascal language are implemented on top of Java classes or arrays. These data structures are pointers in Java, and as a result we can do some things with them that we cannot do with other types that map more directly onto a Java type.

The implicit pointer types and their corresponding Java representations are listed below:

Specific properties of implicit pointer types are:

Strings

String, unicodestring and java.lang.String

The JVM internally only supports a 16 bit unicodestring type (java.lang.String). For this reason, unicodestring is generally somewhat more efficient that either ansistring or shortstring on the JVM target.

A unicodestring directly maps to the java.lang.String type. This means that if your code is supposed to be called from Java code, all public string parameters and constants should be unicodestring rather than some other string type.

In order to facilitate this process, a new {$modeswitch unicodestrings} has been added to the compiler. If used together with {$h+}, it will make uncodestring the default string type and widechar the default char type. This is similar to the change in Delphi 2009, except that it is available via a modeswitch rather than forced onto all code.

If {$modeswitch unicodestrings} is used with {$h-}, then the default string type will be shortstring but the default char type will remain widechar. Notice that {$h+} is the default for {$mode delphi}.

Ansistring and shortstring code page

The "ansi" code page is set by the java program on startup. A default code page is chosen based on the environment on Linux and Windows. On Mac OS X, for legacy reasons the default code page is always MacRoman, which almost never is what you really want to use. See the Usage instructions for details on how to specify the default code page.

Type aliases and subrange types

The JVM supports neither type aliases nor subrange types. As a result, none of the marked type definitions in the following example will be visible to Java code. Of course, they still work as expected in Pascal code. <delphi> type

 tc = class
 end;
 tenum = (ea,eb,ec);
 tc2 = tc; // Pascal-only
 intsub = 3..41; // Pascal-only
 enumsub = eb..ec; // Pascal-only

</delphi>