Daily bump.
[official-gcc.git] / gcc / doc / gm2.texi
blob5bff9eb3829d8af1dc434895ffa737dac64e7a58
1 \input texinfo
2 @c -*-texinfo-*-
3 @c Copyright (C) 2001-2024 Free Software Foundation, Inc.
4 @c This is part of the GM2 manual.
6 @c User level documentation for GNU Modula-2
7 @c
8 @c header
10 @setfilename gm2.info
11 @settitle The GNU Modula-2 Compiler
13 @set version-python  3.5
15 @include gcc-common.texi
17 @c Copyright years for this manual.
18 @set copyrights-gm2 1999-2024
20 @copying
21 @c man begin COPYRIGHT
22 Copyright @copyright{} @value{copyrights-gm2} Free Software Foundation, Inc.
24 Permission is granted to copy, distribute and/or modify this document
25 under the terms of the GNU Free Documentation License, Version 1.3 or
26 any later version published by the Free Software Foundation; with no
27 Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
28 A copy of the license is included in the
29 @c man end
30 section entitled ``GNU Free Documentation License''.
31 @ignore
32 @c man begin COPYRIGHT
33 man page gfdl(7).
34 @c man end
35 @end ignore
36 @end copying
38 @ifinfo
39 @format
40 @dircategory Software development
41 @direntry
42 * gm2: (gm2).               A GCC-based compiler for the Modula-2 language
43 @end direntry
44 @end format
46 @insertcopying
47 @end ifinfo
49 @titlepage
50 @title The GNU Modula-2 Compiler
51 @versionsubtitle
52 @author Gaius Mulley
54 @page
55 @vskip 0pt plus 1filll
56 Published by the Free Software Foundation @*
57 51 Franklin Street, Fifth Floor@*
58 Boston, MA 02110-1301, USA@*
59 @sp 1
60 @insertcopying
61 @end titlepage
62 @contents
63 @page
65 @c `Top' Node and Master Menu
67 @node Top, Overview, (dir), (dir)
68 @top Introduction
70 @menu
71 * Overview::         What is GNU Modula-2.
72 * Using::            Using GNU Modula-2.
73 * License::          License of GNU Modula-2
74 * Copying::          GNU Public License V3.
75 * Contributing::     Contributing to GNU Modula-2
76 @c * Internals::        GNU Modula-2 internals.
77 * EBNF::             EBNF of GNU Modula-2
78 * Libraries::        PIM and ISO library definitions.
79 * Indices::          Document and function indices.
80 @end menu
82 @node Overview, Using, Top, Top
83 @chapter Overview of GNU Modula-2
85 @menu
86 * What is GNU Modula-2::  Brief description of GNU Modula-2.
87 * Why use GNU Modula-2::  Advantages of GNU Modula-2.
88 * Development::           How to get source code using git.
89 * Features::              GNU Modula-2 Features
90 @end menu
92 @node What is GNU Modula-2, Why use GNU Modula-2, , Overview
93 @section What is GNU Modula-2
95 GNU Modula-2 is a @uref{https://gcc.gnu.org/frontends.html, front end}
96 for the GNU Compiler Collection (@uref{https://gcc.gnu.org, GCC}).
97 The GNU Modula-2 compiler is compliant with the PIM2, PIM3, PIM4 and
98 ISO dialects.  Also implemented are a complete set of free ISO
99 libraries and PIM libraries.
101 @footnote{The four Modula-2 dialects supported are defined in the following
102 references:
104 PIM2: 'Programming in Modula-2', 2nd Edition, Springer Verlag, 1982,
105 1983 by Niklaus Wirth (PIM2).
107 PIM3: 'Programming in Modula-2', 3rd Corrected Edition, Springer Verlag,
108 1985 (PIM3).
110 PIM4: 'Programming in Modula-2', 4th Edition, Springer Verlag, 1988
111 (@uref{http://freepages.modula2.org/report4/modula-2.html, PIM4}).
113 ISO: the ISO Modula-2 language as defined in 'ISO/IEC Information
114 technology - programming languages - part 1: Modula-2 Language,
115 ISO/IEC 10514-1 (1996)'
118 @node Why use GNU Modula-2, Development, What is GNU Modula-2, Overview
119 @section Why use GNU Modula-2
121 There are a number of advantages of using GNU Modula-2 rather than
122 translate an existing project into another language.
124 The first advantage is of maintainability of the original sources
125 and the ability to debug the original project source code using a
126 combination of gm2 and gdb.
128 The second advantage is that gcc runs on many processors and
129 platforms.  gm2 builds and runs on powerpc64le, amd64, i386, aarch64
130 to name but a few processors.
132 gm2 can produce swig interface headers to allow access from Python and
133 other scripting languages.  It can also be used with C/C++ and
134 generate shared libraries.
136 The compiler provides semantic analysis and run time checking (full ISO
137 Modula-2 checking is implemented) and there is a plugin which can,
138 under certain conditions, detect run time errors at compile time.
140 The compiler supports PIM2, PIM3, PIM4 and ISO dialects of Modula-2,
141 work is underway to implement M2R10.  Many of the GCC builtins are
142 available and access to assembly programming is achieved using the
143 same syntax as that used by GCC.
145 The gm2 driver allows third party libraries to be installed alongside
146 gm2 libraries.  For example if the user specifies library @code{foo}
147 using @code{-flibs=foo} the driver will check the standard GCC install
148 directory for a sub directory @code{foo} containing the library
149 contents.  The library module search path is altered accordingly
150 for compile and link.
152 @node Development, Features, Why use GNU Modula-2, Overview
153 @section How to get source code using git
155 GNU Modula-2 is now in the @url{https://gcc.gnu.org/git.html, GCC git
156 tree}.
158 @node Features, , Development, Overview
159 @section GNU Modula-2 Features
161 @itemize @bullet
163 @item
164 the compiler currently complies with Programming in Modula-2 Edition
165 2, 3, 4 and ISO Modula-2.  Users can switch on specific language
166 features by using: @samp{-fpim}, @samp{-fpim2}, @samp{-fpim3},
167 @samp{-fpim4} or @samp{-fiso}.
169 @item
170 the option @samp{-fswig} will automatically create a swig interface
171 file which corresponds to the definition module of the file being
172 compiled.
174 @item
175 exception handling is compatible with C++ and swig.  Modula-2 code can
176 be used with C or C++ code.
178 @item
179 Python can call GNU Modula-2 modules via swig.
181 @item
182 shared libraries can be built.
184 @item
185 fixed sized types are now available from @samp{SYSTEM}.
187 @c @item
188 @c support for dynamic @code{ARRAY}s has been added into @samp{gdb}.
190 @item
191 variables can be declared at addresses.
193 @item
194 much better dwarf-2 debugging support and when used with
195 @samp{gdb} the programmer can display @code{RECORD}s,
196 @code{ARRAY}s, @code{SET}s, subranges and constant char literals
197 in Modula-2 syntax.
199 @item
200 supports sets of any ordinal size (memory permitting).
202 @item
203 easy interface to C, and varargs can be passed to C routines.
205 @item
206 many Logitech libraries have been implemented and can be accessed via:
207 @samp{-flibs=m2log,m2pim,m2iso}.
209 @item
210 coroutines have been implemented in the PIM style and these are
211 accessible from SYSTEM.  A number of supporting libraries (executive
212 and file descriptor mapping to interrupt vector libraries are
213 available through the @samp{-flibs=m2iso,m2pim} switch).
215 @item
216 can be built as a cross compiler (for embedded microprocessors
217 such as the AVR and the ARM).
219 @end itemize
221 @node Using, License, Overview, Top
222 @chapter Using GNU Modula-2
224 @menu
225 * Example usage::         Example compile and link.
226 * Compiler options::      GNU Modula-2 compiler options.
227 * Linking::               Linking options in more detail.
228 * Elementary data types:: Data types supported by GNU Modula-2.
229 * Standard procedures::   Permanently accessible base procedures.
230 * High procedure function:: Behavior of the high procedure function.
231 * Dialect::               GNU Modula-2 supported dialects.
232 * Exceptions::            Exception implementation
233 * Semantic checking::     How to detect run time problems at compile time.
234 * Extensions::            GNU Modula-2 language extensions.
235 * Type compatibility::    Data type compatibility.
236 * Unbounded by reference::Explanation of a language optimization.
237 * Building a shared library:: How to build a shared library.
238 * Interface for Python::  How to produce swig interface files.
239 * Producing a Python module::  How to produce a Python module.
240 * Interface to C::        Interfacing GNU Modula-2 to C.
241 * Assembly language::     Interface to assembly language.
242 * Alignment::             Data type alignment.
243 * Packed::                Packing data types.
244 * Built-ins::             Accessing GNU Modula-2 Built-ins.
245 * The PIM system module:: SYSTEM data types and procedures.
246 * The ISO system module:: SYSTEM data types, procedures and run time.
247 @c @ifnothtml
248 @c omit these nodes if generating gm2 webpage as these are hand written.
249 * Release map:: Release map.
250 * Documentation:: Placeholder for how to access the documentation online.
251 * Regression tests:: How to run the testsuite.
252 * Limitations:: Current limitations.
253 * Objectives:: Objectives of the implementation.
254 * FAQ:: Frequently asked questions.
255 * Community:: How to join the community.
256 * Other languages:: Other languages for GCC.
257 @c @end ifnothtml
258 @end menu
260 This document contains the user and design issues relevant to the
261 Modula-2 front end to gcc.
263 @node Example usage, Compiler options, Using, Using
264 @section Example compile and link
266 @ignore
267 @c man begin SYNOPSIS gm2
268 gm2 [@option{-c}|@option{-S}] [@option{-g}] [@option{-pg}]
269     [@option{-O}@var{level}] [@option{-W}@var{warn}@dots{}]
270     [@option{-I}@var{dir}@dots{}] [@option{-L}@var{dir}@dots{}]
271     [@option{-f}@var{option}@dots{}] [@option{-m}@var{machine-option}@dots{}]
272     [@option{-o} @var{outfile}] [@@@var{file}] @var{infile}@dots{}
274 Only the most useful options are listed here; see below for the
275 remainder.
276 @c man end
277 @c man begin SEEALSO
278 gpl(7), gfdl(7), fsf-funding(7), gcc(1)
279 and the Info entries for @file{gm2} and @file{gcc}.
280 @c man end
281 @end ignore
283 @c man begin DESCRIPTION gm2
285 The @command{gm2} command is the GNU compiler for the Modula-2 language and
286 supports many of the same options as @command{gcc}.  @xref{Option Summary, ,
287 Option Summary, gcc, Using the GNU Compiler Collection (GCC)}.
288 This manual only documents the options specific to @command{gm2}.
290 @c man end
292 This section describes how to compile and link a simple hello world
293 program.  It provides a few examples of using the different options
294 mentioned in @pxref{Compiler options}.  Assuming that you have
295 a file called @file{hello.mod} in your current directory which
296 contains:
298 @example
299 MODULE hello ;
301 FROM StrIO IMPORT WriteString, WriteLn ;
303 BEGIN
304    WriteString ('hello world') ; WriteLn
305 END hello.
306 @end example
308 You can compile and link it by: @samp{gm2 -g hello.mod}.
309 The result will be an @samp{a.out} file created in your directory.
311 You can split this command into two steps if you prefer.  The compile
312 step can be achieved by: @samp{gm2 -g -c -fscaffold-main hello.mod}
313 and the link via: @samp{gm2 -g hello.o}.
315 @footnote{To see all the compile actions taken by @samp{gm2} users can also
316 add the @samp{-v} flag at the command line, for example:
318 @samp{gm2 -v -g -I. hello.mod}
320 This displays the sub processes initiated by @samp{gm2} which can be useful
321 when trouble shooting.}
323 @node Compiler options, Linking, Example usage, Using
324 @section Compiler options
326 This section describes the compiler options specific to GNU Modula-2
327 for generic flags details @xref{Invoking GCC, , ,gcc}.
329 @c man begin OPTIONS
331 For any given input file, the file name suffix determines what kind of
332 compilation is done.  The following kinds of input file names are supported:
334 @table @gcctabopt
335 @item @var{file}.mod
336 Modula-2 implementation or program source files.  See the
337 @samp{-fmod=} option if you wish to compile a project which uses a
338 different source file extension.
339 @item @var{file}.def
340 Modula-2 definition module source files.  Definition modules are not
341 compiled separately, in GNU Modula-2 definition modules are parsed as
342 required when program or implementation modules are compiled.  See the
343 @samp{-fdef=} option if you wish to compile a project which uses a
344 different source file extension.
345 @end table
347 You can specify more than one input file on the @command{gm2} command line,
349 @table @code
351 @item -g
352 create debugging information so that debuggers such as @file{gdb}
353 can inspect and control executable.
355 @item -I
356 used to specify the search path for definition and implementation
357 modules.  An example is:  @code{gm2 -g -c -I.:../../libs foo.mod}.
358 If this option is not specified then the default path is added
359 which consists of the current directory followed by the appropriate
360 language dialect library directories.
362 @c ordered list of options from here.
364 @item -fauto-init
365 turns on auto initialization of pointers to NIL.  Whenever a block is
366 created all pointers declared within this scope will have their
367 addresses assigned to NIL.
369 @item -fbounds
370 turns on run time subrange, array index and indirection via @code{NIL}
371 pointer checking.
373 @item -fcase
374 turns on compile time checking to check whether a @code{CASE}
375 statement requires an @code{ELSE} clause when on was not specified.
377 @item -fcpp
378 preprocess the source with @samp{cpp -lang-asm -traditional-cpp}
379 For further details about these options @xref{Invocation, , ,cpp}.
380 If @samp{-fcpp} is supplied then all definition modules and
381 implementation modules which are parsed will be prepossessed by
382 @samp{cpp}.
384 @c fcpp-end
385 @c Modula-2
386 @c passed to the preprocessor if -fcpp is used (internal switch)
388 @c fcpp-begin
389 @c Modula-2
390 @c passed to the preprocessor if -fcpp is used (internal switch)
392 @item -fdebug-builtins
393 call a real function, rather than the builtin equivalent.  This can
394 be useful for debugging parameter values to a builtin function as
395 it allows users to single step code into an intrinsic function.
397 @c fd
398 @c Modula-2
399 @c turn on internal debugging of the compiler (internal switch)
401 @c fdebug-function-line-numbers
402 @c Modula-2
403 @c turn on the Modula-2 function line number generation (internal switch)
405 @item -fdef=
406 recognize the specified suffix as a definition module filename.
407 The default implementation and module filename suffix is @file{.def}.
408 If this option is used GNU Modula-2 will still fall back to this
409 default if a requested definition module is not found.
411 @item -fdump-system-exports
412 display all inbuilt system items.
413 This is an internal command line option.
415 @item -fexceptions
416 turn on exception handling code.  By default this option is on.
417 Exception handling can be disabled by @samp{-fno-exceptions}
418 and no references are made to the run time exception libraries.
420 @item -fextended-opaque
421 allows opaque types to be implemented as any type.  This is a GNU
422 Modula-2 extension and it requires that the implementation module
423 defining the opaque type is available so that it can be resolved when
424 compiling the module which imports the opaque type.
426 @item -ffloatvalue
427 turns on run time checking to check whether a floating point number is
428 about to exceed range.
430 @item -fgen-module-list=@file{filename}
431 attempt to find all modules when linking and generate a module list.
432 If the @file{filename} is @samp{-} then the contents are not written
433 and only used to force the linking of all module ctors.
434 This option cannot be used if @samp{-fuse-list=} is enabled.
436 @item -findex
437 generate code to check whether array index values are out of bounds.
438 Array index checking can be disabled via @samp{-fno-index}.
440 @item -fiso
441 turn on ISO standard features.  Currently this enables the ISO
442 @code{SYSTEM} module and alters the default library search path so
443 that the ISO libraries are searched before the PIM libraries.  It also
444 effects the behavior of @code{DIV} and @code{MOD} operators.
445 @xref{Dialect}.
447 @item -flibs=
448 modifies the default library search path.  The libraries supplied are:
449 m2pim, m2iso, m2min, m2log and m2cor.  These map onto the
450 Programming in Modula-2 base libraries, ISO standard libraries, minimal
451 library support, Logitech compatible library and Programming in
452 Modula-2 with coroutines.
453 Multiple libraries can be specified and are comma separated with precedence
454 going to the first in the list.  It is not necessary to use -flibs=m2pim or
455 -flibs=m2iso if you also specify -fpim, -fpim2, -fpim3, -fpim4 or
456 -fiso.  Unless you are using -flibs=m2min you should include m2pim as
457 the they provide the base modules which all other dialects utilize.
458 The option @samp{-fno-libs=-} disables the @samp{gm2} driver from
459 modifying the search and library paths.
461 @item -static-libgm2
462 On systems that provide the m2 runtimes as both shared and static libraries,
463 this option forces the use of the static version.
465 @c flocation=
466 @c Modula-2 Joined
467 @c set all location values to a specific value (internal switch)
469 @item -fm2-debug-trace=
470 turn on trace debugging using a comma separated list:
471 @samp{line,token,quad,all}.  This is an internal command line option.
473 @item -fm2-dump=
474 enable dumping of modula-2 internal representation of data structures
475 using a comma separated list.  The list can contain:
476 @samp{quad,gimple,decl,all}.
478 @item -fm2-dump-decl=@file{filestem}
479 dump the modula-2 representation of a symbol to the @file{filestem}
480 specified.  This option only takes effect if the
481 @samp{-fm2-dump-filter} is specified.
483 @item -fm2-dump-gimple=@file{filestem}
484 dump modula-2 gimple representation to the @file{filestem} specified.
486 @item -fm2-dump-quad=@file{filestem}
487 dump quadruple representation to the @file{filestem} specified.
489 @item -fm2-dump-filter=@samp{rules}
490 filter the language dumps @samp{-fdump-lang-decl},
491 @samp{-fdump-lang-gimple} and@samp{-fdump-lang-quad}
492 on @samp{rules}.  @samp{rules} must be a comma
493 separated list which can take three forms: the full decl textual name
494 of a procedure, @samp{[libname.]module.ident} or
495 @samp{[filename:]module.ident}.  This is an internal command line
496 option.  Currently it only filters on procedure names and regexp
497 matching is not implemented.  Three examples of its use following
498 the previous forms could be:
499 @code{-fm2-dump-filter=_M2_hello_init},
500 @code{-fm2-dump-filter=m2pim.StrIO.WriteString} and
501 @code{-fm2-dump-filter=StrLib.mod:StrIO.WriteString}.
503 @item -fm2-g
504 improve the debugging experience for new programmers at the expense
505 of generating @code{nop} instructions if necessary to ensure single
506 stepping precision over all code related keywords.  An example
507 of this is in termination of a list of nested @code{IF} statements
508 where multiple @code{END} keywords are mapped onto a sequence of
509 @code{nop} instructions.
511 @item -fm2-lower-case
512 render keywords in error messages using lower case.
514 @item -fm2-pathname=
515 specify the module mangled prefix name for all modules in the
516 following include paths.
518 @item -fm2-pathnameI
519 for internal use only: used by the driver to copy the user facing @samp{-I}
520 option.
522 @item -fm2-plugin
523 insert plugin to identify run time errors at compile time (default on).
525 @item -fm2-prefix=
526 specify the module mangled prefix name.  All exported symbols from a
527 definition module will have the prefix name.
529 @item -fm2-statistics
530 generates quadruple information: number of quadruples generated,
531 number of quadruples remaining after optimization and number of source
532 lines compiled.
534 @item -fm2-strict-type
535 experimental flag to turn on the new strict type checker.
537 @item -fm2-whole-program
538 compile all implementation modules and program module at once.  Notice
539 that you need to take care if you are compiling different dialect
540 modules (particularly with the negative operands to modulus).  But
541 this option, when coupled together with @code{-O3}, can deliver huge
542 performance improvements.
544 @item -fmod=
545 recognize the specified suffix as implementation and module filenames.
546 The default implementation and module filename suffix is @file{.mod}.
547 If this option is used GNU Modula-2 will still fall back to this
548 default if it needs to read an implementation module and the specified
549 suffixed filename does not exist.
551 @item -fnil
552 generate code to detect accessing data through a @code{NIL} value
553 pointer.  Dereferencing checking through a @code{NIL} pointer can be
554 disabled by @samp{-fno-nil}.
556 @item -fpim
557 turn on PIM standard features.  Currently this enables the PIM
558 @code{SYSTEM} module and determines which identifiers are pervasive
559 (declared in the base module).  If no other @samp{-fpim[234]} switch is
560 used then division and modulus operators behave as defined in PIM4.
561 @xref{Dialect}.
563 @item -fpim2
564 turn on PIM-2 standard features.  Currently this removes @code{SIZE}
565 from being a pervasive identifier (declared in the base module).  It
566 places @code{SIZE} in the @code{SYSTEM} module.  It also effects the
567 behavior of @code{DIV} and @code{MOD} operators.
568 @xref{Dialect}.
570 @item -fpim3
571 turn on PIM-3 standard features.  Currently this only effects the
572 behavior of @code{DIV} and @code{MOD} operators.
573 @xref{Dialect}.
575 @item -fpim4
576 turn on PIM-4 standard features.  Currently this only effects the
577 behavior of @code{DIV} and @code{MOD} operators.
578 @xref{Dialect}.
580 @item -fpositive-mod-floor-div
581 forces the @code{DIV} and @code{MOD} operators to behave as defined by PIM4.
582 All modulus results are positive and the results from the division are
583 rounded to the floor.
584 @xref{Dialect}.
586 @item -fpthread
587 link against the pthread library.  By default this option is on.  It
588 can be disabled by @samp{-fno-pthread}.  GNU Modula-2 uses the GCC
589 pthread libraries to implement coroutines (see the SYSTEM
590 implementation module).
592 @c -fq
593 @c -Modula-2
594 @c -internal compiler debugging information, dump the list of quadruples
596 @item -frange
597 generate code to check the assignment range, return value range
598 set range and constructor range.  Range checking can be disabled
599 via @samp{-fno-range}.
601 @item -freturn
602 generate code to check that functions always exit with a @code{RETURN}
603 and do not fall out at the end.  Return checking can be disabled
604 via @samp{-fno-return}.
606 @item -fruntime-modules=
607 specify, using a comma separated list, the run time modules and their
608 order.  These modules will initialized first before any other modules
609 in the application dependency.  By default the run time modules list
610 is set to @code{m2iso:RTentity,m2iso:Storage,m2iso:SYSTEM,}
611 @code{m2iso:M2RTS,m2iso:RTExceptions,m2iso:IOLink}.  Note that these
612 modules will only be linked into your executable if they are required.
613 Adding a long list of dependent modules will not effect the size of
614 the executable it merely states the initialization order should they
615 be required.
617 @item -fscaffold-dynamic
618 the option ensures that @samp{gm2} will generate a dynamic scaffold
619 infrastructure when compiling implementation and program modules.
620 By default this option is on.  Use @samp{-fno-scaffold-dynamic}
621 to turn it off or select @samp{-fno-scaffold-static}.
623 @item -fscaffold-c
624 generate a C source scaffold for the current module being compiled.
626 @item -fscaffold-c++
627 generate a C++ source scaffold for the current module being compiled.
629 @item -fscaffold-main
630 force the generation of the @samp{main} function.  This is not
631 necessary if the @samp{-c} is omitted.
633 @item -fscaffold-static
634 the option ensures that @samp{gm2} will generate a static scaffold
635 within the program module.  The static scaffold consists of sequences
636 of calls to all dependent module initialization and finalization
637 procedures.  The static scaffold is useful for debugging and single
638 stepping the initialization blocks of implementation modules.
640 @item -fshared
641 generate a shared library from the module.
643 @item -fsoft-check-all
644 turns on all run time checks.  This is the same as invoking
645 GNU Modula-2 using the command options
646 @code{-fnil} @code{-frange} @code{-findex}
647 @code{-fwholevalue}
648 @code{-fwholediv} @code{-fcase} @code{-freturn}.
650 @item -fsources
651 displays the path to the source of each module.  This option
652 can be used at compile time to check the correct definition module
653 is being used.
655 @item -fswig
656 generate a swig interface file.
658 @item -funbounded-by-reference
659 enable optimization of unbounded parameters by attempting to pass non
660 @code{VAR} unbounded parameters by reference.  This optimization
661 avoids the implicit copy inside the callee procedure.  GNU Modula-2
662 will only allow unbounded parameters to be passed by reference if,
663 inside the callee procedure, they are not written to, no address is
664 calculated on the array and it is not passed as a @code{VAR}
665 parameter.  Note that it is possible to write code to break this
666 optimization, therefore this option should be used carefully.
667 For example it would be possible to take the address of an array, pass
668 the address and the array to a procedure, read from the array in
669 the procedure and write to the location using the address parameter.
671 Due to the dangerous nature of this option it is not enabled
672 when the @samp{-O} option is specified.
674 @item -fuse-list=@file{filename}
675 if @samp{-fscaffold-static} is enabled then use the file
676 @file{filename} for the initialization order of modules.  Whereas if
677 @samp{-fscaffold-dynamic} is enabled then use this file to force
678 linking of all module ctors.
679 This option cannot be used if @samp{-fgen-module-list=} is enabled.
681 @item -fwholediv
682 generate code to detect whole number division by zero or modulus by
683 zero.
685 @item -fwholevalue
686 generate code to detect whole number overflow and underflow.
688 @item -Wcase-enum
689 generate a warning if a @code{CASE} statement selects on an enumerated
690 type expression and the statement is missing one or more @code{CASE}
691 labels.  No warning is issued if the @code{CASE} statement has a default
692 @code{ELSE} clause.
693 The option @samp{-Wall} will turn on this flag.
695 @item -Wuninit-variable-checking
696 issue a warning if a variable is used before it is initialized.
697 The checking only occurs in the first basic block in each procedure.
698 It does not check parameters, array types or set types.
700 @item -Wuninit-variable-checking=all,known,cond
701 issue a warning if a variable is used before it is initialized.
702 The checking will only occur in the first basic block in each
703 procedure if @samp{known} is specified.  If @samp{cond} or @samp{all}
704 is specified then checking continues into conditional branches of the
705 flow graph.  All checking will stop when a procedure call is invoked
706 or the top of a loop is encountered.
707 The option @samp{-Wall} will turn on this flag with
708 @samp{-Wuninit-variable-checking=known}.
709 The @samp{-Wuninit-variable-checking=all} will increase compile time.
711 @c the following warning options are complete but need to be
712 @c regression tested against all other front ends
713 @c to ensure the options do not conflict.
715 @c @item -Wall
716 @c turn on all Modula-2 warnings.
718 @c @item -Wpedantic
719 @c forces the compiler to reject nested @code{WITH} statements
720 @c referencing the same record type.  Does not allow multiple imports of
721 @c the same item from a module.  It also checks that: procedure variables
722 @c are written to before being read; variables are not only written to
723 @c but read from; variables are declared and used.  If the compiler
724 @c encounters a variable being read before written it will terminate with
725 @c a message.  It will check that @code{FOR} loop indices are not used
726 @c outside the end of this loop without being reset.
728 @c @item -Wpedantic-cast
729 @c warns if the ISO system function is used and if the size of
730 @c the variable is different from that of the type.  This is legal
731 @c in ISO Modula-2, however it can be dangerous.  Some users may prefer
732 @c to use @code{VAL} instead in these situations and use @code{CAST}
733 @c exclusively for changes in type on objects which have the same size.
735 @c @item -Wpedantic-param-names
736 @c procedure parameter names are checked in the definition module
737 @c against their implementation module counterpart.  This is not
738 @c necessary in ISO or PIM versions of Modula-2.
740 @c @item -Wstyle
741 @c checks for poor programming style.  This option is aimed at new users of
742 @c Modula-2 in that it checks for situations which might cause confusion
743 @c and thus mistakes.  It checks whether variables of the same name are
744 @c declared in different scopes and whether variables look like keywords.
745 @c Experienced users might find this option too aggressive.
747 @c @item -Wunused-variable
748 @c warns if a variable has been declared and it not used.
750 @c @item -Wunused-parameter
751 @c warns if a parameter has been declared and it not used.
753 @c @item -Wverbose-unbounded
754 @c inform the user which non @code{VAR} unbounded parameters will be
755 @c passed by reference.  This only produces output if the option
756 @c @samp{-funbounded-by-reference} is also supplied on the command line.
758 @end table
760 @c man end
762 @node Linking, Elementary data types, Compiler options, Using
764 This section describes the linking related options.  There are three
765 linking strategies available which are dynamic scaffold, static
766 scaffold and user defined.  The dynamic scaffold is enabled by default
767 and each module will register itself to the run time @samp{M2RTS} via
768 a constructor.  The static scaffold mechanism will invoke each modules
769 @samp{_init} and @samp{_finish} function in turn via a sequence of
770 calls from within @samp{main}.  Lastly the user defined strategy
771 can be implemented by turning off the dynamic and static options via
772 @samp{-fno-scaffold-dynamic} and @samp{-fno-scaffold-static}.
774 In the simple test below:
776 @example
777 $ gm2 hello.mod
778 @end example
780 the driver will add the options @samp{-fscaffold-dynamic} and
781 @samp{-fgen-module-list=-} which generate a list of application
782 modules and also creates the @samp{main} function with calls to
783 @samp{M2RTS}.  It can be useful to add the option @samp{-fsources}
784 which displays the source files as they are parsed and summarizes
785 whether the source file is required for compilation or linking.
787 If you wish to split the above command line into a compile and link
788 then you could use these steps:
790 @example
791 $ gm2 -c -fscaffold-main hello.mod
792 $ gm2 hello.o
793 @end example
795 The @samp{-fscaffold-main} informs the compiler to generate the
796 @samp{main} function and scaffold.  You can enable the environment
797 variable @samp{GCC_M2LINK_RTFLAG} to trace the construction and
798 destruction of the application.  The values for
799 @samp{GCC_M2LINK_RTFLAG} are shown in the table below:
801 @example
802 value   | meaning
803 =================
804 all     | turn on all flags below
805 module  | trace modules as they register themselves
806 hex     | display the hex address of the init/fini functions
807 warning | show any warnings
808 pre     | generate module list prior to dependency resolution
809 dep     | trace module dependency resolution
810 post    | generate module list after dependency resolution
811 force   | generate a module list after dependency and forced
812         | ordering is complete
813 @end example
815 The values can be combined using a comma separated list.
817 One of the advantages of the dynamic scaffold is that the driver
818 behaves in a similar way to the other front end drivers.
819 For example consider a small project consisting of 4 definition
820 implementation modules (@samp{a.def}, @samp{a.mod}, @samp{b.def},
821 @samp{b.mod}, @samp{c.def}, @samp{c.mod}, @samp{d.def}, @samp{d.mod})
822 and a program module @samp{program.mod}.
824 To link this project we could:
826 @example
827 $ gm2 -g -c a.mod
828 $ gm2 -g -c b.mod
829 $ gm2 -g -c c.mod
830 $ gm2 -g -c d.mod
831 $ gm2 -g program.mod a.o b.o c.o d.o
832 @end example
834 The module initialization sequence is defined by the ISO standard to
835 follow the import graph traversal.  The initialization order is the
836 order in which the corresponding separate modules finish the
837 processing of their import lists.
839 However, if required, you can override this using
840 @samp{-fruntime-modules=a,b,c,d} for example which forces the
841 initialization sequence to @samp{a}, @samp{b}, @samp{c} and @samp{d}.
843 @node Elementary data types, Standard procedures, Linking, Using
844 @section Elementary data types
846 This section describes the elementary data types supported by GNU
847 Modula-2.  It also describes the relationship between these data types
848 and the equivalent C data types.
850 The following data types are supported: @code{INTEGER},
851 @code{LONGINT}, @code{SHORTINT}, @code{CARDINAL}, @code{LONGCARD},
852 @code{SHORTCARD}, @code{BOOLEAN}, @code{REAL}, @code{LONGREAL},
853 @code{SHORTREAL}, @code{COMPLEX}, @code{LONGCOMPLEX},
854 @code{SHORTCOMPLEX} and @code{CHAR}.
856 An equivalence table is given below:
858 @example
859 GNU Modula-2              GNU C
860 ======================================
861 INTEGER                   int
862 LONGINT                   long long int
863 SHORTINT                  short int
864 CARDINAL                  unsigned int
865 LONGCARD                  long long unsigned int
866 SHORTCARD                 short unsigned int
867 BOOLEAN                   bool
868 REAL                      double
869 LONGREAL                  long double
870 SHORTREAL                 float
871 CHAR                      char
872 SHORTCOMPLEX              complex float
873 COMPLEX                   complex double
874 LONGCOMPLEX               complex long double
875 @end example
877 Note that GNU Modula-2 also supports fixed sized data types which are
878 exported from the @code{SYSTEM} module.
879 @xref{The PIM system module}.
880 @xref{The ISO system module}.
882 @node Standard procedures, High procedure function, Elementary data types, Using
883 @section Permanently accessible base procedures.
885 This section describes the procedures and functions which are
886 always visible.
888 @subsection Standard procedures and functions common to PIM and ISO
890 The following procedures are implemented and conform with Programming
891 in Modula-2 and ISO Modula-2: @code{NEW}, @code{DISPOSE}, @code{INC},
892 @code{DEC}, @code{INCL}, @code{EXCL} and @code{HALT}.  The standard
893 functions are: @code{ABS}, @code{CAP}, @code{CHR}, @code{FLOAT},
894 @code{HIGH}, @code{LFLOAT}, @code{LTRUNC}, @code{MIN}, @code{MAX},
895 @code{ODD}, @code{SFLOAT}, @code{STRUNC} @code{TRUNC} and
896 @code{VAL}.  All these functions and procedures (except @code{HALT},
897 @code{NEW}, @code{DISPOSE} and, under non constant conditions,
898 @code{LENGTH}) generate in-line code for efficiency.
900 @example
903    ABS - returns the positive value of i.
906 @findex ABS
907 PROCEDURE ABS (i: <any signed type>) : <any signed type> ;
909 @end example
911 @example
914    CAP - returns the capital of character ch providing
915          ch lies within the range 'a'..'z'.  Otherwise ch
916          is returned unaltered.
919 @findex CAP
920 PROCEDURE CAP (ch: CHAR) : CHAR ;
922 @end example
924 @example
927    CHR - converts a value of a <whole number type> into a CHAR.
928          CHR(x) is shorthand for VAL(CHAR, x).
931 @findex CHR
932 PROCEDURE CHR (x: <whole number type>) : CHAR ;
934 @end example
936 @example
939    DISPOSE - the procedure DISPOSE is replaced by:
940              DEALLOCATE(p, TSIZE(p^)) ;
941              The user is expected to import the procedure DEALLOCATE
942              (normally found in the module, Storage.)
944              In:  a variable p: of any pointer type which has been
945                   initialized by a call to NEW.
946              Out: the area of memory
947                   holding p^ is returned to the system.
948                   Note that the underlying procedure DEALLOCATE
949                   procedure in module Storage will assign p to NIL.
952 @findex DISPOSE
953 PROCEDURE DISPOSE (VAR p:<any pointer type>) ;
954 @end example
956 @example
959    DEC - can either take one or two parameters.  If supplied
960          with one parameter then on the completion of the call to
961          DEC, v will have its predecessor value.  If two
962          parameters are supplied then the value v will have its
963          n'th predecessor.  For these reasons the value of n
964          must be >=0.
967 @findex DEC
968 PROCEDURE DEC (VAR v: <any base type>; [n: <any base type> = 1]) ;
969 @end example
971 @example
974    EXCL - excludes bit element e from a set type s.
977 @findex EXCL
978 PROCEDURE EXCL (VAR s: <any set type>; e: <element of set type s>) ;
979 @end example
981 @example
984    FLOAT - will return a REAL number whose value is the same as o.
987 @findex FLOAT
988 PROCEDURE FLOAT (o: <any whole number type>) : REAL ;
989 @end example
991 @example
994    FLOATS - will return a SHORTREAL number whose value is the same as o.
997 @findex FLOATS
998 PROCEDURE FLOATS (o: <any whole number type>) : REAL ;
999 @end example
1001 @example
1004    FLOATL - will return a LONGREAL number whose value is the same as o.
1007 @findex FLOATL
1008 PROCEDURE FLOATL (o: <any whole number type>) : REAL ;
1009 @end example
1011 @example
1014    HALT - will call the HALT procedure inside the module M2RTS.
1015           Users can replace M2RTS.
1018 @findex HALT
1019 PROCEDURE HALT ;
1020 @end example
1022 @example
1025    HIGH - returns the last accessible index of an parameter declared as
1026           ARRAY OF CHAR.  Thus
1028           PROCEDURE foo (a: ARRAY OF CHAR) ;
1029           VAR
1030              c: CARDINAL ;
1031           BEGIN
1032              c := HIGH(a)
1033           END foo ;
1035           BEGIN
1036              foo('hello')
1037           END
1039           will cause the local variable c to contain the value 5
1042 @findex HIGH
1043 PROCEDURE HIGH (a: ARRAY OF CHAR) : CARDINAL ;
1044 @end example
1046 @example
1049    INC - can either take one or two parameters.  If supplied
1050          with one parameter then on the completion of the call to
1051          INC, v will have its successor value.  If two
1052          parameters are supplied then the value v will have its
1053          n'th successor.  For these reasons the value of n
1054          must be >=0.
1057 @findex INC
1058 PROCEDURE INC (VAR v: <any base type>; [n: <any base type> = 1]) ;
1059 @end example
1061 @example
1064    INCL - includes bit element e to a set type s.
1067 @findex INCL
1068 PROCEDURE INCL (VAR s: <any set type>; e: <element of set type s>) ;
1069 @end example
1071 @example
1074    LFLOAT - will return a LONGREAL number whose value is the same as o.
1077 @findex LFLOAT
1078 PROCEDURE LFLOAT (o: <any whole number type>) : LONGREAL ;
1079 @end example
1081 @example
1084    LTRUNC - will return a LONG<type> number whose value is the
1085             same as o.  PIM2, PIM3 and ISO Modula-2 will return
1086             a LONGCARD whereas PIM4 returns LONGINT.
1089 @findex LTRUNC
1090 PROCEDURE LTRUNC (o: <any floating point type>) : LONG<type> ;
1091 @end example
1093 @example
1096    MIN - returns the lowest legal value of an ordinal type.
1099 @findex MIN
1100 PROCEDURE MIN (t: <ordinal type>) : <ordinal type> ;
1102 @end example
1104 @example
1107    MAX - returns the largest legal value of an ordinal type.
1110 @findex MAX
1111 PROCEDURE MAX (t: <ordinal type>) : <ordinal type> ;
1113 @end example
1115 @example
1118    NEW - the procedure NEW is replaced by:
1119          ALLOCATE(p, TSIZE(p^)) ;
1120          The user is expected to import the procedure ALLOCATE
1121          (normally found in the module, Storage.)
1123          In:  a variable p: of any pointer type.
1124          Out: variable p is set to some allocated memory
1125               which is large enough to hold all the contents of p^.
1128 @findex NEW
1129 PROCEDURE NEW (VAR p:<any pointer type>) ;
1130 @end example
1132 @example
1135    ODD - returns TRUE if the value is not divisible by 2.
1138 @findex ODD
1139 PROCEDURE ODD (x: <whole number type>) : BOOLEAN ;
1141 @end example
1143 @example
1146    SFLOAT - will return a SHORTREAL number whose value is the same
1147             as o.
1150 @findex SFLOAT
1151 PROCEDURE SFLOAT (o: <any whole number type>) : SHORTREAL ;
1152 @end example
1154 @example
1157    STRUNC - will return a SHORT<type> number whose value is the same
1158             as o.  PIM2, PIM3 and ISO Modula-2 will return a
1159             SHORTCARD whereas PIM4 returns SHORTINT.
1162 @findex STRUNC
1163 PROCEDURE STRUNC (o: <any floating point type>) : SHORT<type> ;
1164 @end example
1166 @example
1169    TRUNC - will return a <type> number whose value is the same as o.
1170            PIM2, PIM3 and ISO Modula-2 will return a CARDINAL
1171            whereas PIM4 returns INTEGER.
1174 @findex TRUNC
1175 PROCEDURE TRUNC (o: <any floating point type>) : <type> ;
1176 @end example
1178 @example
1181    TRUNCS - will return a <type> number whose value is the same
1182             as o.  PIM2, PIM3 and ISO Modula-2 will return a
1183             SHORTCARD whereas PIM4 returns SHORTINT.
1186 @findex TRUNCS
1187 PROCEDURE TRUNCS (o: <any floating point type>) : <type> ;
1188 @end example
1190 @example
1193    TRUNCL - will return a <type> number whose value is the same
1194             as o.  PIM2, PIM3 and ISO Modula-2 will return a
1195             LONGCARD whereas PIM4 returns LONGINT.
1198 @findex TRUNCL
1199 PROCEDURE TRUNCL (o: <any floating point type>) : <type> ;
1200 @end example
1202 @example
1205    VAL - converts data i of <any simple data type 2> to
1206          <any simple data type 1> and returns this value.
1207          No range checking is performed during this conversion.
1210 @findex VAL
1211 PROCEDURE VAL (<any simple data type 1>,
1212                i: <any simple data type 2>) : <any simple data type 1> ;
1214 @end example
1216 @subsection ISO specific standard procedures and functions
1218 The standard function @code{LENGTH} is specific to ISO Modula-2 and
1219 is defined as:
1221 @example
1224    IM - returns the imaginary component of a complex type.
1225         The return value will the same type as the imaginary field
1226         within the complex type.
1229 @findex IM
1230 PROCEDURE IM (c: <any complex type>) : <floating point type> ;
1231 @end example
1233 @example
1236    INT - returns an INTEGER value which has the same value as v.
1237          This function is equivalent to: VAL(INTEGER, v).
1240 @findex INT
1241 PROCEDURE INT (v: <any ordinal type>) : INTEGER ;
1242 @end example
1244 @example
1247    LENGTH - returns the length of string a.
1250 @findex LENGTH
1251 PROCEDURE LENGTH (a: ARRAY OF CHAR) : CARDINAL ;
1252 @end example
1254 This function is evaluated at compile time, providing that string
1255 @code{a} is a constant.  If @code{a} cannot be evaluated then a call is
1256 made to @code{M2RTS.Length}.
1258 @example
1261    ODD - returns a BOOLEAN indicating whether the whole number
1262          value, v, is odd.
1265 @findex ODD
1266 PROCEDURE ODD (v: <any whole number type>) : BOOLEAN ;
1267 @end example
1269 @example
1272    RE - returns the real component of a complex type.
1273         The return value will the same type as the real field
1274         within the complex type.
1277 @findex RE
1278 PROCEDURE RE (c: <any complex type>) : <floating point type> ;
1279 @end example
1281 @node High procedure function, Dialect, Standard procedures, Using
1283 @section Behavior of the high procedure function
1285 This section describes the behavior of the standard procedure function
1286 @code{HIGH} and it includes a table of parameters with the expected
1287 return result.  The standard procedure function will return the last
1288 accessible indice of an @code{ARRAY}.  If the parameter to @code{HIGH}
1289 is a static array then the result will be a @code{CARDINAL} value
1290 matching the upper bound in the @code{ARRAY} declaration.
1292 The section also describes the behavior of a string literal actual
1293 parameter and how it relates to @code{HIGH}.
1294 The PIM2, PIM3, PIM4 and ISO standard is silent on the issue of
1295 whether a @code{nul} is present in an @code{ARRAY} @code{OF}
1296 @code{CHAR} actual parameter.
1298 If the first parameter to @code{HIGH} is an unbounded @code{ARRAY} the
1299 return value from @code{HIGH} will be the last accessible element in
1300 the array.  If a constant string literal is passed as an actual
1301 parameter then it will be @code{nul} terminated.  The table and
1302 example code below describe the effect of passing an actual parameter
1303 and the expected @code{HIGH} value.
1305 @example
1306 MODULE example1 ;
1308 PROCEDURE test (a: ARRAY OF CHAR) ;
1310    x: CARDINAL ;
1311 BEGIN
1312    x := HIGH (a) ;
1313    ...
1314 END test ;
1317 BEGIN
1318    test ('') ;
1319    test ('1') ;
1320    test ('12') ;
1321    test ('123') ;
1322 END example1.
1325 Actual parameter | HIGH (a) | a[HIGH (a)] = nul
1326 ===============================================
1327  ''              | 0        | TRUE
1328  '1'             | 1        | TRUE
1329  '12'            | 2        | TRUE
1330  '123'           | 3        | TRUE
1331 @end example
1333 A constant string literal will be passed to an @code{ARRAY} @code{OF}
1334 @code{CHAR} with an appended @code{nul} @code{CHAR}.  Thus if the
1335 constant string literal @code{''} is passed as an actual parameter (in
1336 example1) then the result from @code{HIGH(a)} will be @code{0}.
1338 @example
1339 MODULE example2 ;
1341 PROCEDURE test (a: ARRAY OF CHAR) ;
1343    x: CARDINAL ;
1344 BEGIN
1345    x := HIGH (a) ;
1346    ...
1347 END test ;
1350    str0: ARRAY [0..0] OF CHAR ;
1351    str1: ARRAY [0..1] OF CHAR ;
1352    str2: ARRAY [0..2] OF CHAR ;
1353    str3: ARRAY [0..3] OF CHAR ;
1354 BEGIN
1355    str0 := 'a' ;   (* No room for the nul terminator.  *)
1356    test (str0) ;
1357    str1 := 'ab' ;  (* No room for the nul terminator.  *)
1358    test (str1) ;
1359    str2 := 'ab' ;  (* Terminated with a nul.  *)
1360    test (str2) ;
1361    str2 := 'abc' ; (* Terminated with a nul.  *)
1362    test (str3) ;
1363 END example2.
1365 Actual parameter | HIGH (a) | a[HIGH (a)] = nul
1366 ===============================================
1367  str0            | 0        | FALSE
1368  str1            | 1        | FALSE
1369  atr2            | 2        | TRUE
1370  str3            | 3        | TRUE
1371 @end example
1373 @node Dialect, Exceptions, High procedure function, Using
1374 @section GNU Modula-2 supported dialects
1376 This section describes the dialects understood by GNU Modula-2.
1377 It also describes the differences between the dialects and
1378 any command line switches which determine dialect behaviour.
1380 The GNU Modula-2 compiler is compliant with four dialects of Modula-2.
1381 The language as defined in 'Programming in Modula-2' 2nd Edition,
1382 Springer Verlag, 1982, 1983 by Niklaus Wirth (PIM2), 'Programming in
1383 Modula-2', 3rd Corrected Edition, Springer Verlag, 1985 (PIM3) and
1384 'Programming in Modula-2', 4th Edition, Springer Verlag, 1988 (PIM4)
1385 @uref{http://freepages.modula2.org/report4/modula-2.html} and the ISO
1386 Modula-2 language as defined in ISO/IEC Information technology -
1387 programming languages - part 1: Modula-2 Language, ISO/IEC 10514-1
1388 (1996) (ISO).
1390 The command line switches @samp{-fpim2}, @samp{-fpim3}, @samp{-fpim4}
1391 and @samp{-fiso} can be used to force mutually exclusive
1392 features.  However by default the compiler will not aggressively fail
1393 if a non mutually exclusive feature is used from another dialect.  For
1394 example it is possible to specify @samp{-fpim2} and still utilize
1395 @samp{DEFINITION} @samp{MODULES} which have no export list.
1397 Some dialect differences will force a compile time error, for example
1398 in PIM2 the user must @code{IMPORT} @code{SIZE} from the module
1399 @code{SYSTEM}, whereas in PIM3 and PIM4 @code{SIZE} is a pervasive
1400 function.  Thus compiling PIM4 source code with the @samp{-fpim2}
1401 switch will cause a compile time error.  This can be fixed quickly
1402 with an additional @code{IMPORT} or alternatively by compiling with
1403 the @samp{-fpim4} switch.
1405 However there are some very important differences between the dialects
1406 which are mutually exclusive and therefore it is vital that users
1407 choose the dialects with care when these language features are used.
1409 @subsection Integer division, remainder and modulus
1411 The most dangerous set of mutually exclusive features found in the
1412 four dialects supported by GNU Modula-2 are the @code{INTEGER}
1413 division, remainder and modulus arithmetic operators.  It is important
1414 to note that the same source code can be compiled to give different
1415 run time results depending upon these switches!  The reference manual
1416 for the various dialects of Modula-2 are quite clear about this
1417 behavior and sadly there are three distinct definitions.
1419 The table below illustrates the problem when a negative operand is
1420 used.
1422 @example
1423                   Pim2/3          Pim4                ISO
1424                -----------    -----------    ----------------------
1425 lval    rval   DIV     MOD    DIV     MOD    DIV    MOD    /    REM
1426  31      10      3       1      3       1      3      1     3     1
1427 -31      10     -3      -1     -4       9     -4      9    -3    -1
1428  31     -10     -3       1     -3       1     Exception    -3     1
1429 -31     -10      3      -1      4       9     Exception     3    -1
1430 @end example
1432 See also P24 of PIM2, P27 of PIM3, P29 of PIM4 and P201 of the ISO
1433 Standard.  At present all dialect division, remainder and modulus are
1434 implemented as above, apart from the exception calling in the ISO
1435 dialect.  Instead of exception handling the results are the same as the
1436 PIM4 dialect.  This is a temporary implementation situation.
1438 @node Exceptions, Semantic checking, Dialect, Using
1439 @section Exception implementation
1441 This section describes how exceptions are implemented in GNU Modula-2
1442 and how command line switches affect their behavior.  The option
1443 @samp{-fsoft-check-all} enables all software checking of nil
1444 dereferences, division by zero etc.  Additional code is produced to
1445 check these conditions and exception handlers are invoked if the
1446 conditions prevail.
1448 Without @samp{-fsoft-check-all} these exceptions will be caught by
1449 hardware (assuming the hardware support exists) and a signal handler
1450 is invoked.  The signal handler will in turn @code{THROW} an exception
1451 which will be caught by the appropriate Modula-2 handler.  However the
1452 action of throwing an exception from within a signal handler is
1453 implementation defined (according to the C++ documentation).  For
1454 example on the x86_64 architecture this works whereas on the i686
1455 architecture it does not.  Therefore to ensure portability it is
1456 recommended to use @samp{-fsoft-check-all}.
1458 @footnote{@samp{-fsoft-check-all} can be effectively combined with
1459 @samp{-O2} to semantically analyze source code for possible run time
1460 errors at compile time.}
1462 @node Semantic checking, Extensions, Exceptions, Using
1463 @section How to detect run time problems at compile time
1465 Consider the following program:
1467 @example
1468 MODULE assignvalue ;  (*!m2iso+gm2*)
1470 PROCEDURE bad () : INTEGER ;
1472    i: INTEGER ;
1473 BEGIN
1474    i := -1 ;
1475    RETURN i
1476 END bad ;
1479    foo: CARDINAL ;
1480 BEGIN
1481    (* The m2rte plugin will detect this as an error, post
1482       optimization.  *)
1483    foo := bad ()
1484 END assignvalue.
1485 @end example
1487 here we see that the programmer has overlooked that the return value
1488 from @samp{bad} will cause an overflow to @samp{foo}.  If we compile
1489 the code with the following options:
1491 @example
1492 $ gm2 -g -fsoft-check-all -O2 -c assignvalue.mod
1493 assignvalue.mod:16:0:inevitable that this error will occur at run time,
1494 assignment will result in an overflow
1495 @end example
1497 The gm2 semantic plugin is automatically run and will generate a
1498 warning message for every exception call which is known as reachable.
1499 It is highly advised to run the optimizer (@samp{-O2} or @samp{-O3})
1500 with @samp{-fsoft-check-all} so that the compiler is able to run the
1501 optimizer and perform variable and flow analysis before the semantic
1502 plugin is invoked.
1504 The @samp{-Wuninit-variable-checking} can be used to identify
1505 uninitialized variables within the first basic block in a procedure.
1506 The checking is limited to variables so long as they are
1507 not an array or set or a variant record or var parameter.
1509 The following example detects whether a sub component within a record
1510 is uninitialized.
1512 @example
1513 MODULE testlarge2 ;
1515 TYPE
1516    color = RECORD
1517               r, g, b: CARDINAL ;
1518            END ;
1520    pixel = RECORD
1521               fg, bg: color ;
1522            END ;
1524 PROCEDURE test ;
1526    p: pixel ;
1527 BEGIN
1528    p.fg.r := 1 ;
1529    p.fg.g := 2 ;
1530    p.fg.g := 3 ;   (* Deliberate typo should be p.fg.b.  *)
1531    p.bg := p.fg ;  (* Accessing an uninitialized field.  *)
1532 END test ;
1534 BEGIN
1535    test
1536 END testlarge2.
1537 @end example
1539 @example
1540 $ gm2 -c -Wuninit-variable-checking testlarge2.mod
1541 testlarge2.mod:19:13: warning: In procedure â€˜test’: attempting to
1542 access expression before it has been initialized
1543    19 |    p.bg := p.fg ;  (* Accessing an uninitialized field.  *)
1544       |            ~^~~
1545 @end example
1547 The following example detects if an individual field is uninitialized.
1549 @example
1550 MODULE testwithnoptr ;
1552 TYPE
1553    Vec =  RECORD
1554              x, y: CARDINAL ;
1555           END ;
1557 PROCEDURE test ;
1559    p: Vec ;
1560 BEGIN
1561    WITH p DO
1562       x := 1 ;
1563       x := 2   (* Deliberate typo, user meant y.  *)
1564    END ;
1565    IF p.y = 2
1566    THEN
1567    END
1568 END test ;
1570 BEGIN
1571    test
1572 END testwithnoptr.
1573 @end example
1575 The following example detects a record is uninitialized via a
1576 pointer variable in a @samp{WITH} block.
1578 @example
1579 $ gm2 -g -c -Wuninit-variable-checking testwithnoptr.mod
1580 testwithnoptr.mod:21:8: warning: In procedure â€˜test’: attempting to
1581 access expression before it has been initialized
1582    21 |    IF p.y = 2
1583       |       ~^~
1584 @end example
1586 @example
1587 MODULE testnew6 ;
1589 FROM Storage IMPORT ALLOCATE ;
1591 TYPE
1592    PtrToVec = POINTER TO RECORD
1593                             x, y: INTEGER ;
1594                          END ;
1596 PROCEDURE test ;
1598    p: PtrToVec ;
1599 BEGIN
1600    NEW (p) ;
1601    WITH p^ DO
1602       x := 1 ;
1603       x := 2   (* Deliberate typo, user meant y.  *)
1604    END ;
1605    IF p^.y = 2
1606    THEN
1607    END
1608 END test ;
1611 BEGIN
1612    test
1613 END testnew6.
1614 @end example
1616 @example
1617 $ gm2 -g -c -Wuninit-variable-checking testnew6.mod
1618 testnew6.mod:19:9: warning: In procedure â€˜test’: attempting to
1619 access expression before it has been initialized
1620    19 |    IF p^.y = 2
1621       |       ~~^~
1622 @end example
1624 @node Extensions, Type compatibility, Semantic checking, Using
1625 @section GNU Modula-2 language extensions
1627 This section introduces the GNU Modula-2 language extensions.
1628 The GNU Modula-2 compiler allows abstract data types to be any type,
1629 not just restricted to a pointer type providing the
1630 @samp{-fextended-opaque} option is supplied
1631 @xref{Compiler options}.
1633 Declarations can be made in any order, whether they are
1634 types, constants, procedures, nested modules or variables.
1635 @c (@xref{Passes, , ,}.)
1637 GNU Modula-2 also allows programmers to interface to @code{C} and
1638 assembly language.
1640 GNU Modula-2 provides support for the special tokens @code{__LINE__},
1641 @code{__FILE__}, @code{__FUNCTION__} and @code{__DATE__}.  Support for
1642 these tokens will occur even if the @samp{-fcpp} option is not
1643 supplied.  A table of these identifiers and their data type and values
1644 is given below:
1646 @example
1647 Scope       GNU Modula-2 token      Data type and example value
1649 anywhere    __LINE__                Constant Literal compatible
1650                                     with CARDINAL, INTEGER and WORD.
1651                                     Example 1234
1653 anywhere    __FILE__                Constant string compatible
1654                                     with parameter ARRAY OF CHAR or
1655                                     an ARRAY whose SIZE is >= string
1656                                     length.  Example
1657                                     "hello.mod"
1659 procedure   __FUNCTION__            Constant string compatible
1660                                     with parameter ARRAY OF CHAR or
1661                                     an ARRAY whose SIZE is >= string
1662                                     length.  Example
1663                                     "calc"
1665 module      __FUNCTION__            Example
1666                                     "module hello initialization"
1668 anywhere    __DATE__                Constant string compatible
1669                                     with parameter ARRAY OF CHAR or
1670                                     an ARRAY whose SIZE is >= string
1671                                     length.  Example
1672                                     "Thu Apr 29 10:07:16 BST 2004"
1674 anywhere   __COLUMN__               Gives a constant literal number
1675                                     determining the left hand column
1676                                     where the first _ appears in
1677                                     __COLUMN__.  The left most column
1678                                     is 1.
1680 @end example
1682 The preprocessor @samp{cpp} can be invoked via the @samp{-fcpp}
1683 command line option.  This in turn invokes @samp{cpp} with the
1684 following arguments @samp{-traditional -lang-asm}.  These options
1685 preserve comments and all quotations.  @samp{gm2} treats a @samp{#}
1686 character in the first column as a preprocessor directive unless
1687 @samp{-fno-cpp} is supplied.
1689 For example here is a module which calls @code{FatalError}
1690 via the macro @code{ERROR}.
1692 @example
1693 MODULE cpp ;
1695 FROM SYSTEM IMPORT ADR, SIZE ;
1696 FROM libc IMPORT exit, printf, malloc ;
1698 PROCEDURE FatalError (a, file: ARRAY OF CHAR;
1699                          line: CARDINAL;
1700                          func: ARRAY OF CHAR) ;
1701 BEGIN
1702    printf ("%s:%d:fatal error, %s, in %s\n",
1703             ADR (file), line, ADR (a), ADR (func)) ;
1704    exit (1)
1705 END FatalError ;
1707 #define ERROR(X)  FatalError(X, __FILE__, __LINE__, __FUNCTION__)
1710    pc: POINTER TO CARDINAL;
1711 BEGIN
1712    pc := malloc (SIZE (CARDINAL)) ;
1713    IF pc = NIL
1714    THEN
1715       ERROR ('out of memory')
1716    END
1717 END cpp.
1718 @end example
1720 Another use for the C preprocessor in Modula-2 might be to turn on
1721 debugging code.  For example the library module
1722 @file{FormatStrings.mod} uses procedures from @file{DynamicStrings.mod}
1723 and to track down memory leaks it was useful to track the source file
1724 and line where each string was created.  Here is a section of
1725 @file{FormatStrings.mod} which shows how the debugging code was
1726 enabled and disabled by adding @code{-fcpp} to the command line.
1728 @example
1729 FROM DynamicStrings IMPORT String, InitString, InitStringChar, Mark,
1730                            ConCat, Slice, Index, char,
1731                            Assign, Length, Mult, Dup, ConCatChar,
1732                            PushAllocation, PopAllocationExemption,
1733                            InitStringDB, InitStringCharStarDB,
1734                            InitStringCharDB, MultDB, DupDB, SliceDB ;
1737 #define InitString(X) InitStringDB(X, __FILE__, __LINE__)
1738 #define InitStringCharStar(X) InitStringCharStarDB(X, __FILE__, \
1739                                                    __LINE__)
1740 #define InitStringChar(X) InitStringCharDB(X, __FILE__, __LINE__)
1741 #define Mult(X,Y) MultDB(X, Y, __FILE__, __LINE__)
1742 #define Dup(X) DupDB(X, __FILE__, __LINE__)
1743 #define Slice(X,Y,Z) SliceDB(X, Y, Z, __FILE__, __LINE__)
1746 PROCEDURE doDSdbEnter ;
1747 BEGIN
1748    PushAllocation
1749 END doDSdbEnter ;
1751 PROCEDURE doDSdbExit (s: String) ;
1752 BEGIN
1753    s := PopAllocationExemption (TRUE, s)
1754 END doDSdbExit ;
1756 PROCEDURE DSdbEnter ;
1757 BEGIN
1758 END DSdbEnter ;
1760 PROCEDURE DSdbExit (s: String) ;
1761 BEGIN
1762 END DSdbExit ;
1765 #define DBsbEnter doDBsbEnter
1766 #define DBsbExit  doDBsbExit
1769 PROCEDURE Sprintf1 (s: String; w: ARRAY OF BYTE) : String ;
1770 BEGIN
1771    DSdbEnter ;
1772    s := FormatString (HandleEscape (s), w) ;
1773    DSdbExit (s) ;
1774    RETURN s
1775 END Sprintf1 ;
1776 @end example
1778 It is worth noting that the overhead of this code once @code{-fcpp} is
1779 not present and -O2 is used will be zero since the local empty
1780 procedures @code{DSdbEnter} and @code{DSdbExit} will be thrown away by
1781 the optimization passes of the GCC backend.
1783 @subsection Optional procedure parameter
1785 GNU Modula-2 allows the last parameter to a procedure or function
1786 parameter to be optional.  For example in the ISO library
1787 @file{COROUTINES.def} the procedure @code{NEWCOROUTINE} is defined as
1788 having an optional fifth argument (@code{initProtection}) which, if
1789 absent, is automatically replaced by @code{NIL}.
1791 @example
1792 @findex NEWCOROUTINE
1793 PROCEDURE NEWCOROUTINE (procBody: PROC; workspace: SYSTEM.ADDRESS;
1794                         size: CARDINAL; VAR cr: COROUTINE;
1795                         [initProtection: PROTECTION = NIL]);
1797   (* Creates a new coroutine whose body is given by procBody,
1798      and returns the identity of the coroutine in cr.
1799      workspace is a pointer to the work space allocated to
1800      the coroutine; size specifies the size of this workspace
1801      in terms of SYSTEM.LOC.
1803      The optional fifth argument may contain a single parameter
1804      which specifies the initial protection level of the coroutine.
1805   *)
1806 @end example
1808 The implementation module @file{COROUTINES.mod} implements this
1809 procedure using the following syntax:
1811 @example
1812 PROCEDURE NEWCOROUTINE (procBody: PROC; workspace: SYSTEM.ADDRESS;
1813                         size: CARDINAL; VAR cr: COROUTINE;
1814                         [initProtection: PROTECTION]);
1815 BEGIN
1817 END NEWCOROUTINE ;
1818 @end example
1820 Note that it is illegal for this declaration to contain an initializer
1821 value for @code{initProtection}.  However it is necessary to surround
1822 this parameter with the brackets @code{[} and @code{]}.  This serves to
1823 remind the programmer that the last parameter was declared as optional
1824 in the definition module.
1826 Local procedures can be declared to have an optional final parameter
1827 in which case the initializer is mandatory in the implementation or
1828 program module.
1830 GNU Modula-2 also provides additional fixed sized data types which
1831 are all exported from the @code{SYSTEM} module.
1832 @xref{The PIM system module}.
1833 @xref{The ISO system module}.
1835 @node Type compatibility, Unbounded by reference, Extensions, Using
1836 @section Type compatibility
1838 This section discuss the issues surrounding assignment, expression
1839 and parameter compatibility, their effect of the additional
1840 fixed sized datatypes and also their effect of run time checking.
1841 The data types supported by the compiler are:
1843 @example
1844 GNU Modula-2              scope      switches
1845 =============================================
1846 INTEGER                   pervasive
1847 LONGINT                   pervasive
1848 SHORTINT                  pervasive
1849 CARDINAL                  pervasive
1850 LONGCARD                  pervasive
1851 SHORTCARD                 pervasive
1852 BOOLEAN                   pervasive
1853 BITSET                    pervasive
1854 REAL                      pervasive
1855 LONGREAL                  pervasive
1856 SHORTREAL                 pervasive
1857 CHAR                      pervasive
1858 SHORTCOMPLEX              pervasive
1859 COMPLEX                   pervasive
1860 LONGCOMPLEX               pervasive
1862 LOC                       SYSTEM     -fiso
1863 BYTE                      SYSTEM
1864 WORD                      SYSTEM
1865 ADDRESS                   SYSTEM
1867 The following extensions are supported for
1868 most architectures (please check SYSTEM.def).
1869 =============================================
1870 INTEGER8                  SYSTEM
1871 INTEGER16                 SYSTEM
1872 INTEGER32                 SYSTEM
1873 INTEGER64                 SYSTEM
1874 CARDINAL8                 SYSTEM
1875 CARDINAL16                SYSTEM
1876 CARDINAL32                SYSTEM
1877 CARDINAL64                SYSTEM
1878 BITSET8                   SYSTEM
1879 BITSET16                  SYSTEM
1880 BITSET32                  SYSTEM
1881 WORD16                    SYSTEM
1882 WORD32                    SYSTEM
1883 WORD64                    SYSTEM
1884 REAL32                    SYSTEM
1885 REAL64                    SYSTEM
1886 REAL96                    SYSTEM
1887 REAL128                   SYSTEM
1888 COMPLEX32                 SYSTEM
1889 COMPLEX64                 SYSTEM
1890 COMPLEX96                 SYSTEM
1891 COMPLEX128                SYSTEM
1892 @end example
1894 The Modula-2 language categorizes compatibility between entities of
1895 possibly differing types into three sub components: expressions,
1896 assignments, and parameters.  Parameter compatibility is further
1897 divided into two sections for pass by reference and pass by value
1898 compatibility.
1900 For more detail on the Modula-2 type compatibility see the Modula-2
1901 ISO standard BS ISO/IEC 10514-1:1996 page 121-125.  For detail on the
1902 PIM type compatibility see Programming in Modula-2 Edition 4 page 29,
1903 (Elementary Data Types).
1905 @subsection Expression compatibility
1907 Modula-2 restricts the types of expressions to the same type.
1908 Expression compatibility is a symmetric relation.
1910 For example two sub expressions of @code{INTEGER} and @code{CARDINAL}
1911 are not expression compatible
1912 (@uref{http://freepages.modula2.org/report4/modula-2.html} and ISO
1913 Modula-2).
1915 In GNU Modula-2 this rule is also extended across all fixed sized data
1916 types (imported from SYSTEM).
1918 @subsection Assignment compatibility
1920 This section discusses the assignment issues surrounding assignment
1921 compatibility of elementary types (@code{INTEGER}, @code{CARDINAL},
1922 @code{REAL} and @code{CHAR} for example).  The information here is
1923 found in more detail in the Modula-2 ISO standard BS ISO/IEC
1924 10514-1:1996 page 122.
1926 Assignment compatibility exists between the same sized elementary
1927 types.
1929 Same type family of different sizes are
1930 also compatible as long as the @code{MAX(}type@code{)} and
1931 @code{MIN(}type@code{)} is known.  So for example this includes the
1932 @code{INTEGER} family, @code{CARDINAL} family and the @code{REAL}
1933 family.
1935 The reason for this is that when the assignment is performed
1936 the compiler will check to see that the expression (on the right of
1937 the @code{:=}) lies within the range of the designator type (on the
1938 left hand side of the @code{:=}).  Thus these ordinal types can be
1939 assignment compatible.  However it does mean that @code{WORD32} is not
1940 compatible with @code{WORD16} as @code{WORD32} does not have a minimum
1941 or maximum value and therefore cannot be checked.  The compiler does
1942 not know which of the two bytes from @code{WORD32} should be copied
1943 into @code{WORD16} and which two should be ignored.  Currently the
1944 types @code{BITSET8}, @code{BITSET16} and @code{BITSET32} are
1945 assignment incompatible.  However this restriction maybe lifted when
1946 further run time checking is achieved.
1948 Modula-2 does allow @code{INTEGER} to be assignment compatible with
1949 @code{WORD} as they are the same size.  Likewise GNU Modula-2 allows
1950 @code{INTEGER16} to be compatible with @code{WORD16} and the same for
1951 the other fixed sized types and their sized equivalent in either
1952 @code{WORD}n, @code{BYTE} or @code{LOC} types.  However it prohibits
1953 assignment between @code{WORD} and @code{WORD32} even though on many
1954 systems these sizes will be the same.  The reasoning behind this rule
1955 is that the extended fixed sized types are meant to be used by
1956 applications requiring fixed sized data types and it is more portable
1957 to forbid the blurring of the boundaries between fixed sized and
1958 machine dependent sized types.
1960 Intermediate code run time checking is always generated by the front
1961 end.  However this intermediate code is only translated into actual
1962 code if the appropriate command line switches are specified.  This
1963 allows the compiler to perform limited range checking at compile time.
1964 In the future it will allow the extensive GCC optimizations to
1965 propagate constant values through to the range checks which if they
1966 are found to exceed the type range will result in a compile time
1967 error message.
1969 @subsection Parameter compatibility
1971 Parameter compatibility is divided into two areas, pass by value and
1972 pass by reference (@code{VAR}).  In the case of pass by value the
1973 rules are exactly the same as assignment.  However in the second case,
1974 pass by reference, the actual parameter and formal parameter must be
1975 the same size and family.  Furthermore @code{INTEGER} and
1976 @code{CARDINAL}s are not treated as compatible in the pass by
1977 reference case.
1979 The types @code{BYTE}, @code{LOC}, @code{WORD} and @code{WORD}n
1980 derivatives are assignment and parameter compatible with any data type
1981 of the same size.
1983 @node Unbounded by reference, Building a shared library, Type compatibility, Using
1984 @section Unbounded by reference
1986 This section documents a GNU Modula-2 compiler switch which implements
1987 a language optimization surrounding the implementation of unbounded
1988 arrays.  In GNU Modula-2 the unbounded array is implemented by
1989 utilizing an internal structure @code{struct @{dataType *address,
1990 unsigned int high@}}.  So given the Modula-2 procedure declaration:
1992 @example
1993 PROCEDURE foo (VAR a: ARRAY OF dataType) ;
1994 BEGIN
1995    IF a[2]= (* etc *)
1996 END foo ;
1997 @end example
1999 it is translated into GCC @code{tree}s, which can be represented
2000 in their C form thus:
2002 @example
2003 void foo (struct @{dataType *address, unsigned int high@} a)
2005    if (a.address[2] == /* etc */
2007 @end example
2009 Whereas if the procedure @code{foo} was declared as:
2011 @example
2012 PROCEDURE foo (a: ARRAY OF dataType) ;
2013 BEGIN
2014    IF a[2]= (* etc *)
2015 END foo ;
2016 @end example
2018 then it is implemented by being translated into the following
2019 GCC @code{tree}s, which can be represented in their C form thus:
2021 @example
2022 void foo (struct @{dataType *address, unsigned int high@} a)
2024    dataType *copyContents = (dataType *)alloca (a.high+1);
2025    memcpy(copyContents, a.address, a.high+1);
2026    a.address = copyContents;
2028    if (a.address[2] == /* etc */
2030 @end example
2032 This implementation works, but it makes a copy of each non VAR
2033 unbounded array when a procedure is entered.  If the unbounded array
2034 is not changed during procedure @code{foo} then this implementation
2035 will be very inefficient.  In effect Modula-2 lacks the @code{REF}
2036 keyword of Ada.  Consequently the programmer maybe tempted to
2037 sacrifice semantic clarity for greater efficiency by declaring the
2038 parameter using the @code{VAR} keyword in place of @code{REF}.
2040 The @code{-funbounded-by-reference} switch instructs the compiler to
2041 check and see if the programmer is modifying the content of any
2042 unbounded array.  If it is modified then a copy will be made upon
2043 entry into the procedure.  Conversely if the content is only read and
2044 never modified then this non @code{VAR} unbounded array is a candidate
2045 for being passed by reference.  It is only a candidate as it is still
2046 possible that passing this parameter by reference could alter the
2047 meaning of the source code.  For example consider the following case:
2049 @example
2050 PROCEDURE StrConCat (VAR a: ARRAY OF CHAR; b, c: ARRAY OF CHAR) ;
2051 BEGIN
2052    (* code which performs string a := b + c *)
2053 END StrConCat ;
2055 PROCEDURE foo ;
2057    a: ARRAY [0..3] OF CHAR ;
2058 BEGIN
2059    a := 'q' ;
2060    StrConCat(a, a, a)
2061 END foo ;
2062 @end example
2064 In the code above we see that the same parameter, @code{a}, is being
2065 passed three times to @code{StrConCat}.  Clearly even though parameters
2066 @code{b} and @code{c} are never modified it would be incorrect to
2067 implement them as pass by reference.  Therefore the compiler checks to
2068 see if any non @code{VAR} parameter is type compatible with any
2069 @code{VAR} parameter and if so it generates run time procedure entry
2070 checks to determine whether the contents of parameters @code{b} or
2071 @code{c} matches the contents of @code{a}.  If a match is detected
2072 then a copy is made and the @code{address} in the unbounded
2073 @code{struct}ure is modified.
2075 The compiler will check the address range of each candidate against
2076 the address range of any @code{VAR} parameter, providing they are type
2077 compatible.  For example consider:
2079 @example
2080 PROCEDURE foo (a: ARRAY OF BYTE; VAR f: REAL) ;
2081 BEGIN
2082    f := 3.14 ;
2083    IF a[0]=BYTE(0)
2084    THEN
2085       (* etc *)
2086    END
2087 END foo ;
2089 PROCEDURE bar ;
2090 BEGIN
2091    r := 2.0 ;
2092    foo(r, r)
2093 END bar ;
2094 @end example
2096 Here we see that although parameter, @code{a}, is a candidate for the
2097 passing by reference, it would be incorrect to use this
2098 transformation.  Thus the compiler detects that parameters, @code{a}
2099 and @code{f} are type compatible and will produce run time checking
2100 code to test whether the address range of their respective contents
2101 intersect.
2103 @node Building a shared library, Interface for Python, Unbounded by reference, Using
2104 @section Building a shared library
2106 This section describes building a tiny shared library implemented in
2107 Modula-2 and built with @file{libtool}.  Suppose a project consists of
2108 two definition modules and two implementation modules and a program
2109 module @file{a.def}, @file{a.mod}, @file{b.def}, @file{b.mod} and
2110 @file{c.mod}.  The first step is to compile the modules using position
2111 independent code.  This can be achieved by the following three
2112 commands:
2114 @example
2115 libtool --tag=CC --mode=compile gm2 -g -c a.mod -o a.lo
2116 libtool --tag=CC --mode=compile gm2 -g -c b.mod -o b.lo
2117 libtool --tag=CC --mode=compile gm2 -g -c c.mod -o c.lo
2118 @end example
2120 The second step is to generate the shared library initialization and
2121 finalization routines.  We can do this by asking gm2 to generate a
2122 list of dependent modules and then use this to generate the scaffold.
2123 We also must compile the scaffold.
2125 @example
2126 gm2 -c -g -fmakelist c.mod
2127 gm2 -c -g -fmakeinit -fshared c.mod
2128 libtool --tag=CC --mode=compile g++ -g -c c_m2.cpp -o c_m2.lo
2129 @end example
2131 The third step is to link all these @file{.lo} files.
2133 @example
2134 libtool --mode=link gcc -g c_m2.lo a.lo b.lo c.lo \
2135         -L$(prefix)/lib64 \
2136         -rpath `pwd` -lgm2 -lstdc++ -lm -o libabc.la
2137 @end example
2139 At this point the shared library @file{libabc.so} will have been
2140 created inside the directory @file{.libs}.
2142 @node Interface for Python, Producing a Python module, Building a shared library, Using
2143 @section How to produce swig interface files
2145 This section describes how Modula-2 implementation modules can be
2146 called from Python (and other scripting languages such as TCL and
2147 Perl).  GNU Modula-2 can be instructed to create a swig interface when
2148 it is compiling an implementation module.  Swig then uses the
2149 interface file to generate all the necessary wrapping to that the
2150 desired scripting language may access the implementation module.
2152 Here is an example of how you might call upon the services of the
2153 Modula-2 library module @code{NumberIO} from Python3.
2155 The following commands can be used to generate the Python3 module:
2157 @example
2158 export src=@samp{directory to the sources}
2159 export prefix=@samp{directory to where the compiler is installed}
2160 gm2 -I$@{src@} -c -g -fswig $@{src@}/../../../gm2-libs/NumberIO.mod
2161 gm2 -I$@{src@} -c -g -fmakelist $@{src@}/../../../gm2-libs/NumberIO.mod
2163 gm2 -I$@{src@} -c -g -fmakeinit -fshared \
2164    $@{src@}/../../../gm2-libs/NumberIO.mod
2166 swig -c++ -python3 NumberIO.i
2168 libtool --mode=compile g++ -g -c -I$@{src@} NumberIO_m2.cpp \
2169   -o NumberIO_m2.lo
2171 libtool --tag=CC --mode=compile gm2 -g -c \
2172   -I$@{src@}../../../gm2-libs \
2173   $@{src@}/../../../gm2-libs/NumberIO.mod -o NumberIO.lo
2175 libtool --tag=CC --mode=compile g++ -g -c NumberIO_wrap.cxx \
2176   -I/usr/include/python3 -o NumberIO_wrap.lo
2178 libtool --mode=link gcc -g NumberIO_m2.lo NumberIO_wrap.lo \
2179    -L$@{prefix@}/lib64 \
2180    -rpath `pwd` -lgm2 -lstdc++ -lm -o libNumberIO.la
2182 cp .libs/libNumberIO.so _NumberIO.so
2183 @end example
2185 The first four commands, generate the swig interface file
2186 @file{NumberIO.i} and python wrap files @file{NumberIO_wrap.cxx} and
2187 @file{NumberIO.py}.  The next three @file{libtool} commnads compile
2188 the C++ and Modula-2 source code into @file{.lo} objects.  The last
2189 @file{libtool} command links all the @file{.lo} files into a
2190 @file{.la} file and includes all shared library dependencies.
2192 Now it is possible to run the following Python script
2193 (called @file{testnum.py}):
2195 @example
2196 import NumberIO
2198 print ("1234 x 2 =", NumberIO.NumberIO_StrToInt("1234")*2)
2199 @end example
2201 like this:
2203 @example
2204 $ python3 testnum.py
2205 1234 x 2 = 2468
2206 @end example
2208 @xref{Producing a Python module} for another example which
2209 uses the @code{UNQUALIFIED} keyword to reduce the module name clutter
2210 from the viewport of Python3.
2212 @subsection Limitations of automatic generated of Swig files
2214 This section discusses the limitations of automatically generating
2215 swig files.  From the previous example we see that the module
2216 @code{NumberIO} had a swig interface file @file{NumberIO.i}
2217 automatically generated by the compiler.  If we consider three of the
2218 procedure definitions in @file{NumberIO.def} we can see the
2219 success and limitations of the automatic interface generation.
2221 @example
2222 PROCEDURE StrToHex (a: ARRAY OF CHAR; VAR x: CARDINAL) ;
2223 PROCEDURE StrToInt (a: ARRAY OF CHAR; VAR x: INTEGER) ;
2224 PROCEDURE ReadInt (VAR x: CARDINAL) ;
2225 @end example
2227 Below are the swig interface prototypes:
2229 @example
2230 extern void NumberIO_StrToHex (char *_m2_address_a,
2231                                int _m2_high_a, unsigned int *OUTPUT);
2232 /*  parameters: x is known to be an OUTPUT */
2233 extern void NumberIO_StrToInt (char *_m2_address_a,
2234                                int _m2_high_a, int *OUTPUT);
2235 /*  parameters: x is guessed to be an OUTPUT */
2236 extern void NumberIO_ReadInt (int *x);
2237 /*  parameters: x is unknown */
2238 @end example
2240 In the case of @code{StrToHex} it can be seen that the compiler
2241 detects that the last parameter is an output.  It explicitly tells
2242 swig this by using the parameter name @code{OUTPUT} and in the
2243 following comment it informs the user that it knows this to be an
2244 output parameter.  In the second procedure @code{StrToInt} it marks
2245 the final parameter as an output, but it tells the user that this is
2246 only a guess.  Finally in @code{ReadInt} it informs the user that
2247 it does not know whether the parameter, @code{x}, is an output, input
2248 or an inout parameter.
2250 The compiler decides whether to mark a parameter as either:
2251 @code{INPUT}, @code{OUTPUT} or @code{INOUT} if it is read before
2252 written or visa versa in the first basic block.  At this point
2253 it will write output that the parameter is known.  If it is not
2254 read or written in the first basic block then subsequent basic blocks
2255 are searched and the result is commented as a guess.  Finally if
2256 no read or write occurs then the parameter is commented as unknown.
2257 However, clearly it is possible to fool this mechanism.  Nevertheless
2258 automatic generation of implementation module into swig interface files
2259 was thought sufficiently useful despite these limitations.
2261 In conclusion it would be wise to check all parameters in any
2262 automatically generated swig interface file.  Furthermore you can
2263 force the automatic mechanism to generate correct interface files by
2264 reading or writing to the @code{VAR} parameter in the first basic
2265 block of a procedure.
2267 @node Producing a Python module, Interface to C, Interface for Python, Using
2268 @section How to produce a Python module
2270 This section describes how it is possible to produce a Python module
2271 from Modula-2 code.  There are a number of advantages to this
2272 approach, it ensures your code reaches a wider audience, maybe it is
2273 easier to initialize your application in Python.
2275 The example application here is a pedagogical two dimensional gravity
2276 next event simulation.  The Python module needs to have a clear API
2277 which should be placed in a single definition module.  Furthermore the
2278 API should only use fundamental pervasive data types and strings.
2279 Below the API is contained in the file @file{twoDsim.def}:
2281 @example
2282 DEFINITION MODULE twoDsim ;
2284 EXPORT UNQUALIFIED gravity, box, poly3, poly5, poly6, mass,
2285                    fix, circle, pivot, velocity, accel, fps,
2286                    replayRate, simulateFor ;
2288    gravity - turn on gravity at: g m^2
2291 PROCEDURE gravity (g: REAL) ;
2295    box - place a box in the world at (x0,y0),(x0+i,y0+j)
2298 PROCEDURE box (x0, y0, i, j: REAL) : CARDINAL ;
2302    poly3 - place a triangle in the world at:
2303            (x0,y0),(x1,y1),(x2,y2)
2306 PROCEDURE poly3 (x0, y0, x1, y1, x2, y2: REAL) : CARDINAL ;
2310    poly5 - place a pentagon in the world at:
2311            (x0,y0),(x1,y1),(x2,y2),(x3,y3),(x4,y4)
2314 PROCEDURE poly5 (x0, y0, x1, y1,
2315                  x2, y2, x3, y3, x4, y4: REAL) : CARDINAL ;
2319    poly6 - place a hexagon in the world at:
2320            (x0,y0),(x1,y1),(x2,y2),(x3,y3),(x4,y4),(x5,y5)
2323 PROCEDURE poly6 (x0, y0, x1, y1,
2324                  x2, y2, x3, y3,
2325                  x4, y4, x5, y5: REAL) : CARDINAL ;
2329    mass - specify the mass of an object and return the, id.
2332 PROCEDURE mass (id: CARDINAL; m: REAL) : CARDINAL ;
2336    fix - fix the object to the world.
2339 PROCEDURE fix (id: CARDINAL) : CARDINAL ;
2343    circle - adds a circle to the world.  Center
2344             defined by: x0, y0 radius, r.
2347 PROCEDURE circle (x0, y0, r: REAL) : CARDINAL ;
2351    velocity - give an object, id, a velocity, vx, vy.
2354 PROCEDURE velocity (id: CARDINAL; vx, vy: REAL) : CARDINAL ;
2358    accel - give an object, id, an acceleration, ax, ay.
2361 PROCEDURE accel (id: CARDINAL; ax, ay: REAL) : CARDINAL ;
2365    fps - set frames per second.
2368 PROCEDURE fps (f: REAL) ;
2372    replayRate - set frames per second during replay.
2375 PROCEDURE replayRate (f: REAL) ;
2379    simulateFor - render for, t, seconds.
2382 PROCEDURE simulateFor (t: REAL) ;
2385 END twoDsim.
2386 @end example
2388 The keyword @code{UNQUALIFIED} can be used to ensure that the
2389 compiler will provide externally accessible functions
2390 @code{gravity}, @code{box}, @code{poly3}, @code{poly5}, @code{poly6},
2391 @code{mass}, @code{fix}, @code{circle}, @code{pivot}, @code{velocity},
2392 @code{accel}, @code{fps}, @code{replayRate}, @code{simulateFor}
2393 rather than name mangled alternatives.
2394 Hence in our Python3 application we could write:
2396 @example
2397 #!/usr/bin/env python3
2399 from twoDsim import *
2401 b = box (0.0, 0.0, 1.0, 1.0)
2402 b = fix (b)
2403 c1 = circle (0.7, 0.7, 0.05)
2404 c1 = mass (c1, 0.01)
2405 c2 = circle (0.7, 0.1, 0.05)
2406 c2 = mass (c2, 0.01)
2407 c2 = fix (c2)
2408 gravity (-9.81)
2409 fps (24.0*4.0)
2410 replayRate (24.0)
2411 print ("creating frames")
2412 try:
2413     simulateFor (1.0)
2414     print ("all done")
2415 except:
2416     print ("exception raised")
2417 @end example
2419 which accesses the various functions defined and implemented by the
2420 module @code{twoDsim}.  The Modula-2 source code is compiled via:
2422 @example
2423 $ gm2 -g -fiso -c -fswig twoDsim.mod
2424 $ gm2 -g -fiso -c -fmakelist twoDsim.mod
2425 $ gm2 -g -fiso -c -fmakeinit twoDsim.mod
2426 @end example
2428 The first command both compiles the source file creating
2429 @file{twoDsim.o} and produces a swig interface file @file{swig.i}.  We
2430 now use @code{swig} and @code{g++} to produce and compile the
2431 interface wrappers:
2433 @example
2434 $ libtool --mode=compile g++ -g -c twoDsim_m2.cpp -o twoDsim_m2.lo
2435 $ swig -c++ -python3 twoDsim.i
2436 $ libtool --mode=compile g++ -c -fPIC twoDsim_wrap.cxx \
2437    -I/usr/include/python3 -o twoDsim_wrap.lo
2438 $ libtool --mode=compile gm2 -g -fPIC -fiso -c deviceGnuPic.mod
2439 $ libtool --mode=compile gm2 -g -fPIC -fiso -c roots.mod
2440 $ libtool --mode=compile gm2 -g -fPIC -fiso -c -fswig \
2441    twoDsim.mod -o twoDsim.lo
2442 @end example
2444 Finally the application is linked into a shared library:
2446 @example
2447 $ libtool --mode=link gcc -g twoDsim_m2.lo twoDsim_wrap.lo \
2448   roots.lo deviceGnuPic.lo \
2449    -L$@{prefix@}/lib64 \
2450    -rpath `pwd` -lgm2 -lstdc++ -lm -o libtwoDsim.la
2451 cp .libs/libtwoDsim.so _twoDsim.so
2452 @end example
2454 The library name must start with @code{_} to comply with the Python3
2455 module naming scheme.
2457 @node Interface to C, Assembly language, Producing a Python module, Using
2458 @section Interfacing GNU Modula-2 to C
2460 The GNU Modula-2 compiler tries to use the C calling convention
2461 wherever possible however some parameters have no C equivalent and
2462 thus a language specific method is used.  For example unbounded arrays
2463 are passed as a @code{struct @{void *address, unsigned int high@}} and
2464 the contents of these arrays are copied by callee functions when they
2465 are declared as non @code{VAR} parameters.  The @code{VAR} equivalent
2466 unbounded array parameters need no copy, but still use the
2467 @code{struct} representation.
2469 The recommended method of interfacing GNU Modula-2 to C is by telling
2470 the definition module that the implementation is in the C language.
2471 This is achieved by using the tokens @code{DEFINITION MODULE FOR "C"}.
2472 Here is an example @file{libprintf.def}.
2474 @example
2475 DEFINITION MODULE FOR "C" libprintf ;
2477 EXPORT UNQUALIFIED printf ;
2479 PROCEDURE printf (a: ARRAY OF CHAR; ...) : [ INTEGER ] ;
2481 END libprintf.
2482 @end example
2484 the @code{UNQUALIFIED} keyword in the definition module informs
2485 GNU Modula-2 not to prefix the module name to exported references
2486 in the object file.
2488 The @code{printf} declaration states that the first parameter
2489 semantically matches @code{ARRAY OF CHAR} but since the module is for
2490 the C language it will be mapped onto @code{char *}.  The token
2491 @code{...} indicates a variable number of arguments (varargs) and all
2492 parameters passed here are mapped onto their C equivalents.  Arrays and
2493 constant strings are passed as pointers.  Lastly @code{[ INTEGER ]}
2494 states that the caller can ignore the function return result if desired.
2496 The hello world program can be rewritten as:
2498 @example
2499 MODULE hello ;
2501 FROM libprintf IMPORT printf ;
2503 BEGIN
2504    printf ("hello world\n")
2505 END hello.
2506 @end example
2508 and it can be compiled by:
2510 @samp{gm2 -g hello.mod -lc}
2512 In reality the @samp{-lc} is redundant as libc is always included in the
2513 linking process.  It is shown here to emphasize that the C library or
2514 object file containing @code{printf} must be present.  The search path
2515 for modules can be changed by using @samp{-I}.
2517 If a procedure function is declared using varargs then some parameter
2518 values are converted.  The table below summarizes the default conversions
2519 and default types used.
2521 @example
2522 Actual Parameter       |  Default conversion  |   Type of actual
2523                        |                      |   value passed
2524 ===============================================================
2525 123                    |  none                |   long long int
2526 "hello world"          |  none                |   const char *
2527 a: ARRAY OF CHAR       |  ADR (a)             |   char *
2528 a: ARRAY [0..5] OF CHAR|  ADR (a)             |   char *
2529 3.14                   |  none                |   long double
2530 @end example
2532 If you wish to pass @code{int} values then you should explicitly
2533 convert the constants using one of the conversion mechanisms.
2534 For example:  @code{INTEGER(10)} or @code{VAL(INTEGER, 10)} or
2535 @code{CAST(INTEGER, 10)}.
2537 @node Assembly language, Alignment, Interface to C, Using
2538 @section Interface to assembly language
2540 The interface for GNU Modula-2 to assembly language is almost
2541 identical to GNU C.  The only alterations are that the keywords
2542 @code{asm} and @code{volatile} are in capitals, following the Modula-2
2543 convention.
2545 A simple, but highly non optimal, example is given below.  Here we want
2546 to add the two @code{CARDINAL}s @code{foo} and @code{bar} together and
2547 return the result.  The target processor is assumed to be executing
2548 the x86_64 instruction set.
2550 @example
2551 PROCEDURE Example (foo, bar: CARDINAL) : CARDINAL ;
2553    myout: CARDINAL ;
2554 BEGIN
2555    ASM VOLATILE ("movq %1,%%rax; addq %2,%%rax; movq %%rax,%0"
2556       : "=rm" (myout)            (* outputs *)
2557       : "rm" (foo), "rm" (bar)   (* inputs  *)
2558       : "rax") ;                 (* we trash *)
2559    RETURN( myout )
2560 END Example ;
2561 @end example
2563 For a full description of this interface we refer the reader to the GNU C manual.
2565 @xref{Extended Asm, ,Extensions to the C Language Family,gcc}.
2567 The same example can be written using the newer extensions of naming
2568 the operands rather than using numbered arguments.
2570 @example
2571 PROCEDURE Example (foo, bar: CARDINAL) : CARDINAL ;
2573    myout: CARDINAL ;
2574 BEGIN
2575    ASM VOLATILE (
2576     "movq %[left],%%rax; addq %[right],%%rax; movq %%rax,%[output]"
2577       : [output] "=rm" (myout)                  (* outputs *)
2578       : [left] "rm" (foo), [right] "rm" (bar)   (* inputs  *)
2579       : "rax") ;                                (* we trash *)
2580    RETURN( myout )
2581 END Example ;
2582 @end example
2584 Both examples generate exactly the same code.  It is worth noting that
2585 the specifier ``rm'' indicates that the operand can be either a
2586 register or memory.  Of course you must choose an instruction which
2587 can take either, but this allows the compiler to take make more
2588 efficient choices depending upon the optimization level given to the
2589 compiler.
2591 @node Alignment, Packed, Assembly language, Using
2592 @section Data type alignment
2594 GNU Modula-2 allows you to specify alignment for types and variables.
2595 The syntax for alignment is to use the ISO pragma directives @code{<*}
2596 @code{bytealignment (} expression @code{)} and @code{*>}.  These directives
2597 can be used after type and variable declarations.
2599 The ebnf of the alignment production is:
2601 @example
2602 Alignment := [ ByteAlignment ] =:
2603 ByteAlignment := '<*' AttributeExpression '*>' =:
2604 AlignmentExpression := "(" ConstExpression ")" =:
2605 @end example
2607 The @code{Alignment} ebnf statement may be used during construction of
2608 types, records, record fields, arrays, pointers and variables.  Below
2609 is an example of aligning a type so that the variable @code{bar} is
2610 aligned on a 1024 address.
2612 @example
2613 MODULE align ;
2615 TYPE
2616    foo = INTEGER <* bytealignment(1024) *> ;
2619    z  : INTEGER ;
2620    bar: foo ;
2621 BEGIN
2622 END align.
2623 @end example
2625 The next example aligns a variable on a 1024 byte boundary.
2627 @example
2628 MODULE align2 ;
2631    x  : CHAR ;
2632    z  : ARRAY [0..255] OF INTEGER <* bytealignment(1024) *> ;
2633 BEGIN
2634 END align2.
2635 @end example
2637 Here the example aligns a pointer on a 1024 byte boundary.
2639 @example
2640 MODULE align4 ;
2642 FROM SYSTEM IMPORT ADR ;
2643 FROM libc IMPORT exit ;
2646    x  : CHAR ;
2647    z  : POINTER TO INTEGER <* bytealignment(1024) *> ;
2648 BEGIN
2649    IF ADR(z) MOD 1024=0
2650    THEN
2651       exit(0)
2652    ELSE
2653       exit(1)
2654    END
2655 END align4.
2656 @end example
2658 In example @code{align5} record field @code{y} is aligned on a 1024
2659 byte boundary.
2661 @example
2662 MODULE align5 ;
2664 FROM SYSTEM IMPORT ADR ;
2665 FROM libc IMPORT exit ;
2667 TYPE
2668    rec = RECORD
2669             x: CHAR ;
2670             y: CHAR <* bytealignment(1024) *> ;
2671          END ;
2673    r: rec ;
2674 BEGIN
2675    IF ADR(r.y) MOD 1024=0
2676    THEN
2677       exit(0)
2678    ELSE
2679       exit(1)
2680    END
2681 END align5.
2682 @end example
2684 In the example below module @code{align6} declares @code{foo} as an
2685 array of 256 @code{INTEGER}s.  The array @code{foo} is aligned on a
2686 1024 byte boundary.
2688 @example
2689 MODULE align6 ;
2691 FROM SYSTEM IMPORT ADR ;
2692 FROM libc IMPORT exit ;
2694 TYPE
2695    foo = ARRAY [0..255] OF INTEGER <* bytealignment(1024) *> ;
2698    x  : CHAR ;
2699    z  : foo ;
2700 BEGIN
2701    IF ADR(z) MOD 1024=0
2702    THEN
2703       exit(0)
2704    ELSE
2705       exit(1)
2706    END
2707 END align6.
2708 @end example
2710 @node Packed, Built-ins, Alignment, Using
2711 @section Packing data types
2713 The pragma @code{<* bytealignment(0) *>} can be used to specify that
2714 the fields within a @code{RECORD} are to be packed.  Currently this
2715 only applies to fields which are declared as subranges, ordinal types
2716 and enumerated types.  Here is an example of how two subranges might
2717 be packed into a byte.
2719 @example
2720 TYPE
2721    bits3c =  [0..7] ;
2722    bits3i = [-4..3] ;
2724    byte = RECORD
2725               <* bytealignment(0) *>
2726               x: bits3c ;
2727               <* bitsunused(2) *>
2728               y: bits3i ;
2729           END ;
2730 @end example
2732 Notice that the user has specified that in between fields @code{x} and
2733 @code{y} there are two bits unused.
2735 Now the user wishes to create a record with byte numbers zero and one
2736 occupied and then an @code{INTEGER32} field which is four byte
2737 aligned.  In this case byte numbers two and three will be unused.  The
2738 pragma @code{bytealignment} can be issued at the start of the record
2739 indicating the default alignment for the whole record and this can be
2740 overridden by individual fields if necessary.
2742 @example
2743    rec = RECORD
2744             <* bytealignment (1) *> ;
2745             a, b: byte ;
2746             x: INTEGER32 <* bytealignment(4) *> ;
2747          END ;
2748 @end example
2750 In the following example the user has specified that a record has two
2751 fields @code{p} and @code{q} but that there are three bytes unused between
2752 these fields.
2754 @example
2755    header = RECORD
2756                <* bytealignment(1) *>
2757                p: byte ;
2758                <* bytesunused(3) *>
2759                q: byte ;
2760             END ;
2761 @end example
2763 The pragma @code{<* bytesunused(x) *>} can only be used if the current
2764 field is on a byte boundary.  There is also a @code{SYSTEM} pseudo
2765 procedure function @code{TBITSIZE(T)} which returns the minimum number of
2766 bits necessary to represent type @code{T}.
2768 Another example of packing record bit fields is given below:
2770 @example
2771 MODULE align21 ;
2773 FROM libc IMPORT exit ;
2775 TYPE
2776    colour = (red, blue, green, purple, white, black) ;
2778    soc = PACKEDSET OF colour ;
2780    rec = RECORD
2781             <* bytealignment(0) *>
2782             x: soc ;
2783             y: [-1..1] ;
2784          END ;
2787    r: rec ;
2788    v: CARDINAL ;
2789 BEGIN
2790    v := SIZE(r) ;
2791    IF SIZE(r)#1
2792    THEN
2793       exit(1)
2794    END ;
2795    r.x := soc@{blue@} ;
2796    IF r.x#soc@{blue@}
2797    THEN
2798       exit(2)
2799    END
2800 END align21.
2801 @end example
2803 Here we see that the total size of this record is one byte and consists
2804 of a six bit set type followed by a 2 bit integer subrange.
2806 @node Built-ins, The PIM system module, Packed, Using
2807 @section Accessing GNU Modula-2 Built-ins
2809 This section describes the built-in constants and functions defined in
2810 GNU Modula-2.  The following compiler constants can be accessed using
2811 the @code{__ATTRIBUTE__} @code{__BUILTIN__} keywords.  These are not
2812 part of the Modula-2 language and they may differ depending upon the
2813 target architecture but they provide a method whereby common
2814 libraries can interface to a different underlying architecture.
2816 The built-in constants are: @code{BITS_PER_UNIT}, @code{BITS_PER_WORD},
2817 @code{BITS_PER_CHAR} and @code{UNITS_PER_WORD}.  They are integrated into
2818 GNU Modula-2 by an extension to the @code{ConstFactor} rule:
2820 @example
2821 ConstFactor := ConstQualidentOrSet | Number | ConstString |
2822                "(" ConstExpression ")" | "NOT" ConstFactor |
2823                ConstAttribute =:
2825 ConstAttribute := "__ATTRIBUTE__" "__BUILTIN__" "(" "(" Ident ")" ")" =:
2826 @end example
2828 Here is an example taken from the ISO library @code{SYSTEM.def}:
2830 @example
2831 CONST
2832    BITSPERLOC    = __ATTRIBUTE__ __BUILTIN__ ((BITS_PER_UNIT)) ;
2833    LOCSPERWORD   = __ATTRIBUTE__ __BUILTIN__ ((UNITS_PER_WORD)) ;
2834 @end example
2836 Built-in functions are transparent to the end user.  All built-in
2837 functions are declared in @code{DEFINITION MODULE}s and are imported
2838 as and when required.  Built-in functions are declared in definition
2839 modules by using the @code{__BUILTIN__} keyword.  Here is a section of
2840 the ISO library @code{LongMath.def} which demonstrates this feature.
2842 @example
2843 PROCEDURE __BUILTIN__ sqrt (x: LONGREAL): LONGREAL;
2844   (* Returns the square root of x *)
2845 @end example
2847 This indicates that the function @code{sqrt} will be implemented using
2848 the gcc built-in maths library.  If gcc cannot utilize the built-in
2849 function (for example if the programmer requested the address of
2850 @code{sqrt}) then code is generated to call the alternative function
2851 implemented in the @code{IMPLEMENTATION} @code{MODULE}.
2853 Sometimes a function exported from the @code{DEFINITION} @code{MODULE}
2854 will have a different name from the built-in function within gcc.  In
2855 such cases the mapping between the GNU Modula-2 function name and the
2856 gcc name is expressed using the keywords @code{__ATTRIBUTE__}
2857 @code{__BUILTIN__} @code{((Ident))}.  For example the function
2858 @code{sqrt} in @code{LongMath.def} maps onto the gcc built-in function
2859 @code{sqrtl} and this is expressed as:
2861 @example
2862 PROCEDURE __ATTRIBUTE__ __BUILTIN__ ((sqrtl)) sqrt
2863                                     (x: LONGREAL) : LONGREAL;
2864   (* Returns the positive square root of x *)
2865 @end example
2867 The following module @code{Builtins.def} enumerates the list of
2868 built-in functions which can be accessed in GNU Modula-2.  It also
2869 serves to define the parameter and return value for each function:
2871 @include m2/Builtins.texi
2873 Although this module exists and will result in the generation of
2874 in-line code if optimization flags are passed to GNU Modula-2, users
2875 are advised to utilize the same functions from more generic libraries.
2876 The built-in mechanism will be applied to these generic
2877 libraries where appropriate.  Note for the mathematical routines to
2878 be in-lined you need to specify the @samp{-ffast-math -O} options.
2880 @node The PIM system module, The ISO system module, Built-ins, Using
2881 @section The PIM system module
2883 @include m2/SYSTEM-pim.texi
2885 The different dialects of Modula-2 PIM-[234] and ISO Modula-2 declare
2886 the function @code{SIZE} in different places.  PIM-[34] and ISO
2887 Modula-2 declare @code{SIZE} as a pervasive function (declared in the
2888 base module).  PIM-2 defined @code{SIZE} in the @code{SYSTEM} module
2889 (as shown above).
2891 GNU Modula-2 allows users to specify the dialect of Modula-2 by using
2892 the @code{-fiso} and @code{-fpim2} command line switches.
2894 The data types @code{CSIZE_T} and @code{CSSIZE_T} are also exported from
2895 the @code{SYSTEM} module.  The type @code{CSIZE_T} is unsigned and is
2896 mapped onto the target C data type @code{size_t} whereas the type
2897 @code{CSSIZE_T} is mapped onto the signed C data type @code{ssize_t}.
2899 It is anticipated that these should only be used to provide cross
2900 platform definition modules for C libraries.
2902 There are also a variety of fixed sized @code{INTEGER} and
2903 @code{CARDINAL} types.  The variety of the fixed sized types will
2904 depend upon the target architecture.
2906 @node The ISO system module, Release map, The PIM system module, Using
2907 @section The ISO system module
2909 @include m2/SYSTEM-iso.texi
2911 The data types @code{CSIZE_T} and @code{CSSIZE_T} are also exported from
2912 the @code{SYSTEM} module.  The type @code{CSIZE_T} is unsigned and is
2913 mapped onto the target C data type @code{size_t} whereas the type
2914 @code{CSSIZE_T} is mapped onto the signed C data type @code{ssize_t}.
2916 It is anticipated that these should only be used to provide cross
2917 platform definition modules for C libraries.
2919 There are also a variety of fixed sized @code{INTEGER} and
2920 @code{CARDINAL} types.  The variety of the fixed sized types will
2921 depend upon the target architecture.
2923 @node Release map, Documentation, The ISO system module, Using
2924 @section Release map
2926 GNU Modula-2 is now part of GCC and therefore will adopt the GCC
2927 release schedule.  It is intended that GNU Modula-2 implement more of
2928 the GCC builtins (vararg access) and GCC features.
2930 There is an intention to implement the ISO generics and the M2R10
2931 dialect of Modula-2.  It will also implement all language changes.  If
2932 you wish to see something different please email
2933 @email{gm2@@nongnu.org} with your ideas.
2935 @node Documentation, Regression tests, Release map, Using
2936 @section Documentation
2938 The GNU Modula-2 documentation is available online at
2939 @url{https://gcc.gnu.org/onlinedocs/}
2940 in the PDF, info, and HTML file formats.
2942 @node Regression tests, Limitations, Documentation, Using
2943 @section Regression tests for gm2 in the repository
2945 The regression testsuite can be run from the gcc build directory:
2947 @example
2948 $ cd build-gcc
2949 $ make check -j 24
2950 @end example
2952 which runs the complete testsuite for all compilers using 24 parallel
2953 invocations of the compiler.  Individual language testsuites can be
2954 run by specifying the language, for example the Modula-2 testsuite can
2955 be run using:
2957 @example
2958 $ cd build-gcc
2959 $ make check-m2 -j 24
2960 @end example
2962 Finally the results of the testsuite can be emailed to the
2963 @url{https://gcc.gnu.org/lists.html, gcc-testresults} list using the
2964 @file{test_summary} script found in the gcc source tree:
2966 @example
2967 $ @samp{directory to the sources}/contrib/test_summary
2968 @end example
2970 @node Limitations, Objectives, Regression tests, Using
2971 @section Limitations
2973 Logitech compatibility library is incomplete.  The principle modules
2974 for this platform exist however for a comprehensive list of completed
2975 modules please check the documentation
2976 @url{gm2.html}.
2978 @node Objectives, FAQ, Limitations, Using
2979 @section Objectives
2981 @itemize @bullet
2983 @item
2984 The intention of GNU Modula-2 is to provide a production Modula-2
2985 front end to GCC.
2987 @item
2988 It should support all Niklaus Wirth PIM Dialects [234] and also ISO
2989 Modula-2 including a re-implementation of all the ISO modules.
2991 @item
2992 There should be an easy interface to C.
2994 @item
2995 Exploit the features of GCC.
2997 @item
2998 Listen to the requests of the users.
2999 @end itemize
3001 @node FAQ, Community, Objectives, Using
3002 @section FAQ
3004 @subsection Why use the C++ exception mechanism in GCC, rather than a bespoke Modula-2 mechanism?
3006 The C++ mechanism is tried and tested, it also provides GNU Modula-2
3007 with the ability to link with C++ modules and via swig it can raise
3008 Python exceptions.
3010 @node Community, Other languages, FAQ, Using
3011 @section Community
3013 You can subscribe to the GNU Modula-2 mailing by sending an
3014 email to:
3015 @email{gm2-subscribe@@nongnu.org}
3016 or by
3017 @url{https://lists.nongnu.org/mailman/listinfo/gm2}.
3018 The mailing list contents can be viewed
3019 @url{https://lists.gnu.org/archive/html/gm2}.
3021 @node Other languages, , Community, Using
3022 @section Other languages for GCC
3024 These exist and can be found on the frontends web page on the
3025 @uref{https://gcc.gnu.org/frontends.html, GCC web site}.
3027 @node License, Copying, Using, Top
3028 @section License of GNU Modula-2
3030 GNU Modula-2 is free software, the compiler is held under the GPL v3
3031 @uref{http://www.gnu.org/licenses/gpl.txt},
3032 its libraries (pim, iso and Logitech compatible) are under the
3033 GPL v3 with the GCC run time library exception clause.
3035 Under Section 7 of GPL version 3, you are granted additional
3036 permissions described in the GCC Runtime Library Exception, version
3037 3.1, as published by the Free Software Foundation.
3039 You should have received a copy of the GNU General Public License and
3040 a copy of the GCC Runtime Library Exception along with this program;
3041 see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
3042 <http://www.gnu.org/licenses/>.
3044 More information on how these licenses work is available
3045 @uref{http://www.gnu.org/licenses/licenses.html} on the GNU web site.
3047 @node Copying, Contributing, License, Top
3048 @include gpl_v3_without_node.texi
3050 @node Contributing, EBNF, Copying, Top
3051 @section Contributing to GNU Modula-2
3053 Please do and please read the GNU Emacs info under
3055 @example
3056 * Standards: (standards).       GNU coding standards.
3057 * Intellectual Property::       Keeping Free Software Free
3058 * Reading Non-Free Code::       Referring to Proprietary Programs
3059 * Contributions::               Accepting Contributions
3060 @end example
3062 You might consider joining the GM2 Mailing list before you start
3063 coding.  The mailing list may be subscribed via a web interface
3064 @uref{http://lists.nongnu.org/mailman/listinfo/gm2} or via email
3065 @email{gm2-subscribe@@nongnu.org}.
3067 Many thanks and enjoy your coding!
3069 @c @node Internals, , ,
3071 @c This section is still being written.
3072 @c @include gm2-internals.texi
3074 @node EBNF, Libraries, Contributing, Top
3075 @chapter EBNF of GNU Modula-2
3077 This chapter contains the EBNF of GNU Modula-2.  This grammar currently
3078 supports both PIM and ISO dialects.  The rules here are automatically
3079 extracted from the crammer files in GNU Modula-2 and serve to document
3080 the syntax of the extensions described earlier and how they fit in
3081 with the base language.
3083 Note that the first six productions are built into the lexical analysis
3084 phase.
3086 @include m2/gm2-ebnf.texi
3088 @node Libraries, Indices, EBNF, Top
3089 @chapter PIM and ISO library definitions
3091 This chapter contains M2F, PIM and ISO libraries.
3093 @include m2/gm2-libs.texi
3095 @node Indices, , Libraries, Top
3096 @section Indices
3098 @ifhtml
3099 @menu
3100 * Contents::    Section and subsections.
3101 * Functions::   Function, constants, types, ebnf indices.
3102 @end menu
3104 @node Contents, , ,
3105 @section Section and subsections
3106 @printindex cp
3108 @node Functions, , ,
3109 @section Function, constants, types, ebnf indices.
3110 @end ifhtml
3112 @printindex fn
3114 @summarycontents
3115 @contents
3116 @bye