@c This is going to become a programmer's guide to GPC.
@c Started on 31 Jul 1997 by Peter Gerwinski, <peter@gerwinski.de>

@node Programming
@chapter The Programmer's Guide to GPC
@cindex programming in GPC

@strong{This chapter is under development, so don't be too excited about the
paragraph below!}

This chapter tells you how the source of a valid GNU Pascal program
should look like.  You can use it as tutorial about the GNU Pascal language,
but since the main goal is to document all special GPC features,
implementation-dependent stuff, etc., expect a steep learning curve.

This chapter does @emph{not} cover how to compile your programs and to produce
an executable---this is discussed above in @ref{Invoking GPC}.

@menu
* Source structures::   How a GNU Pascal source file looks like.
* Data types::          Standard and non-standard data types.
* Operators::           Built-in and user-definable operators.
* Schemata::            Using Extended Pascal's ``schema types''.
* Pointer arithmetics:: How pointer arithmetics can be applied to
                        speed up your program.
* Type casts::          Explicit and emulated type casting in GPC.
* OOP::                 How object-orientated programming is implemented.
* Other languages::     How to share libraries with other languages.
* Run time library::    Pascal declarations for GPC's run time library.
@end menu


@c ============================================================================


@node Source structures
@section Source Structures
@cindex source structures

A source file accepted by GNU Pascal may contain up to one program,
zero or more ISO-style Modules, and/or zero or more UCSD-style Units,
Units and Modules can be mixed in one project.

@menu
* Programs::  The source structure of programs.
* Modules::   The source structure of ISO-10206 Extended Pascal Modules.
* Units::     The source structure of UCSD/Borland Pascal Units.
@end menu

One trivial example for a valid GPC source file follows.  Note that the
below may either be in one source file, or else the Unit and the Program
may be in separate source files.

@cindex foo
@example
Unit Foo;

Interface

Procedure Hello;

Implementation

Procedure Hello;

begin (* Hello *)
  writeln ( 'Hello, world!' );
end (* Hello *);

end.


Program Bar;

uses
  Foo;

begin
  Hello;
end.
@end example


@c ----------------------------------------------------------------------------


@node Programs
@subsection The Source Structure of Programs
@cindex Programs, source structure

A generic GNU Pascal program looks like the following:

@example
Program @var{name} ( Input, Output );

@var{import part}

@var{declaration part}

begin
  @var{statement part}
end.
@end example

While the program parameters (usually @samp{Input, Output}) are obligatory in
ISO Pascal if you want to use @samp{readln} and @samp{writeln}, they are
optional in GNU Pascal.  However if you give parameters to the program
headline, they work like ISO requires.

The @var{import part} consists either of an ISO-style @samp{import}
specification or a UCSD/Borland-style @samp{uses} clause.  While
@samp{import} is intended to be used with interfaces exported by ISO-10206
Extended Pascal @samp{Modules} and @samp{uses} is intended to be used with 
@samp{Units}, this is not enforced.  (See also @ref{uses}, @ref{import}.)

The @var{declaration part} consists of constant, type, variable, procedure,
and function declarations in free order.

As an extension, GPC supports a ``declaring statement'' which can be used
in the statement part to declare variables (see @ref{Var}).


@c ----------------------------------------------------------------------------


@node Units
@subsection The Source Structure of UCSD/Borland Pascal Units
@cindex Units, source structure

A generic GNU Pascal Unit looks like the following:

@example
Unit @var{name};

Interface

@var{import part}

@var{interface part}

Implementation

@var{implementation part}

@var{initialization part}

end.
@end example

@cindex foo
The @var{name} of the unit should coincide with the name of the file
with the extension @file{.pas} or @file{.p} stripped.  (If not, you
can tell GPC the file name with @samp{uses foo in 'bar.pas'}, see
@ref{uses}.)

The @var{import part} is either empty or contains a @samp{uses} clause to
import other Units.  It may also consist of an ISO-style @samp{import}
specification.  Note that the implementation part is not preceeded by a
second import part in GPC (see @ref{import}).

The @var{interface part} consists of constant, type, and variable
declarations, procedure and function headings which may be freely mixed.

The @var{implementation part} is like the declaration part of a program,
but the headers of procedures and functions may be abbreviated:  Parameter
lists and function return values may be omitted for procedures and
functions already declared in the interface part.

The @var{initialization part} may be missing, or it may be a @samp{begin}
followed by one or more statements, such that the Unit has a statement part
between this @samp{begin} and the final @samp{end}.  Alternatively, a Unit
may have ISO-style Module initializers and finalizers, see @ref{to begin},
@ref{to end}.

Note that GPC does @emph{not} check whether all interface declarations are
resolved in the same Unit.  Procedures and functions which are in fact not
used may be omitted, and/or procedures and functions may be implemented
somewhere else, even in a different language.


@c ----------------------------------------------------------------------------


@node Modules
@subsection The Source Structure of ISO-10206 Extended Pascal Modules
@cindex Modules, source structure

(Under construction.  If you are familiar with
Extended Pascal Modules, please help!)


@c ============================================================================


@node Data types
@section Data Types

@menu
* Integer types::    GPC has @emph{lots of} built-in Integer types
* Subrange types::   Packed and non-packed subranges
* endianness::       How integer types are stored on different machines
* alignment::        How variables are placed in memory
@end menu


@c ----------------------------------------------------------------------------


@node Integer types
@subsection Integer Types
@cindex Integer types

Besides @samp{Integer}, GNU Pascal supports a large zoo of integer types.
Some of them you will find in other compilers, too, but most are GNU
extensions, introduced for particular needs.  Many of these types are
synonyms for each other.  In total, GPC provides 20 built-in integer types,
plus seven families you can play with.  (Four of these ``families'' are
signed and unsigned, packed and unpacked Subrange types; the others are
explained below.)

@menu
* Natural integer types::
* Main branch integer types::
* Integer types with specified size::
* Integer types and compatibility::
* Summary of integer types::
@end menu

See also: @ref{Subrange types}.


@c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 


@node Natural integer types
@subsubsection ``Natural'' Integer Types
@cindex integer types, ``natural''

For most purposes, you will always use @samp{Integer}, a signed integer type
which has the ``natural'' size of such types for the machine.  On most
machines GPC runs on, this is a size of 32 bits, so @samp{Integer} usually
has a range of @samp{-2147483648..2147483647} (see @ref{Integer}).

If you need an unsigned integer type, the ``natural'' choice is
@samp{Cardinal}, also called @samp{Word}.  Like @samp{Integer}, it has
32 bits on most machines and thus a range of @samp{0..4294967295} (see
@ref{Cardinal}, @ref{Word}).

These natural integer types should be your first choice for best
performance.  For instance on an Intel X86 processor operations with
@samp{Integer} usually work faster than operations with shorter integer
types like @samp{ShortInt} or @samp{ByteInt} (see below).


@c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 


@node Main branch integer types
@subsubsection ``Main Branch'' Integer Types
@cindex integer types, ``main branch''

@samp{Integer}, @samp{Cardinal}, and @samp{Word} define the three ``main
branches'' of GPC's integer types.  You won't always be able to deal with
the natural size; sometimes something smaller or longer will be needed.
Especially when interfacing with libraries written in other languages such
as C, you will need equivalents for their integer types.

The following variants of @samp{Integer}, @samp{Cardinal} and @samp{Word} are
guaranteed to be compatible to the integer types of GNU C.  The sizes,
however, are @emph{not} guaranteed.  They are just typical values currently
used on most platforms, but they may be actually shorter or increase in the
future.

@example
(signed)        (unsigned)         GNU C equivalent   typical size (bits) 

ByteInt    ByteCard    Byte        [un]signed char              8
ShortInt   ShortCard   ShortWord   [unsigned] short int        16
Integer    Cardinal    Word        [unsigned] int              32
MedInt     MedCard     MedWord     [unsinged] long int         32
LongInt    LongCard    LongWord    [unsinged] long long int    64
@end example

Since we don't know whether @samp{LongInt} will always remain the ``longest''
integer type available---maybe GNU C will get @samp{long long long int}, one
day, which we will support as @samp{LongLongInt}---we have added the synonym
@samp{LongestInt} for the longest available singed integer type, and the same
holds for @samp{LongestCard} and @samp{LongestWord}.


@c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 


@node Integer types with specified size
@subsubsection Integer Types with Specified Size
@cindex integer types, specified size

In some situations you will need an integer type of a well-defined size.
For this purpose, GNU Pascal provides tree families of signed and unsinged
integer types.  The type

@smallexample
  Integer ( 42 )
@end smallexample

is guaranteed to have a precision of 42 bits.  In a realistic context, you
will most often give a power of two as the number of bits, and the machine
you will need it on will support variables of that size.  If this is the case,
the specified precision will simultaneously be the amount of storage needed
for variables of this type.

In short:  If you want to be sure that you have a signed integer with 32 bits
width, write @samp{Integer ( 32 )}, not just @samp{Integer} which might be
bigger.  The same works with @samp{Cardinal} and @samp{Word} if you need
unsigned integer types of well-known size.


@c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 


@node Integer types and compatibility
@subsubsection Compatibility to other Pascal compilers
@cindex integer types, compatibility

If you care about ISO compliance, @emph{only} use @samp{Integer} and
subranges of @samp{Integer}.

Some of GPC's non-ISO integer types exist in Borland Pascal, too:
@samp{Byte}, @samp{ShortInt}, @samp{Word}, and @samp{LongInt}.  The
sizes of these types, however, are not the same as in Borland Pascal.
Even for @samp{Byte} this is not guaranteed (while probable, though).

When designing GNU Pascal, we thought about compatibility to Borland Pascal.
Since GNU Pascal is (at least) a 32-bit compiler, @samp{Integer} @emph{must}
have (at least) 32 bits.  But what to do with @samp{Word}?  Same size as
@samp{Integer} (like in BP) or 16 bits (like in BP)?  We decided to make
@samp{Word} the ``natural-sized'' unsigned integer type, thus making it
(at least) 32 bits wide.  Similarly, we decided to give @samp{LongInt} twice
the size of @samp{Integer} (like in BP) rather than making it 32 bits wide
(like in BP).  So @samp{LongInt} has 64 bits, and @samp{ShortInt} has 16 bits
on the Intel X86 platforms.

On the other hand, to increase compatibility to Borland Pascal and Delphi,
GPC provides the alias name @samp{Comp} for @samp{LongInt} (64 bits on Intel
X86) and @samp{SmallInt} for @samp{ShortInt} (16 bits on Intel X86).  Note
that BP treads @samp{Comp} as a ``real'' type and allows assignments like
@samp{MyCompVar:= 42.0}.  Since we don't consider this a feature, GPC does
not copy this behaviour.


@c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 


@node Summary of integer types
@subsubsection Summary of Integer Types
@cindex integer types, summary

Here is a summary of all integer types defined in GPC.  The sizes and ranges are
only @emph{typical} values, valid on some, but not all platforms.  Compatibility
to GNU C however @emph{is} guaranteed (to the extend of the GNU General Public
License, of course ;-).

@table @ref
@item ByteInt
  signed 8-bit integer type, @samp{-128..128}, @*
  compatible to @samp{signed char} in GNU C.
@item ByteCard, Byte
  unsigned 8-bit integer type, @samp{0..255}, @*
  compatible to @samp{unsigned char} in GNU C.
@item ShortInt
  signed 16-bit integer type, @samp{-32768..32767}, @*
  compatible to @samp{short int} in GNU C.
@item ShortCard, ShortWord
  unsigned 16-bit integer type, @samp{0..65535}, @*
  compatible to @samp{unsigned short int} in GNU C.
@item Integer
  signed 32-bit integer type, @samp{-2147483648..2147483647}, @*
  compatible to @samp{int} in GNU C.
@item Cardinal, Word
  unsigned 32-bit integer type, @samp{0..4294967295}, @*
  compatible to @samp{unsigned int} in GNU C.
@item MedInt
  signed 32-bit integer type, @samp{-2147483648..2147483647}, @*
  compatible to @samp{long int} in GNU C.
@item MedCard, MedWord
  unsigned 32-bit integer type, @samp{0..4294967295}, @*
  compatible to @samp{unsigned long int} in GNU C.
@item LongInt
  signed 64-bit integer type, @samp{-9223372036854775808..9223372036854775807}, @*
  compatible to @samp{long long int} in GNU C.
@item LongCard, LongWord
  unsigned 64-bit integer type, @samp{0..18446744073709551615}, @*
  compatible to @samp{unsigned long long int} in GNU C.
@item LongestInt
  signed 64-bit integer type, @samp{-9223372036854775808..9223372036854775807}.
@item LongestCard, LongestWord
  unsigned 64-bit integer type, @samp{0..18446744073709551615}.
@item Comp
  signed 64-bit integer type, @samp{-9223372036854775808..9223372036854775807}.
@item SmallInt
  signed 16-bit integer type, @samp{-32768..32767}.
@end table

To specify the number of bits, use

@table @samp
@item Integer ( @var{n} )
  signed @var{n}-bit integer type.
@item Cardinal ( @var{n} )
  unsigned @var{n}-bit integer type.
@item Word ( @var{n} )
  unsigned @var{n}-bit integer type.
@end table

See also: @ref{Subrange types}.


@c ----------------------------------------------------------------------------


@node Subrange types
@subsection Subrange Types
@cindex subrange types

GNU Pascal supports Standard Pascal's subrange types:

@smallexample
  Type
    MonthInt = 1..12;
    Capital = 'A'..'Z';
    ControlChar = ^A..^Z;  (* `^A' = `chr ( 1 )' is an extension *)
@end smallexample

To increase performance, variables of such a type are aligned in a way
which makes them fastest to access by the CPU.  As a result, @samp{1..12}
occupies 4 bytes of storage on an Intel X86 compatible processor.

For if you want to save storage at the expense of speed, GPC provides a
@samp{packed} variant of these as an extension:

@smallexample
  Type
    MonthInt = packed 1..12;
@end smallexample

A variable of this type occupies the shortest possible (= addressable) space
in memory---one byte on an Intel X86 compatible processor.

See also: @ref{packed}.


@c ----------------------------------------------------------------------------


@node endianness
@subsection Endianness
@cindex endianness

(Under construction.)


@c ----------------------------------------------------------------------------


@node alignment
@subsection Alignment
@cindex alignment

(Under construction.)


@c ============================================================================


@node Operators
@section Operators
@cindex Operators

GNU Pascal supports all operators of ISO Pascal and Borland Pascal.
In addition, you can define your own operators according to the
Pascal-SC (PXSC) syntax.

@menu
* Built-in operators::
* User-defined operators::
@end menu


@c ----------------------------------------------------------------------------


@node Built-in operators
@subsection Built-in Operators
@cindex operators, built-in

The following table lists all built-in GNU Pascal operators, ordered by
precedence:  @samp{:=} has lowest precedence, @samp{not} highest.
As usual, the precedence of operators can be superseeded with parentheses.

@example
:=
<    =    >    in   <>   >=   <=
+    -    or   +<   -<   +>   ->
*    /    div  mod  and  shl  shr  xor  *<   /<   *>   />
pow  **
not  &    @@
@end example

The Pascal-SC (PXSC) operators @samp{+<}, @samp{-<}, @samp{+>}, @samp{->},
@samp{*<}, @samp{/<}, @samp{*>}, and @samp{/>} are not yet implemented into
GNU Pascal but may be defined by the user (see below).


@c ----------------------------------------------------------------------------


@node User-defined operators
@subsection User-defined Operators
@cindex operators, user-defined

GNU Pascal allows the definition of binary operators according to the
Pascal-SC (PXSC) syntax.  The following ``scalar product'' example
illustrates how to do this:

@example
  Type
    Vector = record
      x, y: Real;
    end (* Vector *);

  Operator * ( a, b: Vector ) s: Real;  (* or: `= s: Real' *)

  begin (* Vector * Vector *)
    s:= a.x * b.x + a.y * b.y;
  ^end (* Vector * Vector *);

  Var
    u, v: Vector;
    a: Real;

  [...]

  a:= u * v;
@end example

Between the closing parenthesis of the argument list and the result variable,
GPC allows an optional equal sign.  This is not allowed in PXSC, but it is
consistent with Extended Pascal's function return variable definitions, where
the equal sign is obligatory (but optional in GPC).

The argument types needn't be equal, and the name of the operator may be an
identifier instead of a known symbol.  You cannot define @emph{new} symbols
in GPC.

The PXSC operators @samp{+>}, @samp{+<}, etc.@: for exact numerical calculations
currently are not implemented in GPC, but you can define them.  If you write
a module which really implements these operators, please send it to us, so we
can include it into the next distribution.  Also, the other real-type operators
do @emph{not} meet the requirements of PXSC; a module which fixes that would
be a welcome contribution.

(And if you know more about modules in Pascal-SC than just their existence,
please contact us either!  We could probably easily implement them if we knew
how they look like.  Something quite close to Pascal-SC modules already
@emph{is} implemented as ``GNU specific modules''.)


@c ============================================================================


@node Schemata
@section Schema Types
@cindex schemata
@cindex types, schema

Schemata are types that depend on one or more variables, called
``discriminants''.  They are an ISO-10206 Extended Pascal extension.

@smallexample
  Type
    RealArray ( n: Integer ) = array [ 1..n ] of Real;
@end smallexample

The type @samp{RealArray} in this example is called a Schema with the
discriminant @samp{n}.  To declare a variable of such a type, write

@cindex Foo
@smallexample
  Var
    Foo: RealArray ( 42 );
@end smallexample

Schema-typed variables ``know'' about their discriminants.  They can
be accessed just like record fields:

@smallexample
  writeln ( Foo.n );   (* yields 42 *)
@end smallexample

While types of variables must always have specified discriminants (which
may be other variables), @emph{pointers} to schema variables may be
without a discriminant:

@cindex Bar
@smallexample
  Type
    RealArrayPtr = ^RealArray;

  Var
    Bar: RealArrayPtr;
@end smallexample

When applying @samp{New} to such a pointer, you must specify the
intended value of the discriminant as a parameter:

@smallexample
  New ( Bar, 137 );
@end smallexample

As a GNU extension, the above can also be written as

@smallexample
  Bar:= New ( RealArrayPtr, 137 );
@end smallexample

Schemata are not limited to arrays.  They can be of any type that
normally requires constant values in its definition, for instance
subrange types, or records containing arrays etc.  (Sets do not yet
work.)

To finish this section, here is a somewhat exotic example:

@smallexample
  Type
    ColorType = ( red, green, blue );
    ColoredInteger ( Color: ColorType ) = Integer;
@end smallexample

A @samp{ColoredInteger} behaves just like an ordinary integer, but
it has an additional property @samp{Color} which can be accessed like
a record field.

@smallexample
  Var
    Foo: ColoredInteger ( green );

  [...]

  Foo:= 7;
  if Foo.Color = red then
    inc ( Foo, 2 )
  else
    Foo:= Foo div 3;
@end smallexample


@c ============================================================================


@node Pointer arithmetics
@section Pointer Arithmetics
@cindex pointer arithmetics

GPC allows to increment, decrement, compare, and subtract pointers or to use
them in @samp{for} loops just like the C language.

@smallexample
  Var
    A: array [ 1..7 ] of Char;
    p, q: ^Char;
    i: Integer;

  [...]

  for p:= @@A [ 1 ] to @@A [ 7 ] do
    p^:= 'x';

  p:= @@A [ 7 ];
  q:= @@A [ 3 ];
  while p > q do
    begin
      p^:= 'y';
      dec ( p );
    end (* while *);

  p:= @@A [ 7 ];
  q:= @@A [ 3 ];
  i:= q - p;      (* yields 4 *)
@end smallexample

Incrementing a pointer by one means to increment the address it contains
by the size of the variable it is pointing to.  For typeless pointers
(@samp{Pointer}), the address is incremented by one instead.

Similar things hold when decrementing a pointer.

Subtracting two pointers yields the number of variables pointed to
between both pointers, i.e.@: the difference of the addresses divided by
the size of the variables pointed to.  The pointers must be of the same
type.


@c ============================================================================


@node Type casts
@section Type Casts
@cindex type casts

In some cases, especially when interfacing with other languages,
Pascal's strong typing can be an obstacle.  To temporarily circumvent
this, GPC (and other Pascal compilers) defines explicit ``type casts''.

There are two kinds of type casts, value type casts and variable type
casts.

Value type casts

To convert a value of one data type into another type, you can use the
target type like the name of a function that is called. The value to be
converted can be a variable or an expression.

An example:

@smallexample
  Var
    Ch: Char;
    i: Integer;

  [...]

  i := Integer (Ch);
@end smallexample

Another, more complicated, example:

@smallexample
  Type
    CharPtr = ^Char;
    CharArray = array [ 0..99 ] of Char;
    CharArrayPtr = ^CharArray;

  Var
    Foo1, Foo2: CharPtr;
    Bar: CharArrayPtr;

  [...]

  @{$X+@} @{ We need extended syntax in order to use ``Succ'' on a pointer @}

  Foo1 := CharPtr ( Bar );
  Foo2 := CharPtr ( Succ ( Bar ) );
@end smallexample

However, because of risks involved with type casts, explained below,
you should try to avoid type casts whenever possible -- and it should be
possible in most cases. For instance, the first example above could use
the built-in function ``Ord'' instead of the type cast:

@smallexample
  i := Ord (Ch);
@end smallexample

The assignments in the second example could be written in the following
way without any type casts:

@smallexample
  Foo1 := @@Bar^ [ 0 ];
  Foo2 := @@Bar^ [ 1 ];
@end smallexample

Value type casting only works between certain types: either between
different ordinal types (including integer types), or between different
real types, or between different pointer types. In each case, the actual
value, i.e. the ordinal or numeric value or the address pointed to,
respectively, is preserved in the cast.

Note: It is also possible to cast from an integer into a real type.
This is a consequence of the fact that integer values are generally
automatically converted to real values when needed.

Note: In the case of pointers, a warning is issued if the dereferenced
target type requires a bigger alignment than the dereferenced source type
(see @ref{alignment}).

Variable type casts

It is also possible to temporarily change the type of a variable,
without converting its contents in any way. This is called variable
type casting.

The syntax is the same as for value type casting. This can be confusing,
as the example below shows.

The type-casted variable is still the same variable (memory location)
as the original one, just with a different type. Outside of the type
cast, the variable keeps its original type.

There are some important differences between value and variable type
casting:

@itemize @bullet

@item
  Variable type casting only works on variables, not on expressions.

@item
  The result of a variable type casting is still a variable.
  Especially, it can be used on the left side of an assignment
  (as a so-called ``lvalue''), or passed by reference to a procedure.

@item
  No values are converted. The contents of the variable, seen as a raw
  bit pattern, are just interpreted according to the new type. In many
  cases, this does not make a big difference, e.g. the same ordinal
  values of different ordinal types have the same bit pattern (provided,
  the types have the same size), and similarly for different pointer types.
  However, there are cases where it does make a difference, most notably
  the completely different internal representation of integer and real
  types. This is demonstrated in the following example, admittedly a
  very constructed example, by using an integer and a real type of the
  same size and trying to cast between them.

@item
  Because bit patterns are just interpreted differently, the source and
  target type must have the same size. If this is not the case, GPC will
  give a warning. (@@error? see below)

@item
  Beware: Variable type casts might have unexpected effects on different
  platforms since you cannot rely on a specific way the data is stored
  (e.g. see @ref{endianness}).

@end itemize

@example
  program TypeCastingTraps;

  @{ Declare a real type and an integer type of the same size, and some
    variables of these types we will need. @}

  Type
    RealType    = ShortReal;
    IntegerType = Integer ( BitSizeOf ( RealType ) );

  Var
    i, i1, i2, i3, i4, i5: IntegerType;
    r, r1, r2, r3, r4:     RealType;

  begin

    @{ First part: Casting integer into real types. @}

    @{ Start with some integer value @}
    i := 42;

    @{ First attempt to cast. Here, an lvalue is casted, so this must
      be a variable type cast. Therefore, the bit pattern of the value
      of i is transferred unchanged into r1 which results in a silly
      value of r1. @}
    IntegerType (r1) := i;

    @{ Second try. Here we cast an expression -- though a trivial one --,
      rather than a variable. So this can only be a value type cast.
      Therefore, the numeric value is preserved, i.e. r2 = 42.0 . @}
    r2 := RealType (i+0);

    @{ Third way. In this last example, a variable is casted, and the
      result is used as an expression, not as an lvalue. So this
      could be either a value or variable type cast. However, there
      is a rule that value type casting is preferred if possible.
      So r3 will contain the correct numeric value, too. @}
    r3 := RealType (i);

    @{ Of course, you do not need any casts at all here. A simple
      assignment will work because of the automatic conversion from
      integer to real types. So r4 will also get the correct result. @}
    r4 := i;

    @{ Now the more difficult part: Casting real into integer types. @}

    @{ Start with some real value. @}
    r := 41.9;

    @{ Like the first attempt above, this one does a variable type cast,
      preserving bit patterns, and leaving a silly value in i1. @}
    RealType (i1) := r;

    @{ The second try from above does not work, because an expression of
      type real is to be casted into an integer which is not allowed. @}
    @{ i2 := IntegerType (r+0); @}

    @{ Third way. This looks just like the third way in the first part
      which was a value type cast.
      But -- surprise! Since value type casting is not possible from
      real into integer, this really does a variable type casting,
      and the value of i3 is silly again! This difference in behaviour
      shows some of the hidden traps in type casting. @}
    i3 := IntegerType (r);

    @{ As often, it is possible to avoid type casts altogether and
      convert real types into integers easily by other means, i.e. by
      using the built-in functions ``Round'' or ``Trunc'', depending
      on the mode of rounding one wants. @}
    i4 := Round (r); @{ 42 @}
    i5 := Trunc (r); @{ 41 @}

  end.
@end example

When dealing with objects (see @ref{OOP}), it is often necessary---and
safe---to cast a pointer to an object into a pointer to a more specialized
(derived) object.  In future releases, GPC will provide an operator
@samp{as} for a safer approach to this problem.

See also: @ref{absolute}, @ref{alignment}, @ref{endianness}, @ref{OOP},
          @ref{ord}, @ref{chr}, @ref{round}, @ref{trunc}.


@c ============================================================================


@node OOP
@section Object-orientated Programming
@cindex OOP
@cindex Object-orientated programming

GNU Pascal follows the object model of Borland Pascal 7.0.  The ANSI draft
Object Pascal language and the Delphi language (also called ``Object Pascal''
by Borland) are currently not implemented, but planned for future versions of
GPC.

The syntax for an object type declaration is as follows:

@cindex foo
@example
  Type
    fooParentPtr = ^fooParent;
    fooPtr = ^foo;

    fooParent = object
      Destructor Fini; virtual;
      Procedure bar ( c: Real ); virtual;
      Procedure baz ( b, a, z: Char );  (* not virtual *)
    end (* FooParent *)

    foo = object ( fooParent )
      x, y: Integer;
      Constructor Init ( a, b: Integer );
      Destructor Fini; virtual;
      z: Real;
      Procedure bar ( c: Real ); virtual;  (* overrides `fooParent.bar' *)
      Function baz: Boolean;  (* new function *)
    end (* foo *);
@end example

Remarks:

@itemize @bullet

@item
Data fields and methods can be mixed.

@item
GPC currently does not support @samp{private} declarations and such.

@item
Constructors and destructors are ordinary functions, internally.  When a
constructor is called, GPC creates some inline code to initialize the object;
destructors do nothing special.

@item
Currently, the @file{gpc1} compiler does not check whether all declared
methods are really implemented; the linker does check this.

@end itemize

A pointer to @samp{fooParent} may be assigned the address of a @samp{foo}
object.  A @samp{fooParent} formal @samp{Var} parameter may get a @samp{foo}
object as the actual parameter.  In such cases, a call to a @samp{virtual}
method calls the child's method, whereas a call to a non-@samp{virtual} method
selects the parent's one:

@smallexample
  Var
    MyFooParent: fooParentPtr;
    SomeFoo: foo;

  [...]

  SomeFoo.Init ( 4, 2 );
  MyFooParent:= @@SomeFoo;
  MyFooParent^.bar ( 3.14 );  (* calls `foo.bar' *)
  MyFooParent^.baz ( 'b', 'a', 'z' );  (* calls `fooParent.baz' *)
  if SomeFoo.baz then  (* calls `foo.baz' *)
    writeln ( 'Baz!' );
@end smallexample

In a method, an overwritten method of a parent object can be called either
prefixing it with the parent type name, or using the keyword @samp{inherited}:

@smallexample
  Procedure foo.bar ( c: Real );

  begin (* foo.bar *)
    z:= c;
    inherited bar ( z );  (* Or: fooParent.bar ( z ) *)
  end (* foo.bar *);
@end smallexample

@cindex inherited
Use @samp{fooParent.bar ( z )} if you want to be sure that @emph{this} method
is called, even if somebody decides not to derive @samp{foo} directly from
@samp{fooParent} but to have some intermediate object.  If you want to call
the method @samp{bar} of the immediate parent---whether it be @samp{fooParent}
or whatever---use @samp{inherited bar ( z )}.

@cindex New
To allocate an object on the heap, use @samp{New} in one of the
following manners:

@smallexample
  Var
    MyFoo: fooPtr;

  [...]

  New ( MyFoo, Init ( 4, 2 ) );

  MyFooParent:= New ( fooPtr, Init ( 4, 2 ) );
@end smallexample

The second possibility has the advantage that @samp{MyFoo} needn't be a
@samp{fooPtr} but can also be a @samp{fooParentPtr}, i.e.@: a pointer to
an ancestor of @samp{foo}.

Destructors can and should be called within Dispose:

@smallexample
  Dispose ( MyFooParent, Fini );
@end smallexample


@c ============================================================================


@node Other languages
@section Interfacing with Other Languages
@cindex GPC and other languages
@cindex C

The standardized GNU compiler back-end makes it relatively easy to share
libraries between GNU Pascal and other GNU compilers.  On UNIX-like platforms
(@emph{not} on MS-DOS-like platforms), the GNU compiler back-end usually
complies to the standards defined for that system, so communication with other
compilers should be easy, too.

In this chapter we discuss how to import libraries written in other languages,
and how to import libraries written in GNU Pascal from other languages.  While
the examples will specialize to compatibility to GNU C, generalization is
straightforward if you are familiar with the other language in question.

@menu
* Importing from other languages::
* Exporting to other languages::
@end menu


@c ----------------------------------------------------------------------------


@node Importing from other languages
@subsection Importing Libraries from Other Languages
@cindex asmname

To use a function written in another language, you need to provide an external
declaration for it---either in the program, or in the interface part of a
Unit, or an Interface Module.

Let's say you want to use the following C library from Pascal:

@cindex foo
@example
  /* foobar.c */

  #include <unistd.h>

  int foo = 1;

  void bar ( void )
  @{
    sleep ( foo );
  @} /* bar */


  /* foobar.h */

  extern int foo;
  extern void bar ( void );
@end example

Then your program can look like this:

@example
  Program TestFoo;

  (*$L foobar.c *)  (* Or: `foobar.o' if you don't have the source *)

  Var
    foo: asmname 'foo' Integer;

  Procedure Bar; asmname 'bar';

  begin
    foo:= 42;
    Bar;  (* Take a break :*)
  end.
@end example

Or, if you want to provide a @samp{FooBar} Unit:

@example
  Unit FooBar;

  Interface

  Var
    foo: asmname 'foo' Integer;

  Procedure Bar; asmname 'bar';
  
  Implementation

  (* empty *)

  end.
@end example

@cindex linking
You can either link your program manually with @samp{foobar.o} or put a
compiler directive @samp{(*$L foobar.o *)} into your program (planned for
Units, too), and then GPC cares about the linking.  If you have the source
of the ``FooBar'' library (you always have it if it is Free Software), you
can even write @samp{(*$L foobar.c *)} in the program (like above).  Then
GPC will also link with @file{foobar.o}, but in addition GPC will run the
C compiler whenever @file{foobar.c} has changed if @samp{--automake} is
given, too.

While it is convenient for most applications, there is no must to give the
C function @samp{bar} the name @samp{Bar} in Pascal; you can name it as you
like.

@cindex C
@cindex C_Language
@cindex C language
@cindex extern
@cindex external
For external functions completely written in lowercase there is the shortcut
@samp{C} or @samp{C_language} for @samp{asmname 'bar'}.  For external
functions written with one uppercase letter and the others in lowercase, you
can use @samp{external} or @samp{extern} instead of @samp{asmname 'Bar'}.
Since GPC internally converts all identifiers to this notation,
@samp{external} is the natural choice when importing other Pascal functions.

@strong{Caution:} This syntax (@samp{C}, @samp{asmname} and such) is subject
to change, especially for variables.

@cindex --gpc-main
@cindex main program
Some libraries provide a @samp{main} function and require your program's
``main'' to be named differently.  To achive this with GPC, invoke it with an
option @samp{--gpc-main="GPCmain"} (where ``GPCmain'' is an example how you
might want to name the program).  You can also write it into your source as
a directive @samp{(*$pascal-main="GPCmain" *)}.


@c ----------------------------------------------------------------------------


@node Exporting to other languages
@subsection Exporting GPC Libraries to Other Languages

The @file{.o} files produced by GPC are in the same format as those of all
other GNU compilers, so there is no problem in writing libraries for other
languages in Pascal.  To use them, you will need to write kind of
interface---a header file in C.  However there are some things to take
into account, especially if your Pascal Unit exports objects:

@itemize @bullet

@item
By default, GPC capitalizes the first letter of each identifier, so
@samp{Procedure FooBAR} must be imported as @samp{extern void Foobar()}
from C.

@item
If you want to specify the external name separately, use @samp{asmname}:

@smallexample
  Procedure FooBAR; asmname 'FooBAR';
  (* Works like a `forward' declaration *)

  Procedure FooBAR;

  begin (* FooBAR *)
    writeln ( 'FooBAR' );
  end (* FooBAR *);
@end smallexample

This one can be imported from C with @samp{extern void FooBar()}.

@item
@cindex Objects
@cindex VMT
Objects are ``records'' internally.  They have an implicit @samp{vmt} field
which contains a pointer to the ``virtual method table''.  This table is
another record of the following structure:

@smallexample
  Type
    SizeInt = Integer ( BitSizeOf ( Pointer ) );

    VMT = record
      ObjectSize: SizeInt;  (* Size of object in bytes. *)
      NegObjectSize: SizeInt;  (* Its negative. *)
      Fun: array [ 1..n ] of Procedure;
        (* Pointers to the virtual functions. *)
    end (* VMT *);
@end smallexample

You can call a virtual method of an object from C if you explicitly declare
this @samp{struct} and explicitly dereference the @samp{Fun} array.  The VMT
of an object @samp{FooBAR} is an external (in C sense) variable @samp{vmt_Foobar}
internally.

@item
Methods of objects are named @samp{Myobject_Mymethod} (with exactly two capital
letters) internally.

@item
@cindex main program
The main program is just another procedure; @samp{Program FooBAR} produces
@samp{Procedure FooBAR; asmname 'program_Foobar'} (without parameters)
internally.  There is a separate function @samp{main} which stores the
command-line arguments in global variables and then calls this ``main
procedure''.

@item
If you want to put a program in a library for some reason, and you want to
give the @samp{main} program an internal name different from @samp{main}, call
GPC with the option @samp{--pascal-main="GPCmain"} (see previous subsection).

@end itemize


@c ============================================================================


@node Run time library
@section Run Time Library---Pascal Declarations
@cindex Run time library

Below is a pascal source of the declarations in GPC's run time library.
A file @file{gpc.pas} with the same contents is included in the GPC
distribution in the same directory as @file{libgcc.a}.  (To find out
the correct directory for your installation type
@samp{gpc -print-libgcc-file-name} at the command prompt.)

@example
@include gpcpas.texi
@end example
