3 @c Copyright (C) 2001-2023 Free Software Foundation, Inc.
4 @c This is part of the GM2 manual.
6 @c User level documentation for GNU Modula-2
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-2023
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
30 section entitled ``GNU Free Documentation License''.
32 @c man begin COPYRIGHT
40 @dircategory Software development
42 * gm2: (gm2). A GCC-based compiler for the Modula-2 language
50 @title The GNU Modula-2 Compiler
55 @vskip 0pt plus 1filll
56 Published by the Free Software Foundation @*
57 51 Franklin Street, Fifth Floor@*
58 Boston, MA 02110-1301, USA@*
65 @c `Top' Node and Master Menu
67 @node Top, Overview, (dir), (dir)
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 * 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.
82 @node Overview, Using, Top, Top
83 @chapter Overview of GNU Modula-2
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
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{http://gcc.gnu.org/frontends.html, front end}
96 for the GNU Compiler Collection (@uref{http://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
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,
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
158 @node Features, , Development, Overview
159 @section GNU Modula-2 Features
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}.
170 the option @samp{-fswig} will automatically create a swig interface
171 file which corresponds to the definition module of the file being
175 exception handling is compatible with C++ and swig. Modula-2 code can
176 be used with C or C++ code.
179 Python can call GNU Modula-2 modules via swig.
182 shared libraries can be built.
185 fixed sized types are now available from @samp{SYSTEM}.
188 @c support for dynamic @code{ARRAY}s has been added into @samp{gdb}.
191 variables can be declared at addresses.
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
200 supports sets of any ordinal size (memory permitting).
203 easy interface to C, and varargs can be passed to C routines.
206 many Logitech libraries have been implemented and can be accessed via:
207 @samp{-flibs=m2log,m2pim,m2iso}.
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).
216 can be built as a cross compiler (for embedded microprocessors
217 such as the AVR and the ARM).
221 @node Using, License, Overview, Top
222 @chapter Using GNU Modula-2
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 * Dialect:: GNU Modula-2 supported dialects.
231 * Exceptions:: Exception implementation
232 * Semantic checking:: How to detect run time problems at compile time.
233 * Extensions:: GNU Modula-2 language extensions.
234 * Type compatibility:: Data type compatibility.
235 * Unbounded by reference::Explanation of a language optimization.
236 * Building a shared library:: How to build a shared library.
237 * Interface for Python:: How to produce swig interface files.
238 * Producing a Python module:: How to produce a Python module.
239 * Interface to C:: Interfacing GNU Modula-2 to C.
240 * Assembly language:: Interface to assembly language.
241 * Alignment:: Data type alignment.
242 * Packed:: Packing data types.
243 * Built-ins:: Accessing GNU Modula-2 Built-ins.
244 * The PIM system module:: SYSTEM data types and procedures.
245 * The ISO system module:: SYSTEM data types, procedures and run time.
247 @c omit these nodes if generating gm2 webpage as these are hand written.
248 * Release map:: Release map.
249 * Documentation:: Placeholder for how to access the documentation online.
250 * Regression tests:: How to run the testsuite.
251 * Limitations:: Current limitations.
252 * Objectives:: Objectives of the implementation.
253 * FAQ:: Frequently asked questions.
254 * Community:: How to join the community.
255 * Other languages:: Other languages for GCC.
259 This document contains the user and design issues relevant to the
260 Modula-2 front end to gcc.
262 @node Example usage, Compiler options, Using, Using
263 @section Example compile and link
266 @c man begin SYNOPSIS gm2
267 gm2 [@option{-c}|@option{-S}] [@option{-g}] [@option{-pg}]
268 [@option{-O}@var{level}] [@option{-W}@var{warn}@dots{}]
269 [@option{-I}@var{dir}@dots{}] [@option{-L}@var{dir}@dots{}]
270 [@option{-f}@var{option}@dots{}] [@option{-m}@var{machine-option}@dots{}]
271 [@option{-o} @var{outfile}] [@@@var{file}] @var{infile}@dots{}
273 Only the most useful options are listed here; see below for the
277 gpl(7), gfdl(7), fsf-funding(7), gcc(1)
278 and the Info entries for @file{gm2} and @file{gcc}.
282 @c man begin DESCRIPTION gm2
284 The @command{gm2} command is the GNU compiler for the Modula-2 language and
285 supports many of the same options as @command{gcc}. @xref{Option Summary, ,
286 Option Summary, gcc, Using the GNU Compiler Collection (GCC)}.
287 This manual only documents the options specific to @command{gm2}.
291 This section describes how to compile and link a simple hello world
292 program. It provides a few examples of using the different options
293 mentioned in @pxref{Compiler options, , ,gm2}. Assuming that you have
294 a file called @file{hello.mod} in your current directory which
300 FROM StrIO IMPORT WriteString, WriteLn ;
303 WriteString ('hello world') ; WriteLn
307 You can compile and link it by: @samp{gm2 -g hello.mod}.
308 The result will be an @samp{a.out} file created in your directory.
310 You can split this command into two steps if you prefer. The compile
311 step can be achieved by: @samp{gm2 -g -c -fscaffold-main hello.mod}
312 and the link via: @samp{gm2 -g hello.o}.
314 @footnote{To see all the compile actions taken by @samp{gm2} users can also
315 add the @samp{-v} flag at the command line, for example:
317 @samp{gm2 -v -g -I. hello.mod}
319 This displays the sub processes initiated by @samp{gm2} which can be useful
320 when trouble shooting.}
322 @node Compiler options, Linking, Example usage, Using
323 @section Compiler options
325 This section describes the compiler options specific to GNU Modula-2
326 for generic flags details @xref{Invoking GCC, , ,gcc}.
330 For any given input file, the file name suffix determines what kind of
331 compilation is done. The following kinds of input file names are supported:
335 Modula-2 implementation or program source files. See the
336 @samp{-fmod=} option if you wish to compile a project which uses a
337 different source file extension.
339 Modula-2 definition module source files. Definition modules are not
340 compiled separately, in GNU Modula-2 definition modules are parsed as
341 required when program or implementation modules are compiled. See the
342 @samp{-fdef=} option if you wish to compile a project which uses a
343 different source file extension.
346 You can specify more than one input file on the @command{gm2} command line,
351 create debugging information so that debuggers such as @file{gdb}
352 can inspect and control executable.
355 used to specify the search path for definition and implementation
356 modules. An example is: @code{gm2 -g -c -I.:../../libs foo.mod}.
357 If this option is not specified then the default path is added
358 which consists of the current directory followed by the appropriate
359 language dialect library directories.
361 @c ordered list of options from here.
364 turns on auto initialization of pointers to NIL. Whenever a block is
365 created all pointers declared within this scope will have their
366 addresses assigned to NIL.
369 turns on run time subrange, array index and indirection via @code{NIL}
373 turns on compile time checking to check whether a @code{CASE}
374 statement requires an @code{ELSE} clause when on was not specified.
377 preprocess the source with @samp{cpp -lang-asm -traditional-cpp}
378 For further details about these options @xref{Invocation, , ,cpp}.
379 If @samp{-fcpp} is supplied then all definition modules and
380 implementation modules which are parsed will be prepossessed by
385 @c passed to the preprocessor if -fcpp is used (internal switch)
389 @c passed to the preprocessor if -fcpp is used (internal switch)
391 @item -fdebug-builtins
392 call a real function, rather than the builtin equivalent. This can
393 be useful for debugging parameter values to a builtin function as
394 it allows users to single step code into a real function.
398 @c turn on internal debugging of the compiler (internal switch)
402 @c turn on quadruple tracing (internal switch)
406 @c turn on the Modula-2 api tracing (internal switch)
408 @c fdebug-function-line-numbers
410 @c turn on the Modula-2 function line number generation (internal switch)
413 recognize the specified suffix as a definition module filename.
414 The default implementation and module filename suffix is @file{.def}.
415 If this option is used GNU Modula-2 will still fall back to this
416 default if a requested definition module is not found.
418 @item -fdump-system-exports
419 display all inbuilt system items.
420 This is an internal command line option.
423 turn on exception handling code. By default this option is on.
424 Exception handling can be disabled by @samp{-fno-exceptions}
425 and no references are made to the run time exception libraries.
427 @item -fextended-opaque
428 allows opaque types to be implemented as any type. This is a GNU
429 Modula-2 extension and it requires that the implementation module
430 defining the opaque type is available so that it can be resolved when
431 compiling the module which imports the opaque type.
434 turns on run time checking to check whether a floating point number is
435 about to exceed range.
437 @item -fgen-module-list=@file{filename}
438 attempt to find all modules when linking and generate a module list.
439 If the @file{filename} is @samp{-} then the contents are not written
440 and only used to force the linking of all module ctors.
441 This option cannot be used if @samp{-fuse-list=} is enabled.
444 generate code to check whether array index values are out of bounds.
445 Array index checking can be disabled via @samp{-fno-index}.
448 turn on ISO standard features. Currently this enables the ISO
449 @code{SYSTEM} module and alters the default library search path so
450 that the ISO libraries are searched before the PIM libraries. It also
451 effects the behavior of @code{DIV} and @code{MOD} operators.
452 @xref{Dialect, , ,gm2}.
455 modifies the default library search path. The libraries supplied are:
456 m2pim, m2iso, m2min, m2log and m2cor. These map onto the
457 Programming in Modula-2 base libraries, ISO standard libraries, minimal
458 library support, Logitech compatible library and Programming in
459 Modula-2 with coroutines.
460 Multiple libraries can be specified and are comma separated with precedence
461 going to the first in the list. It is not necessary to use -flibs=m2pim or
462 -flibs=m2iso if you also specify -fpim, -fpim2, -fpim3, -fpim4 or
463 -fiso. Unless you are using -flibs=m2min you should include m2pim as
464 the they provide the base modules which all other dialects utilize.
465 The option @samp{-fno-libs=-} disables the @samp{gm2} driver from
466 modifying the search and library paths.
469 On systems that provide the m2 runtimes as both shared and static libraries,
470 this option forces the use of the static version.
474 @c set all location values to a specific value (internal switch)
477 improve the debugging experience for new programmers at the expense
478 of generating @code{nop} instructions if necessary to ensure single
479 stepping precision over all code related keywords. An example
480 of this is in termination of a list of nested @code{IF} statements
481 where multiple @code{END} keywords are mapped onto a sequence of
482 @code{nop} instructions.
484 @item -fm2-lower-case
485 render keywords in error messages using lower case.
488 insert plugin to identify run time errors at compile time (default on).
490 @item -fm2-statistics
491 generates quadruple information: number of quadruples generated,
492 number of quadruples remaining after optimization and number of source
495 @item -fm2-strict-type
496 experimental flag to turn on the new strict type checker.
498 @item -fm2-whole-program
499 compile all implementation modules and program module at once. Notice
500 that you need to take care if you are compiling different dialect
501 modules (particularly with the negative operands to modulus). But
502 this option, when coupled together with @code{-O3}, can deliver huge
503 performance improvements.
506 recognize the specified suffix as implementation and module filenames.
507 The default implementation and module filename suffix is @file{.mod}.
508 If this option is used GNU Modula-2 will still fall back to this
509 default if it needs to read an implementation module and the specified
510 suffixed filename does not exist.
513 generate code to detect accessing data through a @code{NIL} value
514 pointer. Dereferencing checking through a @code{NIL} pointer can be
515 disabled by @samp{-fno-nil}.
518 turn on PIM standard features. Currently this enables the PIM
519 @code{SYSTEM} module and determines which identifiers are pervasive
520 (declared in the base module). If no other @samp{-fpim[234]} switch is
521 used then division and modulus operators behave as defined in PIM4.
522 @xref{Dialect, , ,gm2}.
525 turn on PIM-2 standard features. Currently this removes @code{SIZE}
526 from being a pervasive identifier (declared in the base module). It
527 places @code{SIZE} in the @code{SYSTEM} module. It also effects the
528 behavior of @code{DIV} and @code{MOD} operators.
529 @xref{Dialect, , ,gm2}.
532 turn on PIM-3 standard features. Currently this only effects the
533 behavior of @code{DIV} and @code{MOD} operators.
534 @xref{Dialect, , ,gm2}.
537 turn on PIM-4 standard features. Currently this only effects the
538 behavior of @code{DIV} and @code{MOD} operators.
539 @xref{Dialect, , ,gm2}.
541 @item -fpositive-mod-floor-div
542 forces the @code{DIV} and @code{MOD} operators to behave as defined by PIM4.
543 All modulus results are positive and the results from the division are
544 rounded to the floor.
545 @xref{Dialect, , ,gm2}.
548 link against the pthread library. By default this option is on. It
549 can be disabled by @samp{-fno-pthread}. GNU Modula-2 uses the GCC
550 pthread libraries to implement coroutines (see the SYSTEM
551 implementation module).
555 @c -internal compiler debugging information, dump the list of quadruples
558 generate code to check the assignment range, return value range
559 set range and constructor range. Range checking can be disabled
560 via @samp{-fno-range}.
563 generate code to check that functions always exit with a @code{RETURN}
564 and do not fall out at the end. Return checking can be disabled
565 via @samp{-fno-return}.
567 @item -fruntime-modules=
568 specify, using a comma separated list, the run time modules and their
569 order. These modules will initialized first before any other modules
570 in the application dependency. By default the run time modules list is
571 set to @code{Storage,SYSTEM,M2RTS,RTExceptions,IOLink}. Note that
572 these modules will only be linked into your executable if they are
573 required. So adding a long list of dependent modules will not effect
574 the size of the executable it merely states the initialization order
575 should they be required.
577 @item -fscaffold-dynamic
578 the option ensures that @samp{gm2} will generate a dynamic scaffold
579 infrastructure when compiling implementation and program modules.
580 By default this option is on. Use @samp{-fno-scaffold-dynamic}
581 to turn it off or select @samp{-fno-scaffold-static}.
584 generate a C source scaffold for the current module being compiled.
587 generate a C++ source scaffold for the current module being compiled.
589 @item -fscaffold-main
590 force the generation of the @samp{main} function. This is not
591 necessary if the @samp{-c} is omitted.
593 @item -fscaffold-static
594 the option ensures that @samp{gm2} will generate a static scaffold
595 within the program module. The static scaffold consists of sequences
596 of calls to all dependent module initialization and finalization
597 procedures. The static scaffold is useful for debugging and single
598 stepping the initialization blocks of implementation modules.
601 generate a shared library from the module.
603 @item -fsoft-check-all
604 turns on all run time checks. This is the same as invoking
605 GNU Modula-2 using the command options
606 @code{-fnil} @code{-frange} @code{-findex}
608 @code{-fwholediv} @code{-fcase} @code{-freturn}.
611 displays the path to the source of each module. This option
612 can be used at compile time to check the correct definition module
616 generate a swig interface file.
618 @item -funbounded-by-reference
619 enable optimization of unbounded parameters by attempting to pass non
620 @code{VAR} unbounded parameters by reference. This optimization
621 avoids the implicit copy inside the callee procedure. GNU Modula-2
622 will only allow unbounded parameters to be passed by reference if,
623 inside the callee procedure, they are not written to, no address is
624 calculated on the array and it is not passed as a @code{VAR}
625 parameter. Note that it is possible to write code to break this
626 optimization, therefore this option should be used carefully.
627 For example it would be possible to take the address of an array, pass
628 the address and the array to a procedure, read from the array in
629 the procedure and write to the location using the address parameter.
631 Due to the dangerous nature of this option it is not enabled
632 when the @samp{-O} option is specified.
634 @item -fuse-list=@file{filename}
635 if @samp{-fscaffold-static} is enabled then use the file
636 @file{filename} for the initialization order of modules. Whereas if
637 @samp{-fscaffold-dynamic} is enabled then use this file to force
638 linking of all module ctors.
639 This option cannot be used if @samp{-fgen-module-list=} is enabled.
642 generate code to detect whole number division by zero or modulus by
646 generate code to detect whole number overflow and underflow.
648 @c the following warning options are complete but need to be
649 @c regression tested against all other front ends
650 @c to ensure the options do not conflict.
653 @c turn on all Modula-2 warnings.
656 @c forces the compiler to reject nested @code{WITH} statements
657 @c referencing the same record type. Does not allow multiple imports of
658 @c the same item from a module. It also checks that: procedure variables
659 @c are written to before being read; variables are not only written to
660 @c but read from; variables are declared and used. If the compiler
661 @c encounters a variable being read before written it will terminate with
662 @c a message. It will check that @code{FOR} loop indices are not used
663 @c outside the end of this loop without being reset.
665 @c @item -Wpedantic-cast
666 @c warns if the ISO system function is used and if the size of
667 @c the variable is different from that of the type. This is legal
668 @c in ISO Modula-2, however it can be dangerous. Some users may prefer
669 @c to use @code{VAL} instead in these situations and use @code{CAST}
670 @c exclusively for changes in type on objects which have the same size.
672 @c @item -Wpedantic-param-names
673 @c procedure parameter names are checked in the definition module
674 @c against their implementation module counterpart. This is not
675 @c necessary in ISO or PIM versions of Modula-2.
678 @c checks for poor programming style. This option is aimed at new users of
679 @c Modula-2 in that it checks for situations which might cause confusion
680 @c and thus mistakes. It checks whether variables of the same name are
681 @c declared in different scopes and whether variables look like keywords.
682 @c Experienced users might find this option too aggressive.
684 @c @item -Wunused-variable
685 @c warns if a variable has been declared and it not used.
687 @c @item -Wunused-parameter
688 @c warns if a parameter has been declared and it not used.
690 @c @item -Wverbose-unbounded
691 @c inform the user which non @code{VAR} unbounded parameters will be
692 @c passed by reference. This only produces output if the option
693 @c @samp{-funbounded-by-reference} is also supplied on the command line.
699 @node Linking, Elementary data types, Compiler options, Using
701 This section describes the linking related options. There are three
702 linking strategies available which are dynamic scaffold, static
703 scaffold and user defined. The dynamic scaffold is enabled by default
704 and each module will register itself to the run time @samp{M2RTS} via
705 a constructor. The static scaffold mechanism will invoke each modules
706 @samp{_init} and @samp{_finish} function in turn via a sequence of
707 calls from within @samp{main}. Lastly the user defined strategy
708 can be implemented by turning off the dynamic and static options via
709 @samp{-fno-scaffold-dynamic} and @samp{-fno-scaffold-static}.
711 In the simple test below:
717 the driver will add the options @samp{-fscaffold-dynamic} and
718 @samp{-fgen-module-list=-} which generate a list of application
719 modules and also creates the @samp{main} function with calls to
720 @samp{M2RTS}. It can be useful to add the option @samp{-fsources}
721 which displays the source files as they are parsed and summarizes
722 whether the source file is required for compilation or linking.
724 If you wish to split the above command line into a compile and link
725 then you could use these steps:
728 $ gm2 -c -fscaffold-main hello.mod
732 The @samp{-fscaffold-main} informs the compiler to generate the
733 @samp{main} function and scaffold. You can enable the environment
734 variable @samp{GCC_M2LINK_RTFLAG} to trace the construction and
735 destruction of the application. The values for
736 @samp{GCC_M2LINK_RTFLAG} are shown in the table below:
741 all | turn on all flags below
742 module | trace modules as they register themselves
743 pre | generate module list prior to dependency resolution
744 dep | trace module dependency resolution
745 post | generate module list after dependency resolution
746 force | generate a module list after dependency and forced
747 | ordering is complete
750 The values can be combined using a comma separated list.
752 One of the advantages of the dynamic scaffold is that the driver
753 behaves in a similar way to the other front end drivers.
754 For example consider a small project consisting of 4 definition
755 implementation modules (@samp{a.def}, @samp{a.mod}, @samp{b.def},
756 @samp{b.mod}, @samp{c.def}, @samp{c.mod}, @samp{d.def}, @samp{d.mod})
757 and a program module @samp{program.mod}.
759 To link this project we could:
766 $ gm2 -g program.mod a.o b.o c.o d.o
769 The module initialization sequence is defined by the ISO standard to
770 follow the import graph traversal. The initialization order is the
771 order in which the corresponding separate modules finish the
772 processing of their import lists.
774 However, if required, you can override this using
775 @samp{-fruntime-modules=a,b,c,d} for example which forces the
776 initialization sequence to @samp{a}, @samp{b}, @samp{c} and @samp{d}.
778 @node Elementary data types, Standard procedures, Linking, Using
779 @section Elementary data types
781 This section describes the elementary data types supported by GNU
782 Modula-2. It also describes the relationship between these data types
783 and the equivalent C data types.
785 The following data types are supported: @code{INTEGER},
786 @code{LONGINT}, @code{SHORTINT}, @code{CARDINAL}, @code{LONGCARD},
787 @code{SHORTCARD}, @code{BOOLEAN}, @code{REAL}, @code{LONGREAL},
788 @code{SHORTREAL}, @code{COMPLEX}, @code{LONGCOMPLEX},
789 @code{SHORTCOMPLEX} and @code{CHAR}.
791 An equivalence table is given below:
795 ======================================
797 LONGINT long long int
799 CARDINAL unsigned int
800 LONGCARD long long unsigned int
801 SHORTCARD short unsigned int
807 SHORTCOMPLEX complex float
808 COMPLEX complex double
809 LONGCOMPLEX complex long double
812 Note that GNU Modula-2 also supports fixed sized data types which are
813 exported from the @code{SYSTEM} module.
814 @xref{The PIM system module, , ,gm2}.
815 @xref{The ISO system module, , ,gm2}.
817 @node Standard procedures, Dialect, Elementary data types, Using
818 @section Permanently accessible base procedures.
820 This section describes the procedures and functions which are
823 @subsection Standard procedures and functions common to PIM and ISO
825 The following procedures are implemented and conform with Programming
826 in Modula-2 and ISO Modula-2: @code{NEW}, @code{DISPOSE}, @code{INC},
827 @code{DEC}, @code{INCL}, @code{EXCL} and @code{HALT}. The standard
828 functions are: @code{ABS}, @code{CAP}, @code{CHR}, @code{FLOAT},
829 @code{HIGH}, @code{LFLOAT}, @code{LTRUNC}, @code{MIN}, @code{MAX},
830 @code{ODD}, @code{SFLOAT}, @code{STRUNC} @code{TRUNC} and
831 @code{VAL}. All these functions and procedures (except @code{HALT},
832 @code{NEW}, @code{DISPOSE} and, under non constant conditions,
833 @code{LENGTH}) generate in-line code for efficiency.
838 ABS - returns the positive value of i.
842 PROCEDURE ABS (i: <any signed type>) : <any signed type> ;
849 CAP - returns the capital of character ch providing
850 ch lies within the range 'a'..'z'. Otherwise ch
851 is returned unaltered.
855 PROCEDURE CAP (ch: CHAR) : CHAR ;
862 CHR - converts a value of a <whole number type> into a CHAR.
863 CHR(x) is shorthand for VAL(CHAR, x).
867 PROCEDURE CHR (x: <whole number type>) : CHAR ;
874 DISPOSE - the procedure DISPOSE is replaced by:
875 DEALLOCATE(p, TSIZE(p^)) ;
876 The user is expected to import the procedure DEALLOCATE
877 (normally found in the module, Storage.)
879 In: a variable p: of any pointer type which has been
880 initialized by a call to NEW.
881 Out: the area of memory
882 holding p^ is returned to the system.
883 Note that the underlying procedure DEALLOCATE
884 procedure in module Storage will assign p to NIL.
888 PROCEDURE DISPOSE (VAR p:<any pointer type>) ;
894 DEC - can either take one or two parameters. If supplied
895 with one parameter then on the completion of the call to
896 DEC, v will have its predecessor value. If two
897 parameters are supplied then the value v will have its
898 n'th predecessor. For these reasons the value of n
903 PROCEDURE DEC (VAR v: <any base type>; [n: <any base type> = 1]) ;
909 EXCL - excludes bit element e from a set type s.
913 PROCEDURE EXCL (VAR s: <any set type>; e: <element of set type s>) ;
919 FLOAT - will return a REAL number whose value is the same as o.
923 PROCEDURE FLOAT (o: <any whole number type>) : REAL ;
929 FLOATS - will return a SHORTREAL number whose value is the same as o.
933 PROCEDURE FLOATS (o: <any whole number type>) : REAL ;
939 FLOATL - will return a LONGREAL number whose value is the same as o.
943 PROCEDURE FLOATL (o: <any whole number type>) : REAL ;
949 HALT - will call the HALT procedure inside the module M2RTS.
950 Users can replace M2RTS.
960 HIGH - returns the last accessible index of an parameter declared as
963 PROCEDURE foo (a: ARRAY OF CHAR) ;
974 will cause the local variable c to contain the value 4
978 PROCEDURE HIGH (a: ARRAY OF CHAR) : CARDINAL ;
984 INC - can either take one or two parameters. If supplied
985 with one parameter then on the completion of the call to
986 INC, v will have its successor value. If two
987 parameters are supplied then the value v will have its
988 n'th successor. For these reasons the value of n
993 PROCEDURE INC (VAR v: <any base type>; [n: <any base type> = 1]) ;
999 INCL - includes bit element e to a set type s.
1003 PROCEDURE INCL (VAR s: <any set type>; e: <element of set type s>) ;
1009 LFLOAT - will return a LONGREAL number whose value is the same as o.
1013 PROCEDURE LFLOAT (o: <any whole number type>) : LONGREAL ;
1019 LTRUNC - will return a LONG<type> number whose value is the
1020 same as o. PIM2, PIM3 and ISO Modula-2 will return
1021 a LONGCARD whereas PIM4 returns LONGINT.
1025 PROCEDURE LTRUNC (o: <any floating point type>) : LONG<type> ;
1031 MIN - returns the lowest legal value of an ordinal type.
1035 PROCEDURE MIN (t: <ordinal type>) : <ordinal type> ;
1042 MAX - returns the largest legal value of an ordinal type.
1046 PROCEDURE MAX (t: <ordinal type>) : <ordinal type> ;
1053 NEW - the procedure NEW is replaced by:
1054 ALLOCATE(p, TSIZE(p^)) ;
1055 The user is expected to import the procedure ALLOCATE
1056 (normally found in the module, Storage.)
1058 In: a variable p: of any pointer type.
1059 Out: variable p is set to some allocated memory
1060 which is large enough to hold all the contents of p^.
1064 PROCEDURE NEW (VAR p:<any pointer type>) ;
1070 ODD - returns TRUE if the value is not divisible by 2.
1074 PROCEDURE ODD (x: <whole number type>) : BOOLEAN ;
1081 SFLOAT - will return a SHORTREAL number whose value is the same
1086 PROCEDURE SFLOAT (o: <any whole number type>) : SHORTREAL ;
1092 STRUNC - will return a SHORT<type> number whose value is the same
1093 as o. PIM2, PIM3 and ISO Modula-2 will return a
1094 SHORTCARD whereas PIM4 returns SHORTINT.
1098 PROCEDURE STRUNC (o: <any floating point type>) : SHORT<type> ;
1104 TRUNC - will return a <type> number whose value is the same as o.
1105 PIM2, PIM3 and ISO Modula-2 will return a CARDINAL
1106 whereas PIM4 returns INTEGER.
1110 PROCEDURE TRUNC (o: <any floating point type>) : <type> ;
1116 TRUNCS - will return a <type> number whose value is the same
1117 as o. PIM2, PIM3 and ISO Modula-2 will return a
1118 SHORTCARD whereas PIM4 returns SHORTINT.
1122 PROCEDURE TRUNCS (o: <any floating point type>) : <type> ;
1128 TRUNCL - will return a <type> number whose value is the same
1129 as o. PIM2, PIM3 and ISO Modula-2 will return a
1130 LONGCARD whereas PIM4 returns LONGINT.
1134 PROCEDURE TRUNCL (o: <any floating point type>) : <type> ;
1140 VAL - converts data i of <any simple data type 2> to
1141 <any simple data type 1> and returns this value.
1142 No range checking is performed during this conversion.
1146 PROCEDURE VAL (<any simple data type 1>,
1147 i: <any simple data type 2>) : <any simple data type 1> ;
1151 @subsection ISO specific standard procedures and functions
1153 The standard function @code{LENGTH} is specific to ISO Modula-2 and
1159 IM - returns the imaginary component of a complex type.
1160 The return value will the same type as the imaginary field
1161 within the complex type.
1165 PROCEDURE IM (c: <any complex type>) : <floating point type> ;
1171 INT - returns an INTEGER value which has the same value as v.
1172 This function is equivalent to: VAL(INTEGER, v).
1176 PROCEDURE INT (v: <any ordinal type>) : INTEGER ;
1182 LENGTH - returns the length of string a.
1186 PROCEDURE LENGTH (a: ARRAY OF CHAR) : CARDINAL ;
1189 This function is evaluated at compile time, providing that string
1190 @code{a} is a constant. If @code{a} cannot be evaluated then a call is
1191 made to @code{M2RTS.Length}.
1196 ODD - returns a BOOLEAN indicating whether the whole number
1201 PROCEDURE ODD (v: <any whole number type>) : BOOLEAN ;
1207 RE - returns the real component of a complex type.
1208 The return value will the same type as the real field
1209 within the complex type.
1213 PROCEDURE RE (c: <any complex type>) : <floating point type> ;
1216 @node Dialect, Exceptions, Standard procedures, Using
1217 @section GNU Modula-2 supported dialects
1219 This section describes the dialects understood by GNU Modula-2.
1220 It also describes the differences between the dialects and
1221 any command line switches which determine dialect behaviour.
1223 The GNU Modula-2 compiler is compliant with four dialects of Modula-2.
1224 The language as defined in 'Programming in Modula-2' 2nd Edition,
1225 Springer Verlag, 1982, 1983 by Niklaus Wirth (PIM2), 'Programming in
1226 Modula-2', 3rd Corrected Edition, Springer Verlag, 1985 (PIM3) and
1227 'Programming in Modula-2', 4th Edition, Springer Verlag, 1988 (PIM4)
1228 @uref{http://freepages.modula2.org/report4/modula-2.html} and the ISO
1229 Modula-2 language as defined in ISO/IEC Information technology -
1230 programming languages - part 1: Modula-2 Language, ISO/IEC 10514-1
1233 The command line switches @samp{-fpim2}, @samp{-fpim3}, @samp{-fpim4}
1234 and @samp{-fiso} can be used to force mutually exclusive
1235 features. However by default the compiler will not aggressively fail
1236 if a non mutually exclusive feature is used from another dialect. For
1237 example it is possible to specify @samp{-fpim2} and still utilize
1238 @samp{DEFINITION} @samp{MODULES} which have no export list.
1240 Some dialect differences will force a compile time error, for example
1241 in PIM2 the user must @code{IMPORT} @code{SIZE} from the module
1242 @code{SYSTEM}, whereas in PIM3 and PIM4 @code{SIZE} is a pervasive
1243 function. Thus compiling PIM4 source code with the @samp{-fpim2}
1244 switch will cause a compile time error. This can be fixed quickly
1245 with an additional @code{IMPORT} or alternatively by compiling with
1246 the @samp{-fpim4} switch.
1248 However there are some very important differences between the dialects
1249 which are mutually exclusive and therefore it is vital that users
1250 choose the dialects with care when these language features are used.
1252 @subsection Integer division, remainder and modulus
1254 The most dangerous set of mutually exclusive features found in the
1255 four dialects supported by GNU Modula-2 are the @code{INTEGER}
1256 division, remainder and modulus arithmetic operators. It is important
1257 to note that the same source code can be compiled to give different
1258 run time results depending upon these switches! The reference manual
1259 for the various dialects of Modula-2 are quite clear about this
1260 behavior and sadly there are three distinct definitions.
1262 The table below illustrates the problem when a negative operand is
1267 ----------- ----------- ----------------------
1268 lval rval DIV MOD DIV MOD DIV MOD / REM
1269 31 10 3 1 3 1 3 1 3 1
1270 -31 10 -3 -1 -4 9 -4 9 -3 -1
1271 31 -10 -3 1 -3 1 Exception -3 1
1272 -31 -10 3 -1 4 9 Exception 3 -1
1275 See also P24 of PIM2, P27 of PIM3, P29 of PIM4 and P201 of the ISO
1276 Standard. At present all dialect division, remainder and modulus are
1277 implemented as above, apart from the exception calling in the ISO
1278 dialect. Instead of exception handling the results are the same as the
1279 PIM4 dialect. This is a temporary implementation situation.
1281 @node Exceptions, Semantic checking, Dialect, Using
1282 @section Exception implementation
1284 This section describes how exceptions are implemented in GNU Modula-2
1285 and how command line switches affect their behavior. The option
1286 @samp{-fsoft-check-all} enables all software checking of nil
1287 dereferences, division by zero etc. Additional code is produced to
1288 check these conditions and exception handlers are invoked if the
1291 Without @samp{-fsoft-check-all} these exceptions will be caught by
1292 hardware (assuming the hardware support exists) and a signal handler
1293 is invoked. The signal handler will in turn @code{THROW} an exception
1294 which will be caught by the appropriate Modula-2 handler. However the
1295 action of throwing an exception from within a signal handler is
1296 implementation defined (according to the C++ documentation). For
1297 example on the x86_64 architecture this works whereas on the i686
1298 architecture it does not. Therefore to ensure portability it is
1299 recommended to use @samp{-fsoft-check-all}.
1301 @footnote{@samp{-fsoft-check-all} can be effectively combined with
1302 @samp{-O2} to semantically analyze source code for possible run time
1303 errors at compile time.}
1305 @node Semantic checking, Extensions, Exceptions, Using
1306 @section How to detect run time problems at compile time
1308 Consider the following program:
1311 MODULE assignvalue ; (*!m2iso+gm2*)
1313 PROCEDURE bad () : INTEGER ;
1324 (* The m2rte plugin will detect this as an error, post
1330 here we see that the programmer has overlooked that the return value
1331 from @samp{bad} will cause an overflow to @samp{foo}. If we compile
1332 the code with the following options:
1335 $ gm2 -g -fsoft-check-all -O2 -c assignvalue.mod
1336 assignvalue.mod:16:0:inevitable that this error will occur at run time,
1337 assignment will result in an overflow
1340 The gm2 semantic plugin is automatically run and will generate a
1341 warning message for every exception call which is known as reachable.
1342 It is highly advised to run the optimizer (@samp{-O2} or @samp{-O3})
1343 with @samp{-fsoft-check-all} so that the compiler is able to run the
1344 optimizer and perform variable and flow analysis before the semantic
1347 @node Extensions, Type compatibility, Semantic checking, Using
1348 @section GNU Modula-2 language extensions
1350 This section introduces the GNU Modula-2 language extensions.
1351 The GNU Modula-2 compiler allows abstract data types to be any type,
1352 not just restricted to a pointer type providing the
1353 @samp{-fextended-opaque} option is supplied
1354 @xref{Compiler options, , ,gm2}.
1356 Declarations can be made in any order, whether they are
1357 types, constants, procedures, nested modules or variables.
1358 @c (@xref{Passes, , ,}.)
1360 GNU Modula-2 also allows programmers to interface to @code{C} and
1363 GNU Modula-2 provides support for the special tokens @code{__LINE__},
1364 @code{__FILE__}, @code{__FUNCTION__} and @code{__DATE__}. Support for
1365 these tokens will occur even if the @samp{-fcpp} option is not
1366 supplied. A table of these identifiers and their data type and values
1370 Scope GNU Modula-2 token Data type and example value
1372 anywhere __LINE__ Constant Literal compatible
1373 with CARDINAL, INTEGER and WORD.
1376 anywhere __FILE__ Constant string compatible
1377 with parameter ARRAY OF CHAR or
1378 an ARRAY whose SIZE is >= string
1382 procedure __FUNCTION__ Constant string compatible
1383 with parameter ARRAY OF CHAR or
1384 an ARRAY whose SIZE is >= string
1388 module __FUNCTION__ Example
1389 "module hello initialization"
1391 anywhere __DATE__ Constant string compatible
1392 with parameter ARRAY OF CHAR or
1393 an ARRAY whose SIZE is >= string
1395 "Thu Apr 29 10:07:16 BST 2004"
1397 anywhere __COLUMN__ Gives a constant literal number
1398 determining the left hand column
1399 where the first _ appears in
1400 __COLUMN__. The left most column
1405 The preprocessor @samp{cpp} can be invoked via the @samp{-fcpp}
1406 command line option. This in turn invokes @samp{cpp} with the
1407 following arguments @samp{-traditional -lang-asm}. These options
1408 preserve comments and all quotations. @samp{gm2} treats a @samp{#}
1409 character in the first column as a preprocessor directive.
1411 For example here is a module which calls @code{FatalError}
1412 via the macro @code{ERROR}.
1417 FROM SYSTEM IMPORT ADR, SIZE ;
1418 FROM libc IMPORT exit, printf, malloc ;
1420 PROCEDURE FatalError (a, file: ARRAY OF CHAR;
1422 func: ARRAY OF CHAR) ;
1424 printf ("%s:%d:fatal error, %s, in %s\n",
1425 ADR (file), line, ADR (a), ADR (func)) ;
1429 #define ERROR(X) FatalError(X, __FILE__, __LINE__, __FUNCTION__)
1432 pc: POINTER TO CARDINAL;
1434 pc := malloc (SIZE (CARDINAL)) ;
1437 ERROR ('out of memory')
1442 Another use for the C preprocessor in Modula-2 might be to turn on
1443 debugging code. For example the library module
1444 @file{FormatStrings.mod} uses procedures from @file{DynamicStrings.mod}
1445 and to track down memory leaks it was useful to track the source file
1446 and line where each string was created. Here is a section of
1447 @file{FormatStrings.mod} which shows how the debugging code was
1448 enabled and disabled by adding @code{-fcpp} to the command line.
1451 FROM DynamicStrings IMPORT String, InitString, InitStringChar, Mark,
1452 ConCat, Slice, Index, char,
1453 Assign, Length, Mult, Dup, ConCatChar,
1454 PushAllocation, PopAllocationExemption,
1455 InitStringDB, InitStringCharStarDB,
1456 InitStringCharDB, MultDB, DupDB, SliceDB ;
1459 #define InitString(X) InitStringDB(X, __FILE__, __LINE__)
1460 #define InitStringCharStar(X) InitStringCharStarDB(X, __FILE__, \
1462 #define InitStringChar(X) InitStringCharDB(X, __FILE__, __LINE__)
1463 #define Mult(X,Y) MultDB(X, Y, __FILE__, __LINE__)
1464 #define Dup(X) DupDB(X, __FILE__, __LINE__)
1465 #define Slice(X,Y,Z) SliceDB(X, Y, Z, __FILE__, __LINE__)
1468 PROCEDURE doDSdbEnter ;
1473 PROCEDURE doDSdbExit (s: String) ;
1475 s := PopAllocationExemption (TRUE, s)
1478 PROCEDURE DSdbEnter ;
1482 PROCEDURE DSdbExit (s: String) ;
1487 #define DBsbEnter doDBsbEnter
1488 #define DBsbExit doDBsbExit
1491 PROCEDURE Sprintf1 (s: String; w: ARRAY OF BYTE) : String ;
1494 s := FormatString (HandleEscape (s), w) ;
1500 It is worth noting that the overhead of this code once @code{-fcpp} is
1501 not present and -O2 is used will be zero since the local empty
1502 procedures @code{DSdbEnter} and @code{DSdbExit} will be thrown away by
1503 the optimization passes of the GCC backend.
1505 @subsection Optional procedure parameter
1507 GNU Modula-2 allows the last parameter to a procedure or function
1508 parameter to be optional. For example in the ISO library
1509 @file{COROUTINES.def} the procedure @code{NEWCOROUTINE} is defined as
1510 having an optional fifth argument (@code{initProtection}) which, if
1511 absent, is automatically replaced by @code{NIL}.
1514 @findex NEWCOROUTINE
1515 PROCEDURE NEWCOROUTINE (procBody: PROC; workspace: SYSTEM.ADDRESS;
1516 size: CARDINAL; VAR cr: COROUTINE;
1517 [initProtection: PROTECTION = NIL]);
1519 (* Creates a new coroutine whose body is given by procBody,
1520 and returns the identity of the coroutine in cr.
1521 workspace is a pointer to the work space allocated to
1522 the coroutine; size specifies the size of this workspace
1523 in terms of SYSTEM.LOC.
1525 The optional fifth argument may contain a single parameter
1526 which specifies the initial protection level of the coroutine.
1530 The implementation module @file{COROUTINES.mod} implements this
1531 procedure using the following syntax:
1534 PROCEDURE NEWCOROUTINE (procBody: PROC; workspace: SYSTEM.ADDRESS;
1535 size: CARDINAL; VAR cr: COROUTINE;
1536 [initProtection: PROTECTION]);
1542 Note that it is illegal for this declaration to contain an initializer
1543 value for @code{initProtection}. However it is necessary to surround
1544 this parameter with the brackets @code{[} and @code{]}. This serves to
1545 remind the programmer that the last parameter was declared as optional
1546 in the definition module.
1548 Local procedures can be declared to have an optional final parameter
1549 in which case the initializer is mandatory in the implementation or
1552 GNU Modula-2 also provides additional fixed sized data types which
1553 are all exported from the @code{SYSTEM} module.
1554 @xref{The PIM system module, , ,gm2}.
1555 @xref{The ISO system module, , ,gm2}.
1557 @node Type compatibility, Unbounded by reference, Extensions, Using
1558 @section Type compatibility
1560 This section discuss the issues surrounding assignment, expression
1561 and parameter compatibility, their effect of the additional
1562 fixed sized datatypes and also their effect of run time checking.
1563 The data types supported by the compiler are:
1566 GNU Modula-2 scope switches
1567 =============================================
1580 SHORTCOMPLEX pervasive
1582 LONGCOMPLEX pervasive
1589 The following extensions are supported for
1590 most architectures (please check SYSTEM.def).
1591 =============================================
1616 The Modula-2 language categorizes compatibility between entities of
1617 possibly differing types into three sub components: expressions,
1618 assignments, and parameters. Parameter compatibility is further
1619 divided into two sections for pass by reference and pass by value
1622 For more detail on the Modula-2 type compatibility see the Modula-2
1623 ISO standard BS ISO/IEC 10514-1:1996 page 121-125. For detail on the
1624 PIM type compatibility see Programming in Modula-2 Edition 4 page 29,
1625 (Elementary Data Types).
1627 @subsection Expression compatibility
1629 Modula-2 restricts the types of expressions to the same type.
1630 Expression compatibility is a symmetric relation.
1632 For example two sub expressions of @code{INTEGER} and @code{CARDINAL}
1633 are not expression compatible
1634 (@uref{http://freepages.modula2.org/report4/modula-2.html} and ISO
1637 In GNU Modula-2 this rule is also extended across all fixed sized data
1638 types (imported from SYSTEM).
1640 @subsection Assignment compatibility
1642 This section discusses the assignment issues surrounding assignment
1643 compatibility of elementary types (@code{INTEGER}, @code{CARDINAL},
1644 @code{REAL} and @code{CHAR} for example). The information here is
1645 found in more detail in the Modula-2 ISO standard BS ISO/IEC
1646 10514-1:1996 page 122.
1648 Assignment compatibility exists between the same sized elementary
1651 Same type family of different sizes are
1652 also compatible as long as the @code{MAX(}type@code{)} and
1653 @code{MIN(}type@code{)} is known. So for example this includes the
1654 @code{INTEGER} family, @code{CARDINAL} family and the @code{REAL}
1657 The reason for this is that when the assignment is performed
1658 the compiler will check to see that the expression (on the right of
1659 the @code{:=}) lies within the range of the designator type (on the
1660 left hand side of the @code{:=}). Thus these ordinal types can be
1661 assignment compatible. However it does mean that @code{WORD32} is not
1662 compatible with @code{WORD16} as @code{WORD32} does not have a minimum
1663 or maximum value and therefore cannot be checked. The compiler does
1664 not know which of the two bytes from @code{WORD32} should be copied
1665 into @code{WORD16} and which two should be ignored. Currently the
1666 types @code{BITSET8}, @code{BITSET16} and @code{BITSET32} are
1667 assignment incompatible. However this restriction maybe lifted when
1668 further run time checking is achieved.
1670 Modula-2 does allow @code{INTEGER} to be assignment compatible with
1671 @code{WORD} as they are the same size. Likewise GNU Modula-2 allows
1672 @code{INTEGER16} to be compatible with @code{WORD16} and the same for
1673 the other fixed sized types and their sized equivalent in either
1674 @code{WORD}n, @code{BYTE} or @code{LOC} types. However it prohibits
1675 assignment between @code{WORD} and @code{WORD32} even though on many
1676 systems these sizes will be the same. The reasoning behind this rule
1677 is that the extended fixed sized types are meant to be used by
1678 applications requiring fixed sized data types and it is more portable
1679 to forbid the blurring of the boundaries between fixed sized and
1680 machine dependent sized types.
1682 Intermediate code run time checking is always generated by the front
1683 end. However this intermediate code is only translated into actual
1684 code if the appropriate command line switches are specified. This
1685 allows the compiler to perform limited range checking at compile time.
1686 In the future it will allow the extensive GCC optimizations to
1687 propagate constant values through to the range checks which if they
1688 are found to exceed the type range will result in a compile time
1691 @subsection Parameter compatibility
1693 Parameter compatibility is divided into two areas, pass by value and
1694 pass by reference (@code{VAR}). In the case of pass by value the
1695 rules are exactly the same as assignment. However in the second case,
1696 pass by reference, the actual parameter and formal parameter must be
1697 the same size and family. Furthermore @code{INTEGER} and
1698 @code{CARDINAL}s are not treated as compatible in the pass by
1701 The types @code{BYTE}, @code{LOC}, @code{WORD} and @code{WORD}n
1702 derivatives are assignment and parameter compatible with any data type
1705 @node Unbounded by reference, Building a shared library, Type compatibility, Using
1706 @section Unbounded by reference
1708 This section documents a GNU Modula-2 compiler switch which implements
1709 a language optimization surrounding the implementation of unbounded
1710 arrays. In GNU Modula-2 the unbounded array is implemented by
1711 utilizing an internal structure @code{struct @{dataType *address,
1712 unsigned int high@}}. So given the Modula-2 procedure declaration:
1715 PROCEDURE foo (VAR a: ARRAY OF dataType) ;
1721 it is translated into GCC @code{tree}s, which can be represented
1722 in their C form thus:
1725 void foo (struct @{dataType *address, unsigned int high@} a)
1727 if (a.address[2] == /* etc */
1731 Whereas if the procedure @code{foo} was declared as:
1734 PROCEDURE foo (a: ARRAY OF dataType) ;
1740 then it is implemented by being translated into the following
1741 GCC @code{tree}s, which can be represented in their C form thus:
1744 void foo (struct @{dataType *address, unsigned int high@} a)
1746 dataType *copyContents = (dataType *)alloca (a.high+1);
1747 memcpy(copyContents, a.address, a.high+1);
1748 a.address = copyContents;
1750 if (a.address[2] == /* etc */
1754 This implementation works, but it makes a copy of each non VAR
1755 unbounded array when a procedure is entered. If the unbounded array
1756 is not changed during procedure @code{foo} then this implementation
1757 will be very inefficient. In effect Modula-2 lacks the @code{REF}
1758 keyword of Ada. Consequently the programmer maybe tempted to
1759 sacrifice semantic clarity for greater efficiency by declaring the
1760 parameter using the @code{VAR} keyword in place of @code{REF}.
1762 The @code{-funbounded-by-reference} switch instructs the compiler to
1763 check and see if the programmer is modifying the content of any
1764 unbounded array. If it is modified then a copy will be made upon
1765 entry into the procedure. Conversely if the content is only read and
1766 never modified then this non @code{VAR} unbounded array is a candidate
1767 for being passed by reference. It is only a candidate as it is still
1768 possible that passing this parameter by reference could alter the
1769 meaning of the source code. For example consider the following case:
1772 PROCEDURE StrConCat (VAR a: ARRAY OF CHAR; b, c: ARRAY OF CHAR) ;
1774 (* code which performs string a := b + c *)
1779 a: ARRAY [0..3] OF CHAR ;
1786 In the code above we see that the same parameter, @code{a}, is being
1787 passed three times to @code{StrConCat}. Clearly even though parameters
1788 @code{b} and @code{c} are never modified it would be incorrect to
1789 implement them as pass by reference. Therefore the compiler checks to
1790 see if any non @code{VAR} parameter is type compatible with any
1791 @code{VAR} parameter and if so it generates run time procedure entry
1792 checks to determine whether the contents of parameters @code{b} or
1793 @code{c} matches the contents of @code{a}. If a match is detected
1794 then a copy is made and the @code{address} in the unbounded
1795 @code{struct}ure is modified.
1797 The compiler will check the address range of each candidate against
1798 the address range of any @code{VAR} parameter, providing they are type
1799 compatible. For example consider:
1802 PROCEDURE foo (a: ARRAY OF BYTE; VAR f: REAL) ;
1818 Here we see that although parameter, @code{a}, is a candidate for the
1819 passing by reference, it would be incorrect to use this
1820 transformation. Thus the compiler detects that parameters, @code{a}
1821 and @code{f} are type compatible and will produce run time checking
1822 code to test whether the address range of their respective contents
1825 @node Building a shared library, Interface for Python, Unbounded by reference, Using
1826 @section Building a shared library
1828 This section describes building a tiny shared library implemented in
1829 Modula-2 and built with @file{libtool}. Suppose a project consists of
1830 two definition modules and two implementation modules and a program
1831 module @file{a.def}, @file{a.mod}, @file{b.def}, @file{b.mod} and
1832 @file{c.mod}. The first step is to compile the modules using position
1833 independent code. This can be achieved by the following three
1837 libtool --tag=CC --mode=compile gm2 -g -c a.mod -o a.lo
1838 libtool --tag=CC --mode=compile gm2 -g -c b.mod -o b.lo
1839 libtool --tag=CC --mode=compile gm2 -g -c c.mod -o c.lo
1842 The second step is to generate the shared library initialization and
1843 finalization routines. We can do this by asking gm2 to generate a
1844 list of dependent modules and then use this to generate the scaffold.
1845 We also must compile the scaffold.
1848 gm2 -c -g -fmakelist c.mod
1849 gm2 -c -g -fmakeinit -fshared c.mod
1850 libtool --tag=CC --mode=compile g++ -g -c c_m2.cpp -o c_m2.lo
1853 The third step is to link all these @file{.lo} files.
1856 libtool --mode=link gcc -g c_m2.lo a.lo b.lo c.lo \
1858 -rpath `pwd` -lgm2 -lstdc++ -lm -o libabc.la
1861 At this point the shared library @file{libabc.so} will have been
1862 created inside the directory @file{.libs}.
1864 @node Interface for Python, Producing a Python module, Building a shared library, Using
1865 @section How to produce swig interface files
1867 This section describes how Modula-2 implementation modules can be
1868 called from Python (and other scripting languages such as TCL and
1869 Perl). GNU Modula-2 can be instructed to create a swig interface when
1870 it is compiling an implementation module. Swig then uses the
1871 interface file to generate all the necessary wrapping to that the
1872 desired scripting language may access the implementation module.
1874 Here is an example of how you might call upon the services of the
1875 Modula-2 library module @code{NumberIO} from Python3.
1877 The following commands can be used to generate the Python3 module:
1880 export src=@samp{directory to the sources}
1881 export prefix=@samp{directory to where the compiler is installed}
1882 gm2 -I$@{src@} -c -g -fswig $@{src@}/../../../gm2-libs/NumberIO.mod
1883 gm2 -I$@{src@} -c -g -fmakelist $@{src@}/../../../gm2-libs/NumberIO.mod
1885 gm2 -I$@{src@} -c -g -fmakeinit -fshared \
1886 $@{src@}/../../../gm2-libs/NumberIO.mod
1888 swig -c++ -python3 NumberIO.i
1890 libtool --mode=compile g++ -g -c -I$@{src@} NumberIO_m2.cpp \
1893 libtool --tag=CC --mode=compile gm2 -g -c \
1894 -I$@{src@}../../../gm2-libs \
1895 $@{src@}/../../../gm2-libs/NumberIO.mod -o NumberIO.lo
1897 libtool --tag=CC --mode=compile g++ -g -c NumberIO_wrap.cxx \
1898 -I/usr/include/python3 -o NumberIO_wrap.lo
1900 libtool --mode=link gcc -g NumberIO_m2.lo NumberIO_wrap.lo \
1901 -L$@{prefix@}/lib64 \
1902 -rpath `pwd` -lgm2 -lstdc++ -lm -o libNumberIO.la
1904 cp .libs/libNumberIO.so _NumberIO.so
1907 The first four commands, generate the swig interface file
1908 @file{NumberIO.i} and python wrap files @file{NumberIO_wrap.cxx} and
1909 @file{NumberIO.py}. The next three @file{libtool} commnads compile
1910 the C++ and Modula-2 source code into @file{.lo} objects. The last
1911 @file{libtool} command links all the @file{.lo} files into a
1912 @file{.la} file and includes all shared library dependencies.
1914 Now it is possible to run the following Python script
1915 (called @file{testnum.py}):
1920 print ("1234 x 2 =", NumberIO.NumberIO_StrToInt("1234")*2)
1926 $ python3 testnum.py
1930 @xref{Producing a Python module, , ,gm2} for another example which
1931 uses the @code{UNQUALIFIED} keyword to reduce the module name clutter
1932 from the viewport of Python3.
1934 @subsection Limitations of automatic generated of Swig files
1936 This section discusses the limitations of automatically generating
1937 swig files. From the previous example we see that the module
1938 @code{NumberIO} had a swig interface file @file{NumberIO.i}
1939 automatically generated by the compiler. If we consider three of the
1940 procedure definitions in @file{NumberIO.def} we can see the
1941 success and limitations of the automatic interface generation.
1944 PROCEDURE StrToHex (a: ARRAY OF CHAR; VAR x: CARDINAL) ;
1945 PROCEDURE StrToInt (a: ARRAY OF CHAR; VAR x: INTEGER) ;
1946 PROCEDURE ReadInt (VAR x: CARDINAL) ;
1949 Below are the swig interface prototypes:
1952 extern void NumberIO_StrToHex (char *_m2_address_a,
1953 int _m2_high_a, unsigned int *OUTPUT);
1954 /* parameters: x is known to be an OUTPUT */
1955 extern void NumberIO_StrToInt (char *_m2_address_a,
1956 int _m2_high_a, int *OUTPUT);
1957 /* parameters: x is guessed to be an OUTPUT */
1958 extern void NumberIO_ReadInt (int *x);
1959 /* parameters: x is unknown */
1962 In the case of @code{StrToHex} it can be seen that the compiler
1963 detects that the last parameter is an output. It explicitly tells
1964 swig this by using the parameter name @code{OUTPUT} and in the
1965 following comment it informs the user that it knows this to be an
1966 output parameter. In the second procedure @code{StrToInt} it marks
1967 the final parameter as an output, but it tells the user that this is
1968 only a guess. Finally in @code{ReadInt} it informs the user that
1969 it does not know whether the parameter, @code{x}, is an output, input
1970 or an inout parameter.
1972 The compiler decides whether to mark a parameter as either:
1973 @code{INPUT}, @code{OUTPUT} or @code{INOUT} if it is read before
1974 written or visa versa in the first basic block. At this point
1975 it will write output that the parameter is known. If it is not
1976 read or written in the first basic block then subsequent basic blocks
1977 are searched and the result is commented as a guess. Finally if
1978 no read or write occurs then the parameter is commented as unknown.
1979 However, clearly it is possible to fool this mechanism. Nevertheless
1980 automatic generation of implementation module into swig interface files
1981 was thought sufficiently useful despite these limitations.
1983 In conclusion it would be wise to check all parameters in any
1984 automatically generated swig interface file. Furthermore you can
1985 force the automatic mechanism to generate correct interface files by
1986 reading or writing to the @code{VAR} parameter in the first basic
1987 block of a procedure.
1989 @node Producing a Python module, Interface to C, Interface for Python, Using
1990 @section How to produce a Python module
1992 This section describes how it is possible to produce a Python module
1993 from Modula-2 code. There are a number of advantages to this
1994 approach, it ensures your code reaches a wider audience, maybe it is
1995 easier to initialize your application in Python.
1997 The example application here is a pedagogical two dimensional gravity
1998 next event simulation. The Python module needs to have a clear API
1999 which should be placed in a single definition module. Furthermore the
2000 API should only use fundamental pervasive data types and strings.
2001 Below the API is contained in the file @file{twoDsim.def}:
2004 DEFINITION MODULE twoDsim ;
2006 EXPORT UNQUALIFIED gravity, box, poly3, poly5, poly6, mass,
2007 fix, circle, pivot, velocity, accel, fps,
2008 replayRate, simulateFor ;
2010 gravity - turn on gravity at: g m^2
2013 PROCEDURE gravity (g: REAL) ;
2017 box - place a box in the world at (x0,y0),(x0+i,y0+j)
2020 PROCEDURE box (x0, y0, i, j: REAL) : CARDINAL ;
2024 poly3 - place a triangle in the world at:
2025 (x0,y0),(x1,y1),(x2,y2)
2028 PROCEDURE poly3 (x0, y0, x1, y1, x2, y2: REAL) : CARDINAL ;
2032 poly5 - place a pentagon in the world at:
2033 (x0,y0),(x1,y1),(x2,y2),(x3,y3),(x4,y4)
2036 PROCEDURE poly5 (x0, y0, x1, y1,
2037 x2, y2, x3, y3, x4, y4: REAL) : CARDINAL ;
2041 poly6 - place a hexagon in the world at:
2042 (x0,y0),(x1,y1),(x2,y2),(x3,y3),(x4,y4),(x5,y5)
2045 PROCEDURE poly6 (x0, y0, x1, y1,
2047 x4, y4, x5, y5: REAL) : CARDINAL ;
2051 mass - specify the mass of an object and return the, id.
2054 PROCEDURE mass (id: CARDINAL; m: REAL) : CARDINAL ;
2058 fix - fix the object to the world.
2061 PROCEDURE fix (id: CARDINAL) : CARDINAL ;
2065 circle - adds a circle to the world. Center
2066 defined by: x0, y0 radius, r.
2069 PROCEDURE circle (x0, y0, r: REAL) : CARDINAL ;
2073 velocity - give an object, id, a velocity, vx, vy.
2076 PROCEDURE velocity (id: CARDINAL; vx, vy: REAL) : CARDINAL ;
2080 accel - give an object, id, an acceleration, ax, ay.
2083 PROCEDURE accel (id: CARDINAL; ax, ay: REAL) : CARDINAL ;
2087 fps - set frames per second.
2090 PROCEDURE fps (f: REAL) ;
2094 replayRate - set frames per second during replay.
2097 PROCEDURE replayRate (f: REAL) ;
2101 simulateFor - render for, t, seconds.
2104 PROCEDURE simulateFor (t: REAL) ;
2110 The keyword @code{UNQUALIFIED} can be used to ensure that the
2111 compiler will provide externally accessible functions
2112 @code{gravity}, @code{box}, @code{poly3}, @code{poly5}, @code{poly6},
2113 @code{mass}, @code{fix}, @code{circle}, @code{pivot}, @code{velocity},
2114 @code{accel}, @code{fps}, @code{replayRate}, @code{simulateFor}
2115 rather than name mangled alternatives.
2116 Hence in our Python3 application we could write:
2119 #!/usr/bin/env python3
2121 from twoDsim import *
2123 b = box (0.0, 0.0, 1.0, 1.0)
2125 c1 = circle (0.7, 0.7, 0.05)
2126 c1 = mass (c1, 0.01)
2127 c2 = circle (0.7, 0.1, 0.05)
2128 c2 = mass (c2, 0.01)
2133 print ("creating frames")
2138 print ("exception raised")
2141 which accesses the various functions defined and implemented by the
2142 module @code{twoDsim}. The Modula-2 source code is compiled via:
2145 $ gm2 -g -fiso -c -fswig twoDsim.mod
2146 $ gm2 -g -fiso -c -fmakelist twoDsim.mod
2147 $ gm2 -g -fiso -c -fmakeinit twoDsim.mod
2150 The first command both compiles the source file creating
2151 @file{twoDsim.o} and produces a swig interface file @file{swig.i}. We
2152 now use @code{swig} and @code{g++} to produce and compile the
2156 $ libtool --mode=compile g++ -g -c twoDsim_m2.cpp -o twoDsim_m2.lo
2157 $ swig -c++ -python3 twoDsim.i
2158 $ libtool --mode=compile g++ -c -fPIC twoDsim_wrap.cxx \
2159 -I/usr/include/python3 -o twoDsim_wrap.lo
2160 $ libtool --mode=compile gm2 -g -fPIC -fiso -c deviceGnuPic.mod
2161 $ libtool --mode=compile gm2 -g -fPIC -fiso -c roots.mod
2162 $ libtool --mode=compile gm2 -g -fPIC -fiso -c -fswig \
2163 twoDsim.mod -o twoDsim.lo
2166 Finally the application is linked into a shared library:
2169 $ libtool --mode=link gcc -g twoDsim_m2.lo twoDsim_wrap.lo \
2170 roots.lo deviceGnuPic.lo \
2171 -L$@{prefix@}/lib64 \
2172 -rpath `pwd` -lgm2 -lstdc++ -lm -o libtwoDsim.la
2173 cp .libs/libtwoDsim.so _twoDsim.so
2176 The library name must start with @code{_} to comply with the Python3
2177 module naming scheme.
2179 @node Interface to C, Assembly language, Producing a Python module, Using
2180 @section Interfacing GNU Modula-2 to C
2182 The GNU Modula-2 compiler tries to use the C calling convention
2183 wherever possible however some parameters have no C equivalent and
2184 thus a language specific method is used. For example unbounded arrays
2185 are passed as a @code{struct @{void *address, unsigned int high@}} and
2186 the contents of these arrays are copied by callee functions when they
2187 are declared as non @code{VAR} parameters. The @code{VAR} equivalent
2188 unbounded array parameters need no copy, but still use the
2189 @code{struct} representation.
2191 The recommended method of interfacing GNU Modula-2 to C is by telling
2192 the definition module that the implementation is in the C language.
2193 This is achieved by using the tokens @code{DEFINITION MODULE FOR "C"}.
2194 Here is an example @file{libprintf.def}.
2197 DEFINITION MODULE FOR "C" libprintf ;
2199 EXPORT UNQUALIFIED printf ;
2201 PROCEDURE printf (a: ARRAY OF CHAR; ...) : [ INTEGER ] ;
2206 the @code{UNQUALIFIED} keyword in the definition module informs
2207 GNU Modula-2 not to prefix the module name to exported references
2210 The @code{printf} declaration states that the first parameter
2211 semantically matches @code{ARRAY OF CHAR} but since the module is for
2212 the C language it will be mapped onto @code{char *}. The token
2213 @code{...} indicates a variable number of arguments (varargs) and all
2214 parameters passed here are mapped onto their C equivalents. Arrays and
2215 constant strings are passed as pointers. Lastly @code{[ INTEGER ]}
2216 states that the caller can ignore the function return result if desired.
2218 The hello world program can be rewritten as:
2223 FROM libprintf IMPORT printf ;
2226 printf ("hello world\n")
2230 and it can be compiled by:
2232 @samp{gm2 -g hello.mod -lc}
2234 In reality the @samp{-lc} is redundant as libc is always included in the
2235 linking process. It is shown here to emphasize that the C library or
2236 object file containing @code{printf} must be present. The search path
2237 for modules can be changed by using @samp{-I}.
2239 If a procedure function is declared using varargs then some parameter
2240 values are converted. The table below summarizes the default conversions
2241 and default types used.
2244 Actual Parameter | Default conversion | Type of actual
2246 ===============================================================
2247 123 | none | long long int
2248 "hello world" | none | const char *
2249 a: ARRAY OF CHAR | ADR (a) | char *
2250 a: ARRAY [0..5] OF CHAR| ADR (a) | char *
2251 3.14 | none | long double
2254 If you wish to pass @code{int} values then you should explicitly
2255 convert the constants using one of the conversion mechanisms.
2256 For example: @code{INTEGER(10)} or @code{VAL(INTEGER, 10)} or
2257 @code{CAST(INTEGER, 10)}.
2259 @node Assembly language, Alignment, Interface to C, Using
2260 @section Interface to assembly language
2262 The interface for GNU Modula-2 to assembly language is almost
2263 identical to GNU C. The only alterations are that the keywords
2264 @code{asm} and @code{volatile} are in capitals, following the Modula-2
2267 A simple, but highly non optimal, example is given below. Here we want
2268 to add the two @code{CARDINAL}s @code{foo} and @code{bar} together and
2269 return the result. The target processor is assumed to be executing
2270 the x86_64 instruction set.
2273 PROCEDURE Example (foo, bar: CARDINAL) : CARDINAL ;
2277 ASM VOLATILE ("movq %1,%%rax; addq %2,%%rax; movq %%rax,%0"
2278 : "=rm" (myout) (* outputs *)
2279 : "rm" (foo), "rm" (bar) (* inputs *)
2280 : "rax") ; (* we trash *)
2285 For a full description of this interface we refer the reader to the GNU C manual.
2287 @xref{Extended Asm, ,Extensions to the C Language Family,gcc}.
2289 The same example can be written using the newer extensions of naming
2290 the operands rather than using numbered arguments.
2293 PROCEDURE Example (foo, bar: CARDINAL) : CARDINAL ;
2298 "movq %[left],%%rax; addq %[right],%%rax; movq %%rax,%[output]"
2299 : [output] "=rm" (myout) (* outputs *)
2300 : [left] "rm" (foo), [right] "rm" (bar) (* inputs *)
2301 : "rax") ; (* we trash *)
2306 Both examples generate exactly the same code. It is worth noting that
2307 the specifier ``rm'' indicates that the operand can be either a
2308 register or memory. Of course you must choose an instruction which
2309 can take either, but this allows the compiler to take make more
2310 efficient choices depending upon the optimization level given to the
2313 @node Alignment, Packed, Assembly language, Using
2314 @section Data type alignment
2316 GNU Modula-2 allows you to specify alignment for types and variables.
2317 The syntax for alignment is to use the ISO pragma directives @code{<*}
2318 @code{bytealignment (} expression @code{)} and @code{*>}. These directives
2319 can be used after type and variable declarations.
2321 The ebnf of the alignment production is:
2324 Alignment := [ ByteAlignment ] =:
2325 ByteAlignment := '<*' AttributeExpression '*>' =:
2326 AlignmentExpression := "(" ConstExpression ")" =:
2329 The @code{Alignment} ebnf statement may be used during construction of
2330 types, records, record fields, arrays, pointers and variables. Below
2331 is an example of aligning a type so that the variable @code{bar} is
2332 aligned on a 1024 address.
2338 foo = INTEGER <* bytealignment(1024) *> ;
2347 The next example aligns a variable on a 1024 byte boundary.
2354 z : ARRAY [0..255] OF INTEGER <* bytealignment(1024) *> ;
2359 Here the example aligns a pointer on a 1024 byte boundary.
2364 FROM SYSTEM IMPORT ADR ;
2365 FROM libc IMPORT exit ;
2369 z : POINTER TO INTEGER <* bytealignment(1024) *> ;
2371 IF ADR(z) MOD 1024=0
2380 In example @code{align5} record field @code{y} is aligned on a 1024
2386 FROM SYSTEM IMPORT ADR ;
2387 FROM libc IMPORT exit ;
2392 y: CHAR <* bytealignment(1024) *> ;
2397 IF ADR(r.y) MOD 1024=0
2406 In the example below module @code{align6} declares @code{foo} as an
2407 array of 256 @code{INTEGER}s. The array @code{foo} is aligned on a
2413 FROM SYSTEM IMPORT ADR ;
2414 FROM libc IMPORT exit ;
2417 foo = ARRAY [0..255] OF INTEGER <* bytealignment(1024) *> ;
2423 IF ADR(z) MOD 1024=0
2432 @node Packed, Built-ins, Alignment, Using
2433 @section Packing data types
2435 The pragma @code{<* bytealignment(0) *>} can be used to specify that
2436 the fields within a @code{RECORD} are to be packed. Currently this
2437 only applies to fields which are declared as subranges, ordinal types
2438 and enumerated types. Here is an example of how two subranges might
2439 be packed into a byte.
2447 <* bytealignment(0) *>
2454 Notice that the user has specified that in between fields @code{x} and
2455 @code{y} there are two bits unused.
2457 Now the user wishes to create a record with byte numbers zero and one
2458 occupied and then an @code{INTEGER32} field which is four byte
2459 aligned. In this case byte numbers two and three will be unused. The
2460 pragma @code{bytealignment} can be issued at the start of the record
2461 indicating the default alignment for the whole record and this can be
2462 overridden by individual fields if necessary.
2466 <* bytealignment (1) *> ;
2468 x: INTEGER32 <* bytealignment(4) *> ;
2472 In the following example the user has specified that a record has two
2473 fields @code{p} and @code{q} but that there are three bytes unused between
2478 <* bytealignment(1) *>
2480 <* bytesunused(3) *>
2485 The pragma @code{<* bytesunused(x) *>} can only be used if the current
2486 field is on a byte boundary. There is also a @code{SYSTEM} pseudo
2487 procedure function @code{TBITSIZE(T)} which returns the minimum number of
2488 bits necessary to represent type @code{T}.
2490 Another example of packing record bit fields is given below:
2495 FROM libc IMPORT exit ;
2498 colour = (red, blue, green, purple, white, black) ;
2500 soc = PACKEDSET OF colour ;
2503 <* bytealignment(0) *>
2517 r.x := soc@{blue@} ;
2525 Here we see that the total size of this record is one byte and consists
2526 of a six bit set type followed by a 2 bit integer subrange.
2528 @node Built-ins, The PIM system module, Packed, Using
2529 @section Accessing GNU Modula-2 Built-ins
2531 This section describes the built-in constants and functions defined in
2532 GNU Modula-2. The following compiler constants can be accessed using
2533 the @code{__ATTRIBUTE__} @code{__BUILTIN__} keywords. These are not
2534 part of the Modula-2 language and they may differ depending upon the
2535 target architecture but they provide a method whereby common
2536 libraries can interface to a different underlying architecture.
2538 The built-in constants are: @code{BITS_PER_UNIT}, @code{BITS_PER_WORD},
2539 @code{BITS_PER_CHAR} and @code{UNITS_PER_WORD}. They are integrated into
2540 GNU Modula-2 by an extension to the @code{ConstFactor} rule:
2543 ConstFactor := ConstQualidentOrSet | Number | ConstString |
2544 "(" ConstExpression ")" | "NOT" ConstFactor |
2547 ConstAttribute := "__ATTRIBUTE__" "__BUILTIN__" "(" "(" Ident ")" ")" =:
2550 Here is an example taken from the ISO library @code{SYSTEM.def}:
2554 BITSPERLOC = __ATTRIBUTE__ __BUILTIN__ ((BITS_PER_UNIT)) ;
2555 LOCSPERWORD = __ATTRIBUTE__ __BUILTIN__ ((UNITS_PER_WORD)) ;
2558 Built-in functions are transparent to the end user. All built-in
2559 functions are declared in @code{DEFINITION MODULE}s and are imported
2560 as and when required. Built-in functions are declared in definition
2561 modules by using the @code{__BUILTIN__} keyword. Here is a section of
2562 the ISO library @code{LongMath.def} which demonstrates this feature.
2565 PROCEDURE __BUILTIN__ sqrt (x: LONGREAL): LONGREAL;
2566 (* Returns the square root of x *)
2569 This indicates that the function @code{sqrt} will be implemented using
2570 the gcc built-in maths library. If gcc cannot utilize the built-in
2571 function (for example if the programmer requested the address of
2572 @code{sqrt}) then code is generated to call the alternative function
2573 implemented in the @code{IMPLEMENTATION} @code{MODULE}.
2575 Sometimes a function exported from the @code{DEFINITION} @code{MODULE}
2576 will have a different name from the built-in function within gcc. In
2577 such cases the mapping between the GNU Modula-2 function name and the
2578 gcc name is expressed using the keywords @code{__ATTRIBUTE__}
2579 @code{__BUILTIN__} @code{((Ident))}. For example the function
2580 @code{sqrt} in @code{LongMath.def} maps onto the gcc built-in function
2581 @code{sqrtl} and this is expressed as:
2584 PROCEDURE __ATTRIBUTE__ __BUILTIN__ ((sqrtl)) sqrt
2585 (x: LONGREAL) : LONGREAL;
2586 (* Returns the positive square root of x *)
2589 The following module @code{Builtins.def} enumerates the list of
2590 built-in functions which can be accessed in GNU Modula-2. It also
2591 serves to define the parameter and return value for each function:
2593 @include m2/Builtins.texi
2595 Although this module exists and will result in the generation of
2596 in-line code if optimization flags are passed to GNU Modula-2, users
2597 are advised to utilize the same functions from more generic libraries.
2598 The built-in mechanism will be applied to these generic
2599 libraries where appropriate. Note for the mathematical routines to
2600 be in-lined you need to specify the @samp{-ffast-math -O} options.
2602 @node The PIM system module, The ISO system module, Built-ins, Using
2603 @section The PIM system module
2605 @include m2/SYSTEM-pim.texi
2607 The different dialects of Modula-2 PIM-[234] and ISO Modula-2 declare
2608 the function @code{SIZE} in different places. PIM-[34] and ISO
2609 Modula-2 declare @code{SIZE} as a pervasive function (declared in the
2610 base module). PIM-2 defined @code{SIZE} in the @code{SYSTEM} module
2613 GNU Modula-2 allows users to specify the dialect of Modula-2 by using
2614 the @code{-fiso} and @code{-fpim2} command line switches.
2616 The data types @code{CSIZE_T} and @code{CSSIZE_T} are also exported from
2617 the @code{SYSTEM} module. The type @code{CSIZE_T} is unsigned and is
2618 mapped onto the target C data type @code{size_t} whereas the type
2619 @code{CSSIZE_T} is mapped onto the signed C data type @code{ssize_t}.
2621 It is anticipated that these should only be used to provide cross
2622 platform definition modules for C libraries.
2624 There are also a variety of fixed sized @code{INTEGER} and
2625 @code{CARDINAL} types. The variety of the fixed sized types will
2626 depend upon the target architecture.
2628 @node The ISO system module, Release map, The PIM system module, Using
2629 @section The ISO system module
2631 @include m2/SYSTEM-iso.texi
2633 The data types @code{CSIZE_T} and @code{CSSIZE_T} are also exported from
2634 the @code{SYSTEM} module. The type @code{CSIZE_T} is unsigned and is
2635 mapped onto the target C data type @code{size_t} whereas the type
2636 @code{CSSIZE_T} is mapped onto the signed C data type @code{ssize_t}.
2638 It is anticipated that these should only be used to provide cross
2639 platform definition modules for C libraries.
2641 There are also a variety of fixed sized @code{INTEGER} and
2642 @code{CARDINAL} types. The variety of the fixed sized types will
2643 depend upon the target architecture.
2645 @node Release map, Documentation, The ISO system module, Using
2646 @section Release map
2648 GNU Modula-2 is now part of GCC and therefore will adopt the GCC
2649 release schedule. It is intended that GNU Modula-2 implement more of
2650 the GCC builtins (vararg access) and GCC features.
2652 There is an intention to implement the ISO generics and the M2R10
2653 dialect of Modula-2. It will also implement all language changes. If
2654 you wish to see something different please email
2655 @email{gm2@@nongnu.org} with your ideas.
2657 @node Documentation, Regression tests, Release map, Using
2658 @section Documentation
2660 The GNU Modula-2 documentation is available on line
2661 @url{https://www.nongnu.org/gm2/homepage.html,at the gm2 homepage}
2662 or in the pdf, info, html file format.
2664 @node Regression tests, Limitations, Documentation, Using
2665 @section Regression tests for gm2 in the repository
2667 The regression testsuite can be run from the gcc build directory:
2674 which runs the complete testsuite for all compilers using 24 parallel
2675 invocations of the compiler. Individual language testsuites can be
2676 run by specifying the language, for example the Modula-2 testsuite can
2681 $ make check-m2 -j 24
2684 Finally the results of the testsuite can be emailed to the
2685 @url{https://gcc.gnu.org/lists.html, gcc-testresults} list using the
2686 @file{test_summary} script found in the gcc source tree:
2689 $ @samp{directory to the sources}/contrib/test_summary
2692 @node Limitations, Objectives, Regression tests, Using
2693 @section Limitations
2695 Logitech compatibility library is incomplete. The principle modules
2696 for this platform exist however for a comprehensive list of completed
2697 modules please check the documentation
2700 @node Objectives, FAQ, Limitations, Using
2706 The intention of GNU Modula-2 is to provide a production Modula-2
2710 It should support all Niklaus Wirth PIM Dialects [234] and also ISO
2711 Modula-2 including a re-implementation of all the ISO modules.
2714 There should be an easy interface to C.
2717 Exploit the features of GCC.
2720 Listen to the requests of the users.
2723 @node FAQ, Community, Objectives, Using
2726 @subsection Why use the C++ exception mechanism in GCC, rather than a bespoke Modula-2 mechanism?
2728 The C++ mechanism is tried and tested, it also provides GNU Modula-2
2729 with the ability to link with C++ modules and via swig it can raise
2732 @node Community, Other languages, FAQ, Using
2735 You can subscribe to the GNU Modula-2 mailing by sending an
2737 @email{gm2-subscribe@@nongnu.org}
2739 @url{http://lists.nongnu.org/mailman/listinfo/gm2}.
2740 The mailing list contents can be viewed
2741 @url{http://lists.gnu.org/archive/html/gm2}.
2743 @node Other languages, , Community, Using
2744 @section Other languages for GCC
2746 These exist and can be found on the frontends web page on the
2747 @uref{http://gcc.gnu.org/frontends.html, gcc web site}.
2749 @node License, Copying, Using, Top
2750 @section License of GNU Modula-2
2752 GNU Modula-2 is free software, the compiler is held under the GPL v3
2753 @uref{http://www.gnu.org/licenses/gpl.txt},
2754 its libraries (pim, iso and Logitech compatible) are under the
2755 GPL v3 with the GCC run time library exception clause.
2757 Under Section 7 of GPL version 3, you are granted additional
2758 permissions described in the GCC Runtime Library Exception, version
2759 3.1, as published by the Free Software Foundation.
2761 You should have received a copy of the GNU General Public License and
2762 a copy of the GCC Runtime Library Exception along with this program;
2763 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
2764 <http://www.gnu.org/licenses/>.
2766 More information on how these licenses work is available
2767 @uref{http://www.gnu.org/licenses/licenses.html} on the GNU web site.
2769 @c Copying node is inside the gpl_v3.texi
2770 @include gpl_v3.texi
2772 @node Contributing, Internals, Copying, Top
2773 @section Contributing to GNU Modula-2
2775 Please do and please read the GNU Emacs info under
2778 * Standards: (standards). GNU coding standards.
2779 * Intellectual Property:: Keeping Free Software Free
2780 * Reading Non-Free Code:: Referring to Proprietary Programs
2781 * Contributions:: Accepting Contributions
2784 You might consider joining the GM2 Mailing list before you start
2785 coding. The mailing list may be subscribed via a web interface
2786 @uref{http://lists.nongnu.org/mailman/listinfo/gm2} or via email
2787 @email{gm2-subscribe@@nongnu.org}.
2789 Many thanks and enjoy your coding!
2791 @node Internals, EBNF, Contributing, Top
2793 This section is still being written.
2794 @c @include gm2-internals.texi
2796 @node EBNF, Libraries, Internals, Top
2797 @chapter EBNF of GNU Modula-2
2799 This chapter contains the EBNF of GNU Modula-2. This grammar currently
2800 supports both PIM and ISO dialects. The rules here are automatically
2801 extracted from the crammer files in GNU Modula-2 and serve to document
2802 the syntax of the extensions described earlier and how they fit in
2803 with the base language.
2805 Note that the first six productions are built into the lexical analysis
2808 @include m2/gm2-ebnf.texi
2810 @node Libraries, Indices, EBNF, Top
2811 @chapter PIM and ISO library definitions
2813 This chapter contains M2F, PIM and ISO libraries.
2815 @include m2/gm2-libs.texi
2817 @node Indices, , Libraries, Top
2822 * Contents:: Section and subsections.
2823 * Functions:: Function, constants, types, ebnf indices.
2826 @node Contents, Functions, ,
2827 @section Section and subsections
2830 @node Functions, , Contents,
2831 @section Function, constants, types, ebnf indices.