Debian Codegraph @

gcc/doc/gm2.texi

raw
1 \input texinfo
2 @c -*-texinfo-*-
3 @c Copyright (C) 2001-2023 Free Software Foundation, Inc.
4 @c This is part of the GM2 manual.
5
6 @c User level documentation for GNU Modula-2
7 @c
8 @c header
9
10 @setfilename gm2.info
11 @settitle The GNU Modula-2 Compiler
12
13 @set version-python 3.5
14
15 @include gcc-common.texi
16
17 @c Copyright years for this manual.
18 @set copyrights-gm2 1999-2023
19
20 @copying
21 @c man begin COPYRIGHT
22 Copyright @copyright{} @value{copyrights-gm2} Free Software Foundation, Inc.
23
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
37
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
45
46 @insertcopying
47 @end ifinfo
48
49 @titlepage
50 @title The GNU Modula-2 Compiler
51 @versionsubtitle
52 @author Gaius Mulley
53
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
64
65 @c `Top' Node and Master Menu
66
67 @node Top, Overview, (dir), (dir)
68 @top Introduction
69
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
81
82 @node Overview, Using, Top, Top
83 @chapter Overview of GNU Modula-2
84
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
91
92 @node What is GNU Modula-2, Why use GNU Modula-2, , Overview
93 @section What is GNU Modula-2
94
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.
100
101 @footnote{The four Modula-2 dialects supported are defined in the following
102 references:
103
104 PIM2: 'Programming in Modula-2', 2nd Edition, Springer Verlag, 1982,
105 1983 by Niklaus Wirth (PIM2).
106
107 PIM3: 'Programming in Modula-2', 3rd Corrected Edition, Springer Verlag,
108 1985 (PIM3).
109
110 PIM4: 'Programming in Modula-2', 4th Edition, Springer Verlag, 1988
111 (@uref{http://freepages.modula2.org/report4/modula-2.html, PIM4}).
112
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)'
116 }
117
118 @node Why use GNU Modula-2, Development, What is GNU Modula-2, Overview
119 @section Why use GNU Modula-2
120
121 There are a number of advantages of using GNU Modula-2 rather than
122 translate an existing project into another language.
123
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.
127
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.
131
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.
135
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.
139
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.
144
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.
151
152 @node Development, Features, Why use GNU Modula-2, Overview
153 @section How to get source code using git
154
155 GNU Modula-2 is now in the @url{https://gcc.gnu.org/git.html, GCC git
156 tree}.
157
158 @node Features, , Development, Overview
159 @section GNU Modula-2 Features
160
161 @itemize @bullet
162
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}.
168
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.
173
174 @item
175 exception handling is compatible with C++ and swig. Modula-2 code can
176 be used with C or C++ code.
177
178 @item
179 Python can call GNU Modula-2 modules via swig.
180
181 @item
182 shared libraries can be built.
183
184 @item
185 fixed sized types are now available from @samp{SYSTEM}.
186
187 @c @item
188 @c support for dynamic @code{ARRAY}s has been added into @samp{gdb}.
189
190 @item
191 variables can be declared at addresses.
192
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.
198
199 @item
200 supports sets of any ordinal size (memory permitting).
201
202 @item
203 easy interface to C, and varargs can be passed to C routines.
204
205 @item
206 many Logitech libraries have been implemented and can be accessed via:
207 @samp{-flibs=m2log,m2pim,m2iso}.
208
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).
214
215 @item
216 can be built as a cross compiler (for embedded microprocessors
217 such as the AVR and the ARM).
218
219 @end itemize
220
221 @node Using, License, Overview, Top
222 @chapter Using GNU Modula-2
223
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
259
260 This document contains the user and design issues relevant to the
261 Modula-2 front end to gcc.
262
263 @node Example usage, Compiler options, Using, Using
264 @section Example compile and link
265
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{}
273
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
282
283 @c man begin DESCRIPTION gm2
284
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}.
289
290 @c man end
291
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, , ,gm2}. Assuming that you have
295 a file called @file{hello.mod} in your current directory which
296 contains:
297
298 @example
299 MODULE hello ;
300
301 FROM StrIO IMPORT WriteString, WriteLn ;
302
303 BEGIN
304 WriteString ('hello world') ; WriteLn
305 END hello.
306 @end example
307
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.
310
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}.
314
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:
317
318 @samp{gm2 -v -g -I. hello.mod}
319
320 This displays the sub processes initiated by @samp{gm2} which can be useful
321 when trouble shooting.}
322
323 @node Compiler options, Linking, Example usage, Using
324 @section Compiler options
325
326 This section describes the compiler options specific to GNU Modula-2
327 for generic flags details @xref{Invoking GCC, , ,gcc}.
328
329 @c man begin OPTIONS
330
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:
333
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
346
347 You can specify more than one input file on the @command{gm2} command line,
348
349 @table @code
350
351 @item -g
352 create debugging information so that debuggers such as @file{gdb}
353 can inspect and control executable.
354
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.
361
362 @c ordered list of options from here.
363
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.
368
369 @item -fbounds
370 turns on run time subrange, array index and indirection via @code{NIL}
371 pointer checking.
372
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.
376
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}.
383
384 @c fcpp-end
385 @c Modula-2
386 @c passed to the preprocessor if -fcpp is used (internal switch)
387
388 @c fcpp-begin
389 @c Modula-2
390 @c passed to the preprocessor if -fcpp is used (internal switch)
391
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 a real function.
396
397 @c fd
398 @c Modula-2
399 @c turn on internal debugging of the compiler (internal switch)
400
401 @c fdebug-trace-quad
402 @c Modula-2
403 @c turn on quadruple tracing (internal switch)
404
405 @c fdebug-trace-api
406 @c Modula-2
407 @c turn on the Modula-2 api tracing (internal switch)
408
409 @c fdebug-function-line-numbers
410 @c Modula-2
411 @c turn on the Modula-2 function line number generation (internal switch)
412
413 @item -fdef=
414 recognize the specified suffix as a definition module filename.
415 The default implementation and module filename suffix is @file{.def}.
416 If this option is used GNU Modula-2 will still fall back to this
417 default if a requested definition module is not found.
418
419 @item -fdump-system-exports
420 display all inbuilt system items.
421 This is an internal command line option.
422
423 @item -fexceptions
424 turn on exception handling code. By default this option is on.
425 Exception handling can be disabled by @samp{-fno-exceptions}
426 and no references are made to the run time exception libraries.
427
428 @item -fextended-opaque
429 allows opaque types to be implemented as any type. This is a GNU
430 Modula-2 extension and it requires that the implementation module
431 defining the opaque type is available so that it can be resolved when
432 compiling the module which imports the opaque type.
433
434 @item -ffloatvalue
435 turns on run time checking to check whether a floating point number is
436 about to exceed range.
437
438 @item -fgen-module-list=@file{filename}
439 attempt to find all modules when linking and generate a module list.
440 If the @file{filename} is @samp{-} then the contents are not written
441 and only used to force the linking of all module ctors.
442 This option cannot be used if @samp{-fuse-list=} is enabled.
443
444 @item -findex
445 generate code to check whether array index values are out of bounds.
446 Array index checking can be disabled via @samp{-fno-index}.
447
448 @item -fiso
449 turn on ISO standard features. Currently this enables the ISO
450 @code{SYSTEM} module and alters the default library search path so
451 that the ISO libraries are searched before the PIM libraries. It also
452 effects the behavior of @code{DIV} and @code{MOD} operators.
453 @xref{Dialect, , ,gm2}.
454
455 @item -flibs=
456 modifies the default library search path. The libraries supplied are:
457 m2pim, m2iso, m2min, m2log and m2cor. These map onto the
458 Programming in Modula-2 base libraries, ISO standard libraries, minimal
459 library support, Logitech compatible library and Programming in
460 Modula-2 with coroutines.
461 Multiple libraries can be specified and are comma separated with precedence
462 going to the first in the list. It is not necessary to use -flibs=m2pim or
463 -flibs=m2iso if you also specify -fpim, -fpim2, -fpim3, -fpim4 or
464 -fiso. Unless you are using -flibs=m2min you should include m2pim as
465 the they provide the base modules which all other dialects utilize.
466 The option @samp{-fno-libs=-} disables the @samp{gm2} driver from
467 modifying the search and library paths.
468
469 @item -static-libgm2
470 On systems that provide the m2 runtimes as both shared and static libraries,
471 this option forces the use of the static version.
472
473 @c flocation=
474 @c Modula-2 Joined
475 @c set all location values to a specific value (internal switch)
476
477 @item -fm2-g
478 improve the debugging experience for new programmers at the expense
479 of generating @code{nop} instructions if necessary to ensure single
480 stepping precision over all code related keywords. An example
481 of this is in termination of a list of nested @code{IF} statements
482 where multiple @code{END} keywords are mapped onto a sequence of
483 @code{nop} instructions.
484
485 @item -fm2-lower-case
486 render keywords in error messages using lower case.
487
488 @item -fm2-pathname=
489 specify the module mangled prefix name for all modules in the
490 following include paths.
491
492 @item -fm2-pathnameI
493 for internal use only: used by the driver to copy the user facing -I
494 option.
495
496 @item -fm2-plugin
497 insert plugin to identify run time errors at compile time (default on).
498
499 @item -fm2-prefix=
500 specify the module mangled prefix name. All exported symbols from a
501 definition module will have the prefix name.
502
503 @item -fm2-statistics
504 generates quadruple information: number of quadruples generated,
505 number of quadruples remaining after optimization and number of source
506 lines compiled.
507
508 @item -fm2-strict-type
509 experimental flag to turn on the new strict type checker.
510
511 @item -fm2-whole-program
512 compile all implementation modules and program module at once. Notice
513 that you need to take care if you are compiling different dialect
514 modules (particularly with the negative operands to modulus). But
515 this option, when coupled together with @code{-O3}, can deliver huge
516 performance improvements.
517
518 @item -fmod=
519 recognize the specified suffix as implementation and module filenames.
520 The default implementation and module filename suffix is @file{.mod}.
521 If this option is used GNU Modula-2 will still fall back to this
522 default if it needs to read an implementation module and the specified
523 suffixed filename does not exist.
524
525 @item -fnil
526 generate code to detect accessing data through a @code{NIL} value
527 pointer. Dereferencing checking through a @code{NIL} pointer can be
528 disabled by @samp{-fno-nil}.
529
530 @item -fpim
531 turn on PIM standard features. Currently this enables the PIM
532 @code{SYSTEM} module and determines which identifiers are pervasive
533 (declared in the base module). If no other @samp{-fpim[234]} switch is
534 used then division and modulus operators behave as defined in PIM4.
535 @xref{Dialect, , ,gm2}.
536
537 @item -fpim2
538 turn on PIM-2 standard features. Currently this removes @code{SIZE}
539 from being a pervasive identifier (declared in the base module). It
540 places @code{SIZE} in the @code{SYSTEM} module. It also effects the
541 behavior of @code{DIV} and @code{MOD} operators.
542 @xref{Dialect, , ,gm2}.
543
544 @item -fpim3
545 turn on PIM-3 standard features. Currently this only effects the
546 behavior of @code{DIV} and @code{MOD} operators.
547 @xref{Dialect, , ,gm2}.
548
549 @item -fpim4
550 turn on PIM-4 standard features. Currently this only effects the
551 behavior of @code{DIV} and @code{MOD} operators.
552 @xref{Dialect, , ,gm2}.
553
554 @item -fpositive-mod-floor-div
555 forces the @code{DIV} and @code{MOD} operators to behave as defined by PIM4.
556 All modulus results are positive and the results from the division are
557 rounded to the floor.
558 @xref{Dialect, , ,gm2}.
559
560 @item -fpthread
561 link against the pthread library. By default this option is on. It
562 can be disabled by @samp{-fno-pthread}. GNU Modula-2 uses the GCC
563 pthread libraries to implement coroutines (see the SYSTEM
564 implementation module).
565
566 @c -fq
567 @c -Modula-2
568 @c -internal compiler debugging information, dump the list of quadruples
569
570 @item -frange
571 generate code to check the assignment range, return value range
572 set range and constructor range. Range checking can be disabled
573 via @samp{-fno-range}.
574
575 @item -freturn
576 generate code to check that functions always exit with a @code{RETURN}
577 and do not fall out at the end. Return checking can be disabled
578 via @samp{-fno-return}.
579
580 @item -fruntime-modules=
581 specify, using a comma separated list, the run time modules and their
582 order. These modules will initialized first before any other modules
583 in the application dependency. By default the run time modules list
584 is set to @code{m2iso:RTentity,m2iso:Storage,m2iso:SYSTEM,}
585 @code{m2iso:M2RTS,m2iso:RTExceptions,m2iso:IOLink}. Note that these
586 modules will only be linked into your executable if they are required.
587 Adding a long list of dependent modules will not effect the size of
588 the executable it merely states the initialization order should they
589 be required.
590
591 @item -fscaffold-dynamic
592 the option ensures that @samp{gm2} will generate a dynamic scaffold
593 infrastructure when compiling implementation and program modules.
594 By default this option is on. Use @samp{-fno-scaffold-dynamic}
595 to turn it off or select @samp{-fno-scaffold-static}.
596
597 @item -fscaffold-c
598 generate a C source scaffold for the current module being compiled.
599
600 @item -fscaffold-c++
601 generate a C++ source scaffold for the current module being compiled.
602
603 @item -fscaffold-main
604 force the generation of the @samp{main} function. This is not
605 necessary if the @samp{-c} is omitted.
606
607 @item -fscaffold-static
608 the option ensures that @samp{gm2} will generate a static scaffold
609 within the program module. The static scaffold consists of sequences
610 of calls to all dependent module initialization and finalization
611 procedures. The static scaffold is useful for debugging and single
612 stepping the initialization blocks of implementation modules.
613
614 @item -fshared
615 generate a shared library from the module.
616
617 @item -fsoft-check-all
618 turns on all run time checks. This is the same as invoking
619 GNU Modula-2 using the command options
620 @code{-fnil} @code{-frange} @code{-findex}
621 @code{-fwholevalue}
622 @code{-fwholediv} @code{-fcase} @code{-freturn}.
623
624 @item -fsources
625 displays the path to the source of each module. This option
626 can be used at compile time to check the correct definition module
627 is being used.
628
629 @item -fswig
630 generate a swig interface file.
631
632 @item -funbounded-by-reference
633 enable optimization of unbounded parameters by attempting to pass non
634 @code{VAR} unbounded parameters by reference. This optimization
635 avoids the implicit copy inside the callee procedure. GNU Modula-2
636 will only allow unbounded parameters to be passed by reference if,
637 inside the callee procedure, they are not written to, no address is
638 calculated on the array and it is not passed as a @code{VAR}
639 parameter. Note that it is possible to write code to break this
640 optimization, therefore this option should be used carefully.
641 For example it would be possible to take the address of an array, pass
642 the address and the array to a procedure, read from the array in
643 the procedure and write to the location using the address parameter.
644
645 Due to the dangerous nature of this option it is not enabled
646 when the @samp{-O} option is specified.
647
648 @item -fuse-list=@file{filename}
649 if @samp{-fscaffold-static} is enabled then use the file
650 @file{filename} for the initialization order of modules. Whereas if
651 @samp{-fscaffold-dynamic} is enabled then use this file to force
652 linking of all module ctors.
653 This option cannot be used if @samp{-fgen-module-list=} is enabled.
654
655 @item -fwholediv
656 generate code to detect whole number division by zero or modulus by
657 zero.
658
659 @item -fwholevalue
660 generate code to detect whole number overflow and underflow.
661
662 @item -Wcase-enum
663 generate a warning if a @code{CASE} statement selects on an enumerated
664 type expression and the statement is missing one or more @code{CASE}
665 labels. No warning is issued if the @code{CASE} statement has a default
666 @code{ELSE} clause.
667 The option @samp{-Wall} will turn on this flag.
668
669 @item -Wuninit-variable-checking
670 issue a warning if a variable is used before it is initialized.
671 The checking only occurs in the first basic block in each procedure.
672 It does not check parameters, array types or set types.
673
674 @item -Wuninit-variable-checking=all,known,cond
675 issue a warning if a variable is used before it is initialized.
676 The checking will only occur in the first basic block in each
677 procedure if @samp{known} is specified. If @samp{cond} or @samp{all}
678 is specified then checking continues into conditional branches of the
679 flow graph. All checking will stop when a procedure call is invoked
680 or the top of a loop is encountered.
681 The option @samp{-Wall} will turn on this flag with
682 @samp{-Wuninit-variable-checking=known}.
683 The @samp{-Wuninit-variable-checking=all} will increase compile time.
684
685 @c the following warning options are complete but need to be
686 @c regression tested against all other front ends
687 @c to ensure the options do not conflict.
688
689 @c @item -Wall
690 @c turn on all Modula-2 warnings.
691
692 @c @item -Wpedantic
693 @c forces the compiler to reject nested @code{WITH} statements
694 @c referencing the same record type. Does not allow multiple imports of
695 @c the same item from a module. It also checks that: procedure variables
696 @c are written to before being read; variables are not only written to
697 @c but read from; variables are declared and used. If the compiler
698 @c encounters a variable being read before written it will terminate with
699 @c a message. It will check that @code{FOR} loop indices are not used
700 @c outside the end of this loop without being reset.
701
702 @c @item -Wpedantic-cast
703 @c warns if the ISO system function is used and if the size of
704 @c the variable is different from that of the type. This is legal
705 @c in ISO Modula-2, however it can be dangerous. Some users may prefer
706 @c to use @code{VAL} instead in these situations and use @code{CAST}
707 @c exclusively for changes in type on objects which have the same size.
708
709 @c @item -Wpedantic-param-names
710 @c procedure parameter names are checked in the definition module
711 @c against their implementation module counterpart. This is not
712 @c necessary in ISO or PIM versions of Modula-2.
713
714 @c @item -Wstyle
715 @c checks for poor programming style. This option is aimed at new users of
716 @c Modula-2 in that it checks for situations which might cause confusion
717 @c and thus mistakes. It checks whether variables of the same name are
718 @c declared in different scopes and whether variables look like keywords.
719 @c Experienced users might find this option too aggressive.
720
721 @c @item -Wunused-variable
722 @c warns if a variable has been declared and it not used.
723
724 @c @item -Wunused-parameter
725 @c warns if a parameter has been declared and it not used.
726
727 @c @item -Wverbose-unbounded
728 @c inform the user which non @code{VAR} unbounded parameters will be
729 @c passed by reference. This only produces output if the option
730 @c @samp{-funbounded-by-reference} is also supplied on the command line.
731
732 @end table
733
734 @c man end
735
736 @node Linking, Elementary data types, Compiler options, Using
737
738 This section describes the linking related options. There are three
739 linking strategies available which are dynamic scaffold, static
740 scaffold and user defined. The dynamic scaffold is enabled by default
741 and each module will register itself to the run time @samp{M2RTS} via
742 a constructor. The static scaffold mechanism will invoke each modules
743 @samp{_init} and @samp{_finish} function in turn via a sequence of
744 calls from within @samp{main}. Lastly the user defined strategy
745 can be implemented by turning off the dynamic and static options via
746 @samp{-fno-scaffold-dynamic} and @samp{-fno-scaffold-static}.
747
748 In the simple test below:
749
750 @example
751 $ gm2 hello.mod
752 @end example
753
754 the driver will add the options @samp{-fscaffold-dynamic} and
755 @samp{-fgen-module-list=-} which generate a list of application
756 modules and also creates the @samp{main} function with calls to
757 @samp{M2RTS}. It can be useful to add the option @samp{-fsources}
758 which displays the source files as they are parsed and summarizes
759 whether the source file is required for compilation or linking.
760
761 If you wish to split the above command line into a compile and link
762 then you could use these steps:
763
764 @example
765 $ gm2 -c -fscaffold-main hello.mod
766 $ gm2 hello.o
767 @end example
768
769 The @samp{-fscaffold-main} informs the compiler to generate the
770 @samp{main} function and scaffold. You can enable the environment
771 variable @samp{GCC_M2LINK_RTFLAG} to trace the construction and
772 destruction of the application. The values for
773 @samp{GCC_M2LINK_RTFLAG} are shown in the table below:
774
775 @example
776 value | meaning
777 =================
778 all | turn on all flags below
779 module | trace modules as they register themselves
780 hex | display the hex address of the init/fini functions
781 warning | show any warnings
782 pre | generate module list prior to dependency resolution
783 dep | trace module dependency resolution
784 post | generate module list after dependency resolution
785 force | generate a module list after dependency and forced
786 | ordering is complete
787 @end example
788
789 The values can be combined using a comma separated list.
790
791 One of the advantages of the dynamic scaffold is that the driver
792 behaves in a similar way to the other front end drivers.
793 For example consider a small project consisting of 4 definition
794 implementation modules (@samp{a.def}, @samp{a.mod}, @samp{b.def},
795 @samp{b.mod}, @samp{c.def}, @samp{c.mod}, @samp{d.def}, @samp{d.mod})
796 and a program module @samp{program.mod}.
797
798 To link this project we could:
799
800 @example
801 $ gm2 -g -c a.mod
802 $ gm2 -g -c b.mod
803 $ gm2 -g -c c.mod
804 $ gm2 -g -c d.mod
805 $ gm2 -g program.mod a.o b.o c.o d.o
806 @end example
807
808 The module initialization sequence is defined by the ISO standard to
809 follow the import graph traversal. The initialization order is the
810 order in which the corresponding separate modules finish the
811 processing of their import lists.
812
813 However, if required, you can override this using
814 @samp{-fruntime-modules=a,b,c,d} for example which forces the
815 initialization sequence to @samp{a}, @samp{b}, @samp{c} and @samp{d}.
816
817 @node Elementary data types, Standard procedures, Linking, Using
818 @section Elementary data types
819
820 This section describes the elementary data types supported by GNU
821 Modula-2. It also describes the relationship between these data types
822 and the equivalent C data types.
823
824 The following data types are supported: @code{INTEGER},
825 @code{LONGINT}, @code{SHORTINT}, @code{CARDINAL}, @code{LONGCARD},
826 @code{SHORTCARD}, @code{BOOLEAN}, @code{REAL}, @code{LONGREAL},
827 @code{SHORTREAL}, @code{COMPLEX}, @code{LONGCOMPLEX},
828 @code{SHORTCOMPLEX} and @code{CHAR}.
829
830 An equivalence table is given below:
831
832 @example
833 GNU Modula-2 GNU C
834 ======================================
835 INTEGER int
836 LONGINT long long int
837 SHORTINT short int
838 CARDINAL unsigned int
839 LONGCARD long long unsigned int
840 SHORTCARD short unsigned int
841 BOOLEAN bool
842 REAL double
843 LONGREAL long double
844 SHORTREAL float
845 CHAR char
846 SHORTCOMPLEX complex float
847 COMPLEX complex double
848 LONGCOMPLEX complex long double
849 @end example
850
851 Note that GNU Modula-2 also supports fixed sized data types which are
852 exported from the @code{SYSTEM} module.
853 @xref{The PIM system module, , ,gm2}.
854 @xref{The ISO system module, , ,gm2}.
855
856 @node Standard procedures, High procedure function, Elementary data types, Using
857 @section Permanently accessible base procedures.
858
859 This section describes the procedures and functions which are
860 always visible.
861
862 @subsection Standard procedures and functions common to PIM and ISO
863
864 The following procedures are implemented and conform with Programming
865 in Modula-2 and ISO Modula-2: @code{NEW}, @code{DISPOSE}, @code{INC},
866 @code{DEC}, @code{INCL}, @code{EXCL} and @code{HALT}. The standard
867 functions are: @code{ABS}, @code{CAP}, @code{CHR}, @code{FLOAT},
868 @code{HIGH}, @code{LFLOAT}, @code{LTRUNC}, @code{MIN}, @code{MAX},
869 @code{ODD}, @code{SFLOAT}, @code{STRUNC} @code{TRUNC} and
870 @code{VAL}. All these functions and procedures (except @code{HALT},
871 @code{NEW}, @code{DISPOSE} and, under non constant conditions,
872 @code{LENGTH}) generate in-line code for efficiency.
873
874 @example
875
876 (*
877 ABS - returns the positive value of i.
878 *)
879
880 @findex ABS
881 PROCEDURE ABS (i: <any signed type>) : <any signed type> ;
882
883 @end example
884
885 @example
886
887 (*
888 CAP - returns the capital of character ch providing
889 ch lies within the range 'a'..'z'. Otherwise ch
890 is returned unaltered.
891 *)
892
893 @findex CAP
894 PROCEDURE CAP (ch: CHAR) : CHAR ;
895
896 @end example
897
898 @example
899
900 (*
901 CHR - converts a value of a <whole number type> into a CHAR.
902 CHR(x) is shorthand for VAL(CHAR, x).
903 *)
904
905 @findex CHR
906 PROCEDURE CHR (x: <whole number type>) : CHAR ;
907
908 @end example
909
910 @example
911
912 (*
913 DISPOSE - the procedure DISPOSE is replaced by:
914 DEALLOCATE(p, TSIZE(p^)) ;
915 The user is expected to import the procedure DEALLOCATE
916 (normally found in the module, Storage.)
917
918 In: a variable p: of any pointer type which has been
919 initialized by a call to NEW.
920 Out: the area of memory
921 holding p^ is returned to the system.
922 Note that the underlying procedure DEALLOCATE
923 procedure in module Storage will assign p to NIL.
924 *)
925
926 @findex DISPOSE
927 PROCEDURE DISPOSE (VAR p:<any pointer type>) ;
928 @end example
929
930 @example
931
932 (*
933 DEC - can either take one or two parameters. If supplied
934 with one parameter then on the completion of the call to
935 DEC, v will have its predecessor value. If two
936 parameters are supplied then the value v will have its
937 n'th predecessor. For these reasons the value of n
938 must be >=0.
939 *)
940
941 @findex DEC
942 PROCEDURE DEC (VAR v: <any base type>; [n: <any base type> = 1]) ;
943 @end example
944
945 @example
946
947 (*
948 EXCL - excludes bit element e from a set type s.
949 *)
950
951 @findex EXCL
952 PROCEDURE EXCL (VAR s: <any set type>; e: <element of set type s>) ;
953 @end example
954
955 @example
956
957 (*
958 FLOAT - will return a REAL number whose value is the same as o.
959 *)
960
961 @findex FLOAT
962 PROCEDURE FLOAT (o: <any whole number type>) : REAL ;
963 @end example
964
965 @example
966
967 (*
968 FLOATS - will return a SHORTREAL number whose value is the same as o.
969 *)
970
971 @findex FLOATS
972 PROCEDURE FLOATS (o: <any whole number type>) : REAL ;
973 @end example
974
975 @example
976
977 (*
978 FLOATL - will return a LONGREAL number whose value is the same as o.
979 *)
980
981 @findex FLOATL
982 PROCEDURE FLOATL (o: <any whole number type>) : REAL ;
983 @end example
984
985 @example
986
987 (*
988 HALT - will call the HALT procedure inside the module M2RTS.
989 Users can replace M2RTS.
990 *)
991
992 @findex HALT
993 PROCEDURE HALT ;
994 @end example
995
996 @example
997
998 (*
999 HIGH - returns the last accessible index of an parameter declared as
1000 ARRAY OF CHAR. Thus
1001
1002 PROCEDURE foo (a: ARRAY OF CHAR) ;
1003 VAR
1004 c: CARDINAL ;
1005 BEGIN
1006 c := HIGH(a)
1007 END foo ;
1008
1009 BEGIN
1010 foo('hello')
1011 END
1012
1013 will cause the local variable c to contain the value 5
1014 *)
1015
1016 @findex HIGH
1017 PROCEDURE HIGH (a: ARRAY OF CHAR) : CARDINAL ;
1018 @end example
1019
1020 @example
1021
1022 (*
1023 INC - can either take one or two parameters. If supplied
1024 with one parameter then on the completion of the call to
1025 INC, v will have its successor value. If two
1026 parameters are supplied then the value v will have its
1027 n'th successor. For these reasons the value of n
1028 must be >=0.
1029 *)
1030
1031 @findex INC
1032 PROCEDURE INC (VAR v: <any base type>; [n: <any base type> = 1]) ;
1033 @end example
1034
1035 @example
1036
1037 (*
1038 INCL - includes bit element e to a set type s.
1039 *)
1040
1041 @findex INCL
1042 PROCEDURE INCL (VAR s: <any set type>; e: <element of set type s>) ;
1043 @end example
1044
1045 @example
1046
1047 (*
1048 LFLOAT - will return a LONGREAL number whose value is the same as o.
1049 *)
1050
1051 @findex LFLOAT
1052 PROCEDURE LFLOAT (o: <any whole number type>) : LONGREAL ;
1053 @end example
1054
1055 @example
1056
1057 (*
1058 LTRUNC - will return a LONG<type> number whose value is the
1059 same as o. PIM2, PIM3 and ISO Modula-2 will return
1060 a LONGCARD whereas PIM4 returns LONGINT.
1061 *)
1062
1063 @findex LTRUNC
1064 PROCEDURE LTRUNC (o: <any floating point type>) : LONG<type> ;
1065 @end example
1066
1067 @example
1068
1069 (*
1070 MIN - returns the lowest legal value of an ordinal type.
1071 *)
1072
1073 @findex MIN
1074 PROCEDURE MIN (t: <ordinal type>) : <ordinal type> ;
1075
1076 @end example
1077
1078 @example
1079
1080 (*
1081 MAX - returns the largest legal value of an ordinal type.
1082 *)
1083
1084 @findex MAX
1085 PROCEDURE MAX (t: <ordinal type>) : <ordinal type> ;
1086
1087 @end example
1088
1089 @example
1090
1091 (*
1092 NEW - the procedure NEW is replaced by:
1093 ALLOCATE(p, TSIZE(p^)) ;
1094 The user is expected to import the procedure ALLOCATE
1095 (normally found in the module, Storage.)
1096
1097 In: a variable p: of any pointer type.
1098 Out: variable p is set to some allocated memory
1099 which is large enough to hold all the contents of p^.
1100 *)
1101
1102 @findex NEW
1103 PROCEDURE NEW (VAR p:<any pointer type>) ;
1104 @end example
1105
1106 @example
1107
1108 (*
1109 ODD - returns TRUE if the value is not divisible by 2.
1110 *)
1111
1112 @findex ODD
1113 PROCEDURE ODD (x: <whole number type>) : BOOLEAN ;
1114
1115 @end example
1116
1117 @example
1118
1119 (*
1120 SFLOAT - will return a SHORTREAL number whose value is the same
1121 as o.
1122 *)
1123
1124 @findex SFLOAT
1125 PROCEDURE SFLOAT (o: <any whole number type>) : SHORTREAL ;
1126 @end example
1127
1128 @example
1129
1130 (*
1131 STRUNC - will return a SHORT<type> number whose value is the same
1132 as o. PIM2, PIM3 and ISO Modula-2 will return a
1133 SHORTCARD whereas PIM4 returns SHORTINT.
1134 *)
1135
1136 @findex STRUNC
1137 PROCEDURE STRUNC (o: <any floating point type>) : SHORT<type> ;
1138 @end example
1139
1140 @example
1141
1142 (*
1143 TRUNC - will return a <type> number whose value is the same as o.
1144 PIM2, PIM3 and ISO Modula-2 will return a CARDINAL
1145 whereas PIM4 returns INTEGER.
1146 *)
1147
1148 @findex TRUNC
1149 PROCEDURE TRUNC (o: <any floating point type>) : <type> ;
1150 @end example
1151
1152 @example
1153
1154 (*
1155 TRUNCS - will return a <type> number whose value is the same
1156 as o. PIM2, PIM3 and ISO Modula-2 will return a
1157 SHORTCARD whereas PIM4 returns SHORTINT.
1158 *)
1159
1160 @findex TRUNCS
1161 PROCEDURE TRUNCS (o: <any floating point type>) : <type> ;
1162 @end example
1163
1164 @example
1165
1166 (*
1167 TRUNCL - will return a <type> number whose value is the same
1168 as o. PIM2, PIM3 and ISO Modula-2 will return a
1169 LONGCARD whereas PIM4 returns LONGINT.
1170 *)
1171
1172 @findex TRUNCL
1173 PROCEDURE TRUNCL (o: <any floating point type>) : <type> ;
1174 @end example
1175
1176 @example
1177
1178 (*
1179 VAL - converts data i of <any simple data type 2> to
1180 <any simple data type 1> and returns this value.
1181 No range checking is performed during this conversion.
1182 *)
1183
1184 @findex VAL
1185 PROCEDURE VAL (<any simple data type 1>,
1186 i: <any simple data type 2>) : <any simple data type 1> ;
1187
1188 @end example
1189
1190 @subsection ISO specific standard procedures and functions
1191
1192 The standard function @code{LENGTH} is specific to ISO Modula-2 and
1193 is defined as:
1194
1195 @example
1196
1197 (*
1198 IM - returns the imaginary component of a complex type.
1199 The return value will the same type as the imaginary field
1200 within the complex type.
1201 *)
1202
1203 @findex IM
1204 PROCEDURE IM (c: <any complex type>) : <floating point type> ;
1205 @end example
1206
1207 @example
1208
1209 (*
1210 INT - returns an INTEGER value which has the same value as v.
1211 This function is equivalent to: VAL(INTEGER, v).
1212 *)
1213
1214 @findex INT
1215 PROCEDURE INT (v: <any ordinal type>) : INTEGER ;
1216 @end example
1217
1218 @example
1219
1220 (*
1221 LENGTH - returns the length of string a.
1222 *)
1223
1224 @findex LENGTH
1225 PROCEDURE LENGTH (a: ARRAY OF CHAR) : CARDINAL ;
1226 @end example
1227
1228 This function is evaluated at compile time, providing that string
1229 @code{a} is a constant. If @code{a} cannot be evaluated then a call is
1230 made to @code{M2RTS.Length}.
1231
1232 @example
1233
1234 (*
1235 ODD - returns a BOOLEAN indicating whether the whole number
1236 value, v, is odd.
1237 *)
1238
1239 @findex ODD
1240 PROCEDURE ODD (v: <any whole number type>) : BOOLEAN ;
1241 @end example
1242
1243 @example
1244
1245 (*
1246 RE - returns the real component of a complex type.
1247 The return value will the same type as the real field
1248 within the complex type.
1249 *)
1250
1251 @findex RE
1252 PROCEDURE RE (c: <any complex type>) : <floating point type> ;
1253 @end example
1254
1255 @node High procedure function, Dialect, Standard procedures, Using
1256
1257 @section Behavior of the high procedure function
1258
1259 This section describes the behavior of the standard procedure function
1260 @code{HIGH} and it includes a table of parameters with the expected
1261 return result. The standard procedure function will return the last
1262 accessible indice of an @code{ARRAY}. If the parameter to @code{HIGH}
1263 is a static array then the result will be a @code{CARDINAL} value
1264 matching the upper bound in the @code{ARRAY} declaration.
1265
1266 The section also describes the behavior of a string literal actual
1267 parameter and how it relates to @code{HIGH}.
1268 The PIM2, PIM3, PIM4 and ISO standard is silent on the issue of
1269 whether a @code{nul} is present in an @code{ARRAY} @code{OF}
1270 @code{CHAR} actual parameter.
1271
1272 If the first parameter to @code{HIGH} is an unbounded @code{ARRAY} the
1273 return value from @code{HIGH} will be the last accessible element in
1274 the array. If a constant string literal is passed as an actual
1275 parameter then it will be @code{nul} terminated. The table and
1276 example code below describe the effect of passing an actual parameter
1277 and the expected @code{HIGH} value.
1278
1279 @example
1280 MODULE example1 ;
1281
1282 PROCEDURE test (a: ARRAY OF CHAR) ;
1283 VAR
1284 x: CARDINAL ;
1285 BEGIN
1286 x := HIGH (a) ;
1287 ...
1288 END test ;
1289
1290
1291 BEGIN
1292 test ('') ;
1293 test ('1') ;
1294 test ('12') ;
1295 test ('123') ;
1296 END example1.
1297
1298
1299 Actual parameter | HIGH (a) | a[HIGH (a)] = nul
1300 ===============================================
1301 '' | 0 | TRUE
1302 '1' | 1 | TRUE
1303 '12' | 2 | TRUE
1304 '123' | 3 | TRUE
1305 @end example
1306
1307 A constant string literal will be passed to an @code{ARRAY} @code{OF}
1308 @code{CHAR} with an appended @code{nul} @code{CHAR}. Thus if the
1309 constant string literal @code{''} is passed as an actual parameter (in
1310 example1) then the result from @code{HIGH(a)} will be @code{0}.
1311
1312 @example
1313 MODULE example2 ;
1314
1315 PROCEDURE test (a: ARRAY OF CHAR) ;
1316 VAR
1317 x: CARDINAL ;
1318 BEGIN
1319 x := HIGH (a) ;
1320 ...
1321 END test ;
1322
1323 VAR
1324 str0: ARRAY [0..0] OF CHAR ;
1325 str1: ARRAY [0..1] OF CHAR ;
1326 str2: ARRAY [0..2] OF CHAR ;
1327 str3: ARRAY [0..3] OF CHAR ;
1328 BEGIN
1329 str0 := 'a' ; (* No room for the nul terminator. *)
1330 test (str0) ;
1331 str1 := 'ab' ; (* No room for the nul terminator. *)
1332 test (str1) ;
1333 str2 := 'ab' ; (* Terminated with a nul. *)
1334 test (str2) ;
1335 str2 := 'abc' ; (* Terminated with a nul. *)
1336 test (str3) ;
1337 END example2.
1338
1339 Actual parameter | HIGH (a) | a[HIGH (a)] = nul
1340 ===============================================
1341 str0 | 0 | FALSE
1342 str1 | 1 | FALSE
1343 atr2 | 2 | TRUE
1344 str3 | 3 | TRUE
1345 @end example
1346
1347 @node Dialect, Exceptions, High procedure function, Using
1348 @section GNU Modula-2 supported dialects
1349
1350 This section describes the dialects understood by GNU Modula-2.
1351 It also describes the differences between the dialects and
1352 any command line switches which determine dialect behaviour.
1353
1354 The GNU Modula-2 compiler is compliant with four dialects of Modula-2.
1355 The language as defined in 'Programming in Modula-2' 2nd Edition,
1356 Springer Verlag, 1982, 1983 by Niklaus Wirth (PIM2), 'Programming in
1357 Modula-2', 3rd Corrected Edition, Springer Verlag, 1985 (PIM3) and
1358 'Programming in Modula-2', 4th Edition, Springer Verlag, 1988 (PIM4)
1359 @uref{http://freepages.modula2.org/report4/modula-2.html} and the ISO
1360 Modula-2 language as defined in ISO/IEC Information technology -
1361 programming languages - part 1: Modula-2 Language, ISO/IEC 10514-1
1362 (1996) (ISO).
1363
1364 The command line switches @samp{-fpim2}, @samp{-fpim3}, @samp{-fpim4}
1365 and @samp{-fiso} can be used to force mutually exclusive
1366 features. However by default the compiler will not aggressively fail
1367 if a non mutually exclusive feature is used from another dialect. For
1368 example it is possible to specify @samp{-fpim2} and still utilize
1369 @samp{DEFINITION} @samp{MODULES} which have no export list.
1370
1371 Some dialect differences will force a compile time error, for example
1372 in PIM2 the user must @code{IMPORT} @code{SIZE} from the module
1373 @code{SYSTEM}, whereas in PIM3 and PIM4 @code{SIZE} is a pervasive
1374 function. Thus compiling PIM4 source code with the @samp{-fpim2}
1375 switch will cause a compile time error. This can be fixed quickly
1376 with an additional @code{IMPORT} or alternatively by compiling with
1377 the @samp{-fpim4} switch.
1378
1379 However there are some very important differences between the dialects
1380 which are mutually exclusive and therefore it is vital that users
1381 choose the dialects with care when these language features are used.
1382
1383 @subsection Integer division, remainder and modulus
1384
1385 The most dangerous set of mutually exclusive features found in the
1386 four dialects supported by GNU Modula-2 are the @code{INTEGER}
1387 division, remainder and modulus arithmetic operators. It is important
1388 to note that the same source code can be compiled to give different
1389 run time results depending upon these switches! The reference manual
1390 for the various dialects of Modula-2 are quite clear about this
1391 behavior and sadly there are three distinct definitions.
1392
1393 The table below illustrates the problem when a negative operand is
1394 used.
1395
1396 @example
1397 Pim2/3 Pim4 ISO
1398 ----------- ----------- ----------------------
1399 lval rval DIV MOD DIV MOD DIV MOD / REM
1400 31 10 3 1 3 1 3 1 3 1
1401 -31 10 -3 -1 -4 9 -4 9 -3 -1
1402 31 -10 -3 1 -3 1 Exception -3 1
1403 -31 -10 3 -1 4 9 Exception 3 -1
1404 @end example
1405
1406 See also P24 of PIM2, P27 of PIM3, P29 of PIM4 and P201 of the ISO
1407 Standard. At present all dialect division, remainder and modulus are
1408 implemented as above, apart from the exception calling in the ISO
1409 dialect. Instead of exception handling the results are the same as the
1410 PIM4 dialect. This is a temporary implementation situation.
1411
1412 @node Exceptions, Semantic checking, Dialect, Using
1413 @section Exception implementation
1414
1415 This section describes how exceptions are implemented in GNU Modula-2
1416 and how command line switches affect their behavior. The option
1417 @samp{-fsoft-check-all} enables all software checking of nil
1418 dereferences, division by zero etc. Additional code is produced to
1419 check these conditions and exception handlers are invoked if the
1420 conditions prevail.
1421
1422 Without @samp{-fsoft-check-all} these exceptions will be caught by
1423 hardware (assuming the hardware support exists) and a signal handler
1424 is invoked. The signal handler will in turn @code{THROW} an exception
1425 which will be caught by the appropriate Modula-2 handler. However the
1426 action of throwing an exception from within a signal handler is
1427 implementation defined (according to the C++ documentation). For
1428 example on the x86_64 architecture this works whereas on the i686
1429 architecture it does not. Therefore to ensure portability it is
1430 recommended to use @samp{-fsoft-check-all}.
1431
1432 @footnote{@samp{-fsoft-check-all} can be effectively combined with
1433 @samp{-O2} to semantically analyze source code for possible run time
1434 errors at compile time.}
1435
1436 @node Semantic checking, Extensions, Exceptions, Using
1437 @section How to detect run time problems at compile time
1438
1439 Consider the following program:
1440
1441 @example
1442 MODULE assignvalue ; (*!m2iso+gm2*)
1443
1444 PROCEDURE bad () : INTEGER ;
1445 VAR
1446 i: INTEGER ;
1447 BEGIN
1448 i := -1 ;
1449 RETURN i
1450 END bad ;
1451
1452 VAR
1453 foo: CARDINAL ;
1454 BEGIN
1455 (* The m2rte plugin will detect this as an error, post
1456 optimization. *)
1457 foo := bad ()
1458 END assignvalue.
1459 @end example
1460
1461 here we see that the programmer has overlooked that the return value
1462 from @samp{bad} will cause an overflow to @samp{foo}. If we compile
1463 the code with the following options:
1464
1465 @example
1466 $ gm2 -g -fsoft-check-all -O2 -c assignvalue.mod
1467 assignvalue.mod:16:0:inevitable that this error will occur at run time,
1468 assignment will result in an overflow
1469 @end example
1470
1471 The gm2 semantic plugin is automatically run and will generate a
1472 warning message for every exception call which is known as reachable.
1473 It is highly advised to run the optimizer (@samp{-O2} or @samp{-O3})
1474 with @samp{-fsoft-check-all} so that the compiler is able to run the
1475 optimizer and perform variable and flow analysis before the semantic
1476 plugin is invoked.
1477
1478 The @samp{-Wuninit-variable-checking} can be used to identify
1479 uninitialized variables within the first basic block in a procedure.
1480 The checking is limited to variables so long as they are
1481 not an array or set or a variant record or var parameter.
1482
1483 The following example detects whether a sub component within a record
1484 is uninitialized.
1485
1486 @example
1487 MODULE testlarge2 ;
1488
1489 TYPE
1490 color = RECORD
1491 r, g, b: CARDINAL ;
1492 END ;
1493
1494 pixel = RECORD
1495 fg, bg: color ;
1496 END ;
1497
1498 PROCEDURE test ;
1499 VAR
1500 p: pixel ;
1501 BEGIN
1502 p.fg.r := 1 ;
1503 p.fg.g := 2 ;
1504 p.fg.g := 3 ; (* Deliberate typo should be p.fg.b. *)
1505 p.bg := p.fg ; (* Accessing an uninitialized field. *)
1506 END test ;
1507
1508 BEGIN
1509 test
1510 END testlarge2.
1511 @end example
1512
1513 @example
1514 $ gm2 -c -Wuninit-variable-checking testlarge2.mod
1515 testlarge2.mod:19:13: warning: In procedure ‘test’: attempting to
1516 access expression before it has been initialized
1517 19 | p.bg := p.fg ; (* Accessing an uninitialized field. *)
1518 | ~^~~
1519 @end example
1520
1521 The following example detects if an individual field is uninitialized.
1522
1523 @example
1524 MODULE testwithnoptr ;
1525
1526 TYPE
1527 Vec = RECORD
1528 x, y: CARDINAL ;
1529 END ;
1530
1531 PROCEDURE test ;
1532 VAR
1533 p: Vec ;
1534 BEGIN
1535 WITH p DO
1536 x := 1 ;
1537 x := 2 (* Deliberate typo, user meant y. *)
1538 END ;
1539 IF p.y = 2
1540 THEN
1541 END
1542 END test ;
1543
1544 BEGIN
1545 test
1546 END testwithnoptr.
1547 @end example
1548
1549 The following example detects a record is uninitialized via a
1550 pointer variable in a @samp{WITH} block.
1551
1552 @example
1553 $ gm2 -g -c -Wuninit-variable-checking testwithnoptr.mod
1554 testwithnoptr.mod:21:8: warning: In procedure ‘test’: attempting to
1555 access expression before it has been initialized
1556 21 | IF p.y = 2
1557 | ~^~
1558 @end example
1559
1560 @example
1561 MODULE testnew6 ;
1562
1563 FROM Storage IMPORT ALLOCATE ;
1564
1565 TYPE
1566 PtrToVec = POINTER TO RECORD
1567 x, y: INTEGER ;
1568 END ;
1569
1570 PROCEDURE test ;
1571 VAR
1572 p: PtrToVec ;
1573 BEGIN
1574 NEW (p) ;
1575 WITH p^ DO
1576 x := 1 ;
1577 x := 2 (* Deliberate typo, user meant y. *)
1578 END ;
1579 IF p^.y = 2
1580 THEN
1581 END
1582 END test ;
1583
1584
1585 BEGIN
1586 test
1587 END testnew6.
1588 @end example
1589
1590 @example
1591 $ gm2 -g -c -Wuninit-variable-checking testnew6.mod
1592 testnew6.mod:19:9: warning: In procedure ‘test’: attempting to
1593 access expression before it has been initialized
1594 19 | IF p^.y = 2
1595 | ~~^~
1596 @end example
1597
1598 @node Extensions, Type compatibility, Semantic checking, Using
1599 @section GNU Modula-2 language extensions
1600
1601 This section introduces the GNU Modula-2 language extensions.
1602 The GNU Modula-2 compiler allows abstract data types to be any type,
1603 not just restricted to a pointer type providing the
1604 @samp{-fextended-opaque} option is supplied
1605 @xref{Compiler options, , ,gm2}.
1606
1607 Declarations can be made in any order, whether they are
1608 types, constants, procedures, nested modules or variables.
1609 @c (@xref{Passes, , ,}.)
1610
1611 GNU Modula-2 also allows programmers to interface to @code{C} and
1612 assembly language.
1613
1614 GNU Modula-2 provides support for the special tokens @code{__LINE__},
1615 @code{__FILE__}, @code{__FUNCTION__} and @code{__DATE__}. Support for
1616 these tokens will occur even if the @samp{-fcpp} option is not
1617 supplied. A table of these identifiers and their data type and values
1618 is given below:
1619
1620 @example
1621 Scope GNU Modula-2 token Data type and example value
1622
1623 anywhere __LINE__ Constant Literal compatible
1624 with CARDINAL, INTEGER and WORD.
1625 Example 1234
1626
1627 anywhere __FILE__ Constant string compatible
1628 with parameter ARRAY OF CHAR or
1629 an ARRAY whose SIZE is >= string
1630 length. Example
1631 "hello.mod"
1632
1633 procedure __FUNCTION__ Constant string compatible
1634 with parameter ARRAY OF CHAR or
1635 an ARRAY whose SIZE is >= string
1636 length. Example
1637 "calc"
1638
1639 module __FUNCTION__ Example
1640 "module hello initialization"
1641
1642 anywhere __DATE__ Constant string compatible
1643 with parameter ARRAY OF CHAR or
1644 an ARRAY whose SIZE is >= string
1645 length. Example
1646 "Thu Apr 29 10:07:16 BST 2004"
1647
1648 anywhere __COLUMN__ Gives a constant literal number
1649 determining the left hand column
1650 where the first _ appears in
1651 __COLUMN__. The left most column
1652 is 1.
1653
1654 @end example
1655
1656 The preprocessor @samp{cpp} can be invoked via the @samp{-fcpp}
1657 command line option. This in turn invokes @samp{cpp} with the
1658 following arguments @samp{-traditional -lang-asm}. These options
1659 preserve comments and all quotations. @samp{gm2} treats a @samp{#}
1660 character in the first column as a preprocessor directive.
1661
1662 For example here is a module which calls @code{FatalError}
1663 via the macro @code{ERROR}.
1664
1665 @example
1666 MODULE cpp ;
1667
1668 FROM SYSTEM IMPORT ADR, SIZE ;
1669 FROM libc IMPORT exit, printf, malloc ;
1670
1671 PROCEDURE FatalError (a, file: ARRAY OF CHAR;
1672 line: CARDINAL;
1673 func: ARRAY OF CHAR) ;
1674 BEGIN
1675 printf ("%s:%d:fatal error, %s, in %s\n",
1676 ADR (file), line, ADR (a), ADR (func)) ;
1677 exit (1)
1678 END FatalError ;
1679
1680 #define ERROR(X) FatalError(X, __FILE__, __LINE__, __FUNCTION__)
1681
1682 VAR
1683 pc: POINTER TO CARDINAL;
1684 BEGIN
1685 pc := malloc (SIZE (CARDINAL)) ;
1686 IF pc = NIL
1687 THEN
1688 ERROR ('out of memory')
1689 END
1690 END cpp.
1691 @end example
1692
1693 Another use for the C preprocessor in Modula-2 might be to turn on
1694 debugging code. For example the library module
1695 @file{FormatStrings.mod} uses procedures from @file{DynamicStrings.mod}
1696 and to track down memory leaks it was useful to track the source file
1697 and line where each string was created. Here is a section of
1698 @file{FormatStrings.mod} which shows how the debugging code was
1699 enabled and disabled by adding @code{-fcpp} to the command line.
1700
1701 @example
1702 FROM DynamicStrings IMPORT String, InitString, InitStringChar, Mark,
1703 ConCat, Slice, Index, char,
1704 Assign, Length, Mult, Dup, ConCatChar,
1705 PushAllocation, PopAllocationExemption,
1706 InitStringDB, InitStringCharStarDB,
1707 InitStringCharDB, MultDB, DupDB, SliceDB ;
1708
1709 (*
1710 #define InitString(X) InitStringDB(X, __FILE__, __LINE__)
1711 #define InitStringCharStar(X) InitStringCharStarDB(X, __FILE__, \
1712 __LINE__)
1713 #define InitStringChar(X) InitStringCharDB(X, __FILE__, __LINE__)
1714 #define Mult(X,Y) MultDB(X, Y, __FILE__, __LINE__)
1715 #define Dup(X) DupDB(X, __FILE__, __LINE__)
1716 #define Slice(X,Y,Z) SliceDB(X, Y, Z, __FILE__, __LINE__)
1717 *)
1718
1719 PROCEDURE doDSdbEnter ;
1720 BEGIN
1721 PushAllocation
1722 END doDSdbEnter ;
1723
1724 PROCEDURE doDSdbExit (s: String) ;
1725 BEGIN
1726 s := PopAllocationExemption (TRUE, s)
1727 END doDSdbExit ;
1728
1729 PROCEDURE DSdbEnter ;
1730 BEGIN
1731 END DSdbEnter ;
1732
1733 PROCEDURE DSdbExit (s: String) ;
1734 BEGIN
1735 END DSdbExit ;
1736
1737 (*
1738 #define DBsbEnter doDBsbEnter
1739 #define DBsbExit doDBsbExit
1740 *)
1741
1742 PROCEDURE Sprintf1 (s: String; w: ARRAY OF BYTE) : String ;
1743 BEGIN
1744 DSdbEnter ;
1745 s := FormatString (HandleEscape (s), w) ;
1746 DSdbExit (s) ;
1747 RETURN s
1748 END Sprintf1 ;
1749 @end example
1750
1751 It is worth noting that the overhead of this code once @code{-fcpp} is
1752 not present and -O2 is used will be zero since the local empty
1753 procedures @code{DSdbEnter} and @code{DSdbExit} will be thrown away by
1754 the optimization passes of the GCC backend.
1755
1756 @subsection Optional procedure parameter
1757
1758 GNU Modula-2 allows the last parameter to a procedure or function
1759 parameter to be optional. For example in the ISO library
1760 @file{COROUTINES.def} the procedure @code{NEWCOROUTINE} is defined as
1761 having an optional fifth argument (@code{initProtection}) which, if
1762 absent, is automatically replaced by @code{NIL}.
1763
1764 @example
1765 @findex NEWCOROUTINE
1766 PROCEDURE NEWCOROUTINE (procBody: PROC; workspace: SYSTEM.ADDRESS;
1767 size: CARDINAL; VAR cr: COROUTINE;
1768 [initProtection: PROTECTION = NIL]);
1769
1770 (* Creates a new coroutine whose body is given by procBody,
1771 and returns the identity of the coroutine in cr.
1772 workspace is a pointer to the work space allocated to
1773 the coroutine; size specifies the size of this workspace
1774 in terms of SYSTEM.LOC.
1775
1776 The optional fifth argument may contain a single parameter
1777 which specifies the initial protection level of the coroutine.
1778 *)
1779 @end example
1780
1781 The implementation module @file{COROUTINES.mod} implements this
1782 procedure using the following syntax:
1783
1784 @example
1785 PROCEDURE NEWCOROUTINE (procBody: PROC; workspace: SYSTEM.ADDRESS;
1786 size: CARDINAL; VAR cr: COROUTINE;
1787 [initProtection: PROTECTION]);
1788 BEGIN
1789
1790 END NEWCOROUTINE ;
1791 @end example
1792
1793 Note that it is illegal for this declaration to contain an initializer
1794 value for @code{initProtection}. However it is necessary to surround
1795 this parameter with the brackets @code{[} and @code{]}. This serves to
1796 remind the programmer that the last parameter was declared as optional
1797 in the definition module.
1798
1799 Local procedures can be declared to have an optional final parameter
1800 in which case the initializer is mandatory in the implementation or
1801 program module.
1802
1803 GNU Modula-2 also provides additional fixed sized data types which
1804 are all exported from the @code{SYSTEM} module.
1805 @xref{The PIM system module, , ,gm2}.
1806 @xref{The ISO system module, , ,gm2}.
1807
1808 @node Type compatibility, Unbounded by reference, Extensions, Using
1809 @section Type compatibility
1810
1811 This section discuss the issues surrounding assignment, expression
1812 and parameter compatibility, their effect of the additional
1813 fixed sized datatypes and also their effect of run time checking.
1814 The data types supported by the compiler are:
1815
1816 @example
1817 GNU Modula-2 scope switches
1818 =============================================
1819 INTEGER pervasive
1820 LONGINT pervasive
1821 SHORTINT pervasive
1822 CARDINAL pervasive
1823 LONGCARD pervasive
1824 SHORTCARD pervasive
1825 BOOLEAN pervasive
1826 BITSET pervasive
1827 REAL pervasive
1828 LONGREAL pervasive
1829 SHORTREAL pervasive
1830 CHAR pervasive
1831 SHORTCOMPLEX pervasive
1832 COMPLEX pervasive
1833 LONGCOMPLEX pervasive
1834
1835 LOC SYSTEM -fiso
1836 BYTE SYSTEM
1837 WORD SYSTEM
1838 ADDRESS SYSTEM
1839
1840 The following extensions are supported for
1841 most architectures (please check SYSTEM.def).
1842 =============================================
1843 INTEGER8 SYSTEM
1844 INTEGER16 SYSTEM
1845 INTEGER32 SYSTEM
1846 INTEGER64 SYSTEM
1847 CARDINAL8 SYSTEM
1848 CARDINAL16 SYSTEM
1849 CARDINAL32 SYSTEM
1850 CARDINAL64 SYSTEM
1851 BITSET8 SYSTEM
1852 BITSET16 SYSTEM
1853 BITSET32 SYSTEM
1854 WORD16 SYSTEM
1855 WORD32 SYSTEM
1856 WORD64 SYSTEM
1857 REAL32 SYSTEM
1858 REAL64 SYSTEM
1859 REAL96 SYSTEM
1860 REAL128 SYSTEM
1861 COMPLEX32 SYSTEM
1862 COMPLEX64 SYSTEM
1863 COMPLEX96 SYSTEM
1864 COMPLEX128 SYSTEM
1865 @end example
1866
1867 The Modula-2 language categorizes compatibility between entities of
1868 possibly differing types into three sub components: expressions,
1869 assignments, and parameters. Parameter compatibility is further
1870 divided into two sections for pass by reference and pass by value
1871 compatibility.
1872
1873 For more detail on the Modula-2 type compatibility see the Modula-2
1874 ISO standard BS ISO/IEC 10514-1:1996 page 121-125. For detail on the
1875 PIM type compatibility see Programming in Modula-2 Edition 4 page 29,
1876 (Elementary Data Types).
1877
1878 @subsection Expression compatibility
1879
1880 Modula-2 restricts the types of expressions to the same type.
1881 Expression compatibility is a symmetric relation.
1882
1883 For example two sub expressions of @code{INTEGER} and @code{CARDINAL}
1884 are not expression compatible
1885 (@uref{http://freepages.modula2.org/report4/modula-2.html} and ISO
1886 Modula-2).
1887
1888 In GNU Modula-2 this rule is also extended across all fixed sized data
1889 types (imported from SYSTEM).
1890
1891 @subsection Assignment compatibility
1892
1893 This section discusses the assignment issues surrounding assignment
1894 compatibility of elementary types (@code{INTEGER}, @code{CARDINAL},
1895 @code{REAL} and @code{CHAR} for example). The information here is
1896 found in more detail in the Modula-2 ISO standard BS ISO/IEC
1897 10514-1:1996 page 122.
1898
1899 Assignment compatibility exists between the same sized elementary
1900 types.
1901
1902 Same type family of different sizes are
1903 also compatible as long as the @code{MAX(}type@code{)} and
1904 @code{MIN(}type@code{)} is known. So for example this includes the
1905 @code{INTEGER} family, @code{CARDINAL} family and the @code{REAL}
1906 family.
1907
1908 The reason for this is that when the assignment is performed
1909 the compiler will check to see that the expression (on the right of
1910 the @code{:=}) lies within the range of the designator type (on the
1911 left hand side of the @code{:=}). Thus these ordinal types can be
1912 assignment compatible. However it does mean that @code{WORD32} is not
1913 compatible with @code{WORD16} as @code{WORD32} does not have a minimum
1914 or maximum value and therefore cannot be checked. The compiler does
1915 not know which of the two bytes from @code{WORD32} should be copied
1916 into @code{WORD16} and which two should be ignored. Currently the
1917 types @code{BITSET8}, @code{BITSET16} and @code{BITSET32} are
1918 assignment incompatible. However this restriction maybe lifted when
1919 further run time checking is achieved.
1920
1921 Modula-2 does allow @code{INTEGER} to be assignment compatible with
1922 @code{WORD} as they are the same size. Likewise GNU Modula-2 allows
1923 @code{INTEGER16} to be compatible with @code{WORD16} and the same for
1924 the other fixed sized types and their sized equivalent in either
1925 @code{WORD}n, @code{BYTE} or @code{LOC} types. However it prohibits
1926 assignment between @code{WORD} and @code{WORD32} even though on many
1927 systems these sizes will be the same. The reasoning behind this rule
1928 is that the extended fixed sized types are meant to be used by
1929 applications requiring fixed sized data types and it is more portable
1930 to forbid the blurring of the boundaries between fixed sized and
1931 machine dependent sized types.
1932
1933 Intermediate code run time checking is always generated by the front
1934 end. However this intermediate code is only translated into actual
1935 code if the appropriate command line switches are specified. This
1936 allows the compiler to perform limited range checking at compile time.
1937 In the future it will allow the extensive GCC optimizations to
1938 propagate constant values through to the range checks which if they
1939 are found to exceed the type range will result in a compile time
1940 error message.
1941
1942 @subsection Parameter compatibility
1943
1944 Parameter compatibility is divided into two areas, pass by value and
1945 pass by reference (@code{VAR}). In the case of pass by value the
1946 rules are exactly the same as assignment. However in the second case,
1947 pass by reference, the actual parameter and formal parameter must be
1948 the same size and family. Furthermore @code{INTEGER} and
1949 @code{CARDINAL}s are not treated as compatible in the pass by
1950 reference case.
1951
1952 The types @code{BYTE}, @code{LOC}, @code{WORD} and @code{WORD}n
1953 derivatives are assignment and parameter compatible with any data type
1954 of the same size.
1955
1956 @node Unbounded by reference, Building a shared library, Type compatibility, Using
1957 @section Unbounded by reference
1958
1959 This section documents a GNU Modula-2 compiler switch which implements
1960 a language optimization surrounding the implementation of unbounded
1961 arrays. In GNU Modula-2 the unbounded array is implemented by
1962 utilizing an internal structure @code{struct @{dataType *address,
1963 unsigned int high@}}. So given the Modula-2 procedure declaration:
1964
1965 @example
1966 PROCEDURE foo (VAR a: ARRAY OF dataType) ;
1967 BEGIN
1968 IF a[2]= (* etc *)
1969 END foo ;
1970 @end example
1971
1972 it is translated into GCC @code{tree}s, which can be represented
1973 in their C form thus:
1974
1975 @example
1976 void foo (struct @{dataType *address, unsigned int high@} a)
1977 @{
1978 if (a.address[2] == /* etc */
1979 @}
1980 @end example
1981
1982 Whereas if the procedure @code{foo} was declared as:
1983
1984 @example
1985 PROCEDURE foo (a: ARRAY OF dataType) ;
1986 BEGIN
1987 IF a[2]= (* etc *)
1988 END foo ;
1989 @end example
1990
1991 then it is implemented by being translated into the following
1992 GCC @code{tree}s, which can be represented in their C form thus:
1993
1994 @example
1995 void foo (struct @{dataType *address, unsigned int high@} a)
1996 @{
1997 dataType *copyContents = (dataType *)alloca (a.high+1);
1998 memcpy(copyContents, a.address, a.high+1);
1999 a.address = copyContents;
2000
2001 if (a.address[2] == /* etc */
2002 @}
2003 @end example
2004
2005 This implementation works, but it makes a copy of each non VAR
2006 unbounded array when a procedure is entered. If the unbounded array
2007 is not changed during procedure @code{foo} then this implementation
2008 will be very inefficient. In effect Modula-2 lacks the @code{REF}
2009 keyword of Ada. Consequently the programmer maybe tempted to
2010 sacrifice semantic clarity for greater efficiency by declaring the
2011 parameter using the @code{VAR} keyword in place of @code{REF}.
2012
2013 The @code{-funbounded-by-reference} switch instructs the compiler to
2014 check and see if the programmer is modifying the content of any
2015 unbounded array. If it is modified then a copy will be made upon
2016 entry into the procedure. Conversely if the content is only read and
2017 never modified then this non @code{VAR} unbounded array is a candidate
2018 for being passed by reference. It is only a candidate as it is still
2019 possible that passing this parameter by reference could alter the
2020 meaning of the source code. For example consider the following case:
2021
2022 @example
2023 PROCEDURE StrConCat (VAR a: ARRAY OF CHAR; b, c: ARRAY OF CHAR) ;
2024 BEGIN
2025 (* code which performs string a := b + c *)
2026 END StrConCat ;
2027
2028 PROCEDURE foo ;
2029 VAR
2030 a: ARRAY [0..3] OF CHAR ;
2031 BEGIN
2032 a := 'q' ;
2033 StrConCat(a, a, a)
2034 END foo ;
2035 @end example
2036
2037 In the code above we see that the same parameter, @code{a}, is being
2038 passed three times to @code{StrConCat}. Clearly even though parameters
2039 @code{b} and @code{c} are never modified it would be incorrect to
2040 implement them as pass by reference. Therefore the compiler checks to
2041 see if any non @code{VAR} parameter is type compatible with any
2042 @code{VAR} parameter and if so it generates run time procedure entry
2043 checks to determine whether the contents of parameters @code{b} or
2044 @code{c} matches the contents of @code{a}. If a match is detected
2045 then a copy is made and the @code{address} in the unbounded
2046 @code{struct}ure is modified.
2047
2048 The compiler will check the address range of each candidate against
2049 the address range of any @code{VAR} parameter, providing they are type
2050 compatible. For example consider:
2051
2052 @example
2053 PROCEDURE foo (a: ARRAY OF BYTE; VAR f: REAL) ;
2054 BEGIN
2055 f := 3.14 ;
2056 IF a[0]=BYTE(0)
2057 THEN
2058 (* etc *)
2059 END
2060 END foo ;
2061
2062 PROCEDURE bar ;
2063 BEGIN
2064 r := 2.0 ;
2065 foo(r, r)
2066 END bar ;
2067 @end example
2068
2069 Here we see that although parameter, @code{a}, is a candidate for the
2070 passing by reference, it would be incorrect to use this
2071 transformation. Thus the compiler detects that parameters, @code{a}
2072 and @code{f} are type compatible and will produce run time checking
2073 code to test whether the address range of their respective contents
2074 intersect.
2075
2076 @node Building a shared library, Interface for Python, Unbounded by reference, Using
2077 @section Building a shared library
2078
2079 This section describes building a tiny shared library implemented in
2080 Modula-2 and built with @file{libtool}. Suppose a project consists of
2081 two definition modules and two implementation modules and a program
2082 module @file{a.def}, @file{a.mod}, @file{b.def}, @file{b.mod} and
2083 @file{c.mod}. The first step is to compile the modules using position
2084 independent code. This can be achieved by the following three
2085 commands:
2086
2087 @example
2088 libtool --tag=CC --mode=compile gm2 -g -c a.mod -o a.lo
2089 libtool --tag=CC --mode=compile gm2 -g -c b.mod -o b.lo
2090 libtool --tag=CC --mode=compile gm2 -g -c c.mod -o c.lo
2091 @end example
2092
2093 The second step is to generate the shared library initialization and
2094 finalization routines. We can do this by asking gm2 to generate a
2095 list of dependent modules and then use this to generate the scaffold.
2096 We also must compile the scaffold.
2097
2098 @example
2099 gm2 -c -g -fmakelist c.mod
2100 gm2 -c -g -fmakeinit -fshared c.mod
2101 libtool --tag=CC --mode=compile g++ -g -c c_m2.cpp -o c_m2.lo
2102 @end example
2103
2104 The third step is to link all these @file{.lo} files.
2105
2106 @example
2107 libtool --mode=link gcc -g c_m2.lo a.lo b.lo c.lo \
2108 -L$(prefix)/lib64 \
2109 -rpath `pwd` -lgm2 -lstdc++ -lm -o libabc.la
2110 @end example
2111
2112 At this point the shared library @file{libabc.so} will have been
2113 created inside the directory @file{.libs}.
2114
2115 @node Interface for Python, Producing a Python module, Building a shared library, Using
2116 @section How to produce swig interface files
2117
2118 This section describes how Modula-2 implementation modules can be
2119 called from Python (and other scripting languages such as TCL and
2120 Perl). GNU Modula-2 can be instructed to create a swig interface when
2121 it is compiling an implementation module. Swig then uses the
2122 interface file to generate all the necessary wrapping to that the
2123 desired scripting language may access the implementation module.
2124
2125 Here is an example of how you might call upon the services of the
2126 Modula-2 library module @code{NumberIO} from Python3.
2127
2128 The following commands can be used to generate the Python3 module:
2129
2130 @example
2131 export src=@samp{directory to the sources}
2132 export prefix=@samp{directory to where the compiler is installed}
2133 gm2 -I$@{src@} -c -g -fswig $@{src@}/../../../gm2-libs/NumberIO.mod
2134 gm2 -I$@{src@} -c -g -fmakelist $@{src@}/../../../gm2-libs/NumberIO.mod
2135
2136 gm2 -I$@{src@} -c -g -fmakeinit -fshared \
2137 $@{src@}/../../../gm2-libs/NumberIO.mod
2138
2139 swig -c++ -python3 NumberIO.i
2140
2141 libtool --mode=compile g++ -g -c -I$@{src@} NumberIO_m2.cpp \
2142 -o NumberIO_m2.lo
2143
2144 libtool --tag=CC --mode=compile gm2 -g -c \
2145 -I$@{src@}../../../gm2-libs \
2146 $@{src@}/../../../gm2-libs/NumberIO.mod -o NumberIO.lo
2147
2148 libtool --tag=CC --mode=compile g++ -g -c NumberIO_wrap.cxx \
2149 -I/usr/include/python3 -o NumberIO_wrap.lo
2150
2151 libtool --mode=link gcc -g NumberIO_m2.lo NumberIO_wrap.lo \
2152 -L$@{prefix@}/lib64 \
2153 -rpath `pwd` -lgm2 -lstdc++ -lm -o libNumberIO.la
2154
2155 cp .libs/libNumberIO.so _NumberIO.so
2156 @end example
2157
2158 The first four commands, generate the swig interface file
2159 @file{NumberIO.i} and python wrap files @file{NumberIO_wrap.cxx} and
2160 @file{NumberIO.py}. The next three @file{libtool} commnads compile
2161 the C++ and Modula-2 source code into @file{.lo} objects. The last
2162 @file{libtool} command links all the @file{.lo} files into a
2163 @file{.la} file and includes all shared library dependencies.
2164
2165 Now it is possible to run the following Python script
2166 (called @file{testnum.py}):
2167
2168 @example
2169 import NumberIO
2170
2171 print ("1234 x 2 =", NumberIO.NumberIO_StrToInt("1234")*2)
2172 @end example
2173
2174 like this:
2175
2176 @example
2177 $ python3 testnum.py
2178 1234 x 2 = 2468
2179 @end example
2180
2181 @xref{Producing a Python module, , ,gm2} for another example which
2182 uses the @code{UNQUALIFIED} keyword to reduce the module name clutter
2183 from the viewport of Python3.
2184
2185 @subsection Limitations of automatic generated of Swig files
2186
2187 This section discusses the limitations of automatically generating
2188 swig files. From the previous example we see that the module
2189 @code{NumberIO} had a swig interface file @file{NumberIO.i}
2190 automatically generated by the compiler. If we consider three of the
2191 procedure definitions in @file{NumberIO.def} we can see the
2192 success and limitations of the automatic interface generation.
2193
2194 @example
2195 PROCEDURE StrToHex (a: ARRAY OF CHAR; VAR x: CARDINAL) ;
2196 PROCEDURE StrToInt (a: ARRAY OF CHAR; VAR x: INTEGER) ;
2197 PROCEDURE ReadInt (VAR x: CARDINAL) ;
2198 @end example
2199
2200 Below are the swig interface prototypes:
2201
2202 @example
2203 extern void NumberIO_StrToHex (char *_m2_address_a,
2204 int _m2_high_a, unsigned int *OUTPUT);
2205 /* parameters: x is known to be an OUTPUT */
2206 extern void NumberIO_StrToInt (char *_m2_address_a,
2207 int _m2_high_a, int *OUTPUT);
2208 /* parameters: x is guessed to be an OUTPUT */
2209 extern void NumberIO_ReadInt (int *x);
2210 /* parameters: x is unknown */
2211 @end example
2212
2213 In the case of @code{StrToHex} it can be seen that the compiler
2214 detects that the last parameter is an output. It explicitly tells
2215 swig this by using the parameter name @code{OUTPUT} and in the
2216 following comment it informs the user that it knows this to be an
2217 output parameter. In the second procedure @code{StrToInt} it marks
2218 the final parameter as an output, but it tells the user that this is
2219 only a guess. Finally in @code{ReadInt} it informs the user that
2220 it does not know whether the parameter, @code{x}, is an output, input
2221 or an inout parameter.
2222
2223 The compiler decides whether to mark a parameter as either:
2224 @code{INPUT}, @code{OUTPUT} or @code{INOUT} if it is read before
2225 written or visa versa in the first basic block. At this point
2226 it will write output that the parameter is known. If it is not
2227 read or written in the first basic block then subsequent basic blocks
2228 are searched and the result is commented as a guess. Finally if
2229 no read or write occurs then the parameter is commented as unknown.
2230 However, clearly it is possible to fool this mechanism. Nevertheless
2231 automatic generation of implementation module into swig interface files
2232 was thought sufficiently useful despite these limitations.
2233
2234 In conclusion it would be wise to check all parameters in any
2235 automatically generated swig interface file. Furthermore you can
2236 force the automatic mechanism to generate correct interface files by
2237 reading or writing to the @code{VAR} parameter in the first basic
2238 block of a procedure.
2239
2240 @node Producing a Python module, Interface to C, Interface for Python, Using
2241 @section How to produce a Python module
2242
2243 This section describes how it is possible to produce a Python module
2244 from Modula-2 code. There are a number of advantages to this
2245 approach, it ensures your code reaches a wider audience, maybe it is
2246 easier to initialize your application in Python.
2247
2248 The example application here is a pedagogical two dimensional gravity
2249 next event simulation. The Python module needs to have a clear API
2250 which should be placed in a single definition module. Furthermore the
2251 API should only use fundamental pervasive data types and strings.
2252 Below the API is contained in the file @file{twoDsim.def}:
2253
2254 @example
2255 DEFINITION MODULE twoDsim ;
2256
2257 EXPORT UNQUALIFIED gravity, box, poly3, poly5, poly6, mass,
2258 fix, circle, pivot, velocity, accel, fps,
2259 replayRate, simulateFor ;
2260 (*
2261 gravity - turn on gravity at: g m^2
2262 *)
2263
2264 PROCEDURE gravity (g: REAL) ;
2265
2266
2267 (*
2268 box - place a box in the world at (x0,y0),(x0+i,y0+j)
2269 *)
2270
2271 PROCEDURE box (x0, y0, i, j: REAL) : CARDINAL ;
2272
2273
2274 (*
2275 poly3 - place a triangle in the world at:
2276 (x0,y0),(x1,y1),(x2,y2)
2277 *)
2278
2279 PROCEDURE poly3 (x0, y0, x1, y1, x2, y2: REAL) : CARDINAL ;
2280
2281
2282 (*
2283 poly5 - place a pentagon in the world at:
2284 (x0,y0),(x1,y1),(x2,y2),(x3,y3),(x4,y4)
2285 *)
2286
2287 PROCEDURE poly5 (x0, y0, x1, y1,
2288 x2, y2, x3, y3, x4, y4: REAL) : CARDINAL ;
2289
2290
2291 (*
2292 poly6 - place a hexagon in the world at:
2293 (x0,y0),(x1,y1),(x2,y2),(x3,y3),(x4,y4),(x5,y5)
2294 *)
2295
2296 PROCEDURE poly6 (x0, y0, x1, y1,
2297 x2, y2, x3, y3,
2298 x4, y4, x5, y5: REAL) : CARDINAL ;
2299
2300
2301 (*
2302 mass - specify the mass of an object and return the, id.
2303 *)
2304
2305 PROCEDURE mass (id: CARDINAL; m: REAL) : CARDINAL ;
2306
2307
2308 (*
2309 fix - fix the object to the world.
2310 *)
2311
2312 PROCEDURE fix (id: CARDINAL) : CARDINAL ;
2313
2314
2315 (*
2316 circle - adds a circle to the world. Center
2317 defined by: x0, y0 radius, r.
2318 *)
2319
2320 PROCEDURE circle (x0, y0, r: REAL) : CARDINAL ;
2321
2322
2323 (*
2324 velocity - give an object, id, a velocity, vx, vy.
2325 *)
2326
2327 PROCEDURE velocity (id: CARDINAL; vx, vy: REAL) : CARDINAL ;
2328
2329
2330 (*
2331 accel - give an object, id, an acceleration, ax, ay.
2332 *)
2333
2334 PROCEDURE accel (id: CARDINAL; ax, ay: REAL) : CARDINAL ;
2335
2336
2337 (*
2338 fps - set frames per second.
2339 *)
2340
2341 PROCEDURE fps (f: REAL) ;
2342
2343
2344 (*
2345 replayRate - set frames per second during replay.
2346 *)
2347
2348 PROCEDURE replayRate (f: REAL) ;
2349
2350
2351 (*
2352 simulateFor - render for, t, seconds.
2353 *)
2354
2355 PROCEDURE simulateFor (t: REAL) ;
2356
2357
2358 END twoDsim.
2359 @end example
2360
2361 The keyword @code{UNQUALIFIED} can be used to ensure that the
2362 compiler will provide externally accessible functions
2363 @code{gravity}, @code{box}, @code{poly3}, @code{poly5}, @code{poly6},
2364 @code{mass}, @code{fix}, @code{circle}, @code{pivot}, @code{velocity},
2365 @code{accel}, @code{fps}, @code{replayRate}, @code{simulateFor}
2366 rather than name mangled alternatives.
2367 Hence in our Python3 application we could write:
2368
2369 @example
2370 #!/usr/bin/env python3
2371
2372 from twoDsim import *
2373
2374 b = box (0.0, 0.0, 1.0, 1.0)
2375 b = fix (b)
2376 c1 = circle (0.7, 0.7, 0.05)
2377 c1 = mass (c1, 0.01)
2378 c2 = circle (0.7, 0.1, 0.05)
2379 c2 = mass (c2, 0.01)
2380 c2 = fix (c2)
2381 gravity (-9.81)
2382 fps (24.0*4.0)
2383 replayRate (24.0)
2384 print ("creating frames")
2385 try:
2386 simulateFor (1.0)
2387 print ("all done")
2388 except:
2389 print ("exception raised")
2390 @end example
2391
2392 which accesses the various functions defined and implemented by the
2393 module @code{twoDsim}. The Modula-2 source code is compiled via:
2394
2395 @example
2396 $ gm2 -g -fiso -c -fswig twoDsim.mod
2397 $ gm2 -g -fiso -c -fmakelist twoDsim.mod
2398 $ gm2 -g -fiso -c -fmakeinit twoDsim.mod
2399 @end example
2400
2401 The first command both compiles the source file creating
2402 @file{twoDsim.o} and produces a swig interface file @file{swig.i}. We
2403 now use @code{swig} and @code{g++} to produce and compile the
2404 interface wrappers:
2405
2406 @example
2407 $ libtool --mode=compile g++ -g -c twoDsim_m2.cpp -o twoDsim_m2.lo
2408 $ swig -c++ -python3 twoDsim.i
2409 $ libtool --mode=compile g++ -c -fPIC twoDsim_wrap.cxx \
2410 -I/usr/include/python3 -o twoDsim_wrap.lo
2411 $ libtool --mode=compile gm2 -g -fPIC -fiso -c deviceGnuPic.mod
2412 $ libtool --mode=compile gm2 -g -fPIC -fiso -c roots.mod
2413 $ libtool --mode=compile gm2 -g -fPIC -fiso -c -fswig \
2414 twoDsim.mod -o twoDsim.lo
2415 @end example
2416
2417 Finally the application is linked into a shared library:
2418
2419 @example
2420 $ libtool --mode=link gcc -g twoDsim_m2.lo twoDsim_wrap.lo \
2421 roots.lo deviceGnuPic.lo \
2422 -L$@{prefix@}/lib64 \
2423 -rpath `pwd` -lgm2 -lstdc++ -lm -o libtwoDsim.la
2424 cp .libs/libtwoDsim.so _twoDsim.so
2425 @end example
2426
2427 The library name must start with @code{_} to comply with the Python3
2428 module naming scheme.
2429
2430 @node Interface to C, Assembly language, Producing a Python module, Using
2431 @section Interfacing GNU Modula-2 to C
2432
2433 The GNU Modula-2 compiler tries to use the C calling convention
2434 wherever possible however some parameters have no C equivalent and
2435 thus a language specific method is used. For example unbounded arrays
2436 are passed as a @code{struct @{void *address, unsigned int high@}} and
2437 the contents of these arrays are copied by callee functions when they
2438 are declared as non @code{VAR} parameters. The @code{VAR} equivalent
2439 unbounded array parameters need no copy, but still use the
2440 @code{struct} representation.
2441
2442 The recommended method of interfacing GNU Modula-2 to C is by telling
2443 the definition module that the implementation is in the C language.
2444 This is achieved by using the tokens @code{DEFINITION MODULE FOR "C"}.
2445 Here is an example @file{libprintf.def}.
2446
2447 @example
2448 DEFINITION MODULE FOR "C" libprintf ;
2449
2450 EXPORT UNQUALIFIED printf ;
2451
2452 PROCEDURE printf (a: ARRAY OF CHAR; ...) : [ INTEGER ] ;
2453
2454 END libprintf.
2455 @end example
2456
2457 the @code{UNQUALIFIED} keyword in the definition module informs
2458 GNU Modula-2 not to prefix the module name to exported references
2459 in the object file.
2460
2461 The @code{printf} declaration states that the first parameter
2462 semantically matches @code{ARRAY OF CHAR} but since the module is for
2463 the C language it will be mapped onto @code{char *}. The token
2464 @code{...} indicates a variable number of arguments (varargs) and all
2465 parameters passed here are mapped onto their C equivalents. Arrays and
2466 constant strings are passed as pointers. Lastly @code{[ INTEGER ]}
2467 states that the caller can ignore the function return result if desired.
2468
2469 The hello world program can be rewritten as:
2470
2471 @example
2472 MODULE hello ;
2473
2474 FROM libprintf IMPORT printf ;
2475
2476 BEGIN
2477 printf ("hello world\n")
2478 END hello.
2479 @end example
2480
2481 and it can be compiled by:
2482
2483 @samp{gm2 -g hello.mod -lc}
2484
2485 In reality the @samp{-lc} is redundant as libc is always included in the
2486 linking process. It is shown here to emphasize that the C library or
2487 object file containing @code{printf} must be present. The search path
2488 for modules can be changed by using @samp{-I}.
2489
2490 If a procedure function is declared using varargs then some parameter
2491 values are converted. The table below summarizes the default conversions
2492 and default types used.
2493
2494 @example
2495 Actual Parameter | Default conversion | Type of actual
2496 | | value passed
2497 ===============================================================
2498 123 | none | long long int
2499 "hello world" | none | const char *
2500 a: ARRAY OF CHAR | ADR (a) | char *
2501 a: ARRAY [0..5] OF CHAR| ADR (a) | char *
2502 3.14 | none | long double
2503 @end example
2504
2505 If you wish to pass @code{int} values then you should explicitly
2506 convert the constants using one of the conversion mechanisms.
2507 For example: @code{INTEGER(10)} or @code{VAL(INTEGER, 10)} or
2508 @code{CAST(INTEGER, 10)}.
2509
2510 @node Assembly language, Alignment, Interface to C, Using
2511 @section Interface to assembly language
2512
2513 The interface for GNU Modula-2 to assembly language is almost
2514 identical to GNU C. The only alterations are that the keywords
2515 @code{asm} and @code{volatile} are in capitals, following the Modula-2
2516 convention.
2517
2518 A simple, but highly non optimal, example is given below. Here we want
2519 to add the two @code{CARDINAL}s @code{foo} and @code{bar} together and
2520 return the result. The target processor is assumed to be executing
2521 the x86_64 instruction set.
2522
2523 @example
2524 PROCEDURE Example (foo, bar: CARDINAL) : CARDINAL ;
2525 VAR
2526 myout: CARDINAL ;
2527 BEGIN
2528 ASM VOLATILE ("movq %1,%%rax; addq %2,%%rax; movq %%rax,%0"
2529 : "=rm" (myout) (* outputs *)
2530 : "rm" (foo), "rm" (bar) (* inputs *)
2531 : "rax") ; (* we trash *)
2532 RETURN( myout )
2533 END Example ;
2534 @end example
2535
2536 For a full description of this interface we refer the reader to the GNU C manual.
2537
2538 @xref{Extended Asm, ,Extensions to the C Language Family,gcc}.
2539
2540 The same example can be written using the newer extensions of naming
2541 the operands rather than using numbered arguments.
2542
2543 @example
2544 PROCEDURE Example (foo, bar: CARDINAL) : CARDINAL ;
2545 VAR
2546 myout: CARDINAL ;
2547 BEGIN
2548 ASM VOLATILE (
2549 "movq %[left],%%rax; addq %[right],%%rax; movq %%rax,%[output]"
2550 : [output] "=rm" (myout) (* outputs *)
2551 : [left] "rm" (foo), [right] "rm" (bar) (* inputs *)
2552 : "rax") ; (* we trash *)
2553 RETURN( myout )
2554 END Example ;
2555 @end example
2556
2557 Both examples generate exactly the same code. It is worth noting that
2558 the specifier ``rm'' indicates that the operand can be either a
2559 register or memory. Of course you must choose an instruction which
2560 can take either, but this allows the compiler to take make more
2561 efficient choices depending upon the optimization level given to the
2562 compiler.
2563
2564 @node Alignment, Packed, Assembly language, Using
2565 @section Data type alignment
2566
2567 GNU Modula-2 allows you to specify alignment for types and variables.
2568 The syntax for alignment is to use the ISO pragma directives @code{<*}
2569 @code{bytealignment (} expression @code{)} and @code{*>}. These directives
2570 can be used after type and variable declarations.
2571
2572 The ebnf of the alignment production is:
2573
2574 @example
2575 Alignment := [ ByteAlignment ] =:
2576 ByteAlignment := '<*' AttributeExpression '*>' =:
2577 AlignmentExpression := "(" ConstExpression ")" =:
2578 @end example
2579
2580 The @code{Alignment} ebnf statement may be used during construction of
2581 types, records, record fields, arrays, pointers and variables. Below
2582 is an example of aligning a type so that the variable @code{bar} is
2583 aligned on a 1024 address.
2584
2585 @example
2586 MODULE align ;
2587
2588 TYPE
2589 foo = INTEGER <* bytealignment(1024) *> ;
2590
2591 VAR
2592 z : INTEGER ;
2593 bar: foo ;
2594 BEGIN
2595 END align.
2596 @end example
2597
2598 The next example aligns a variable on a 1024 byte boundary.
2599
2600 @example
2601 MODULE align2 ;
2602
2603 VAR
2604 x : CHAR ;
2605 z : ARRAY [0..255] OF INTEGER <* bytealignment(1024) *> ;
2606 BEGIN
2607 END align2.
2608 @end example
2609
2610 Here the example aligns a pointer on a 1024 byte boundary.
2611
2612 @example
2613 MODULE align4 ;
2614
2615 FROM SYSTEM IMPORT ADR ;
2616 FROM libc IMPORT exit ;
2617
2618 VAR
2619 x : CHAR ;
2620 z : POINTER TO INTEGER <* bytealignment(1024) *> ;
2621 BEGIN
2622 IF ADR(z) MOD 1024=0
2623 THEN
2624 exit(0)
2625 ELSE
2626 exit(1)
2627 END
2628 END align4.
2629 @end example
2630
2631 In example @code{align5} record field @code{y} is aligned on a 1024
2632 byte boundary.
2633
2634 @example
2635 MODULE align5 ;
2636
2637 FROM SYSTEM IMPORT ADR ;
2638 FROM libc IMPORT exit ;
2639
2640 TYPE
2641 rec = RECORD
2642 x: CHAR ;
2643 y: CHAR <* bytealignment(1024) *> ;
2644 END ;
2645 VAR
2646 r: rec ;
2647 BEGIN
2648 IF ADR(r.y) MOD 1024=0
2649 THEN
2650 exit(0)
2651 ELSE
2652 exit(1)
2653 END
2654 END align5.
2655 @end example
2656
2657 In the example below module @code{align6} declares @code{foo} as an
2658 array of 256 @code{INTEGER}s. The array @code{foo} is aligned on a
2659 1024 byte boundary.
2660
2661 @example
2662 MODULE align6 ;
2663
2664 FROM SYSTEM IMPORT ADR ;
2665 FROM libc IMPORT exit ;
2666
2667 TYPE
2668 foo = ARRAY [0..255] OF INTEGER <* bytealignment(1024) *> ;
2669
2670 VAR
2671 x : CHAR ;
2672 z : foo ;
2673 BEGIN
2674 IF ADR(z) MOD 1024=0
2675 THEN
2676 exit(0)
2677 ELSE
2678 exit(1)
2679 END
2680 END align6.
2681 @end example
2682
2683 @node Packed, Built-ins, Alignment, Using
2684 @section Packing data types
2685
2686 The pragma @code{<* bytealignment(0) *>} can be used to specify that
2687 the fields within a @code{RECORD} are to be packed. Currently this
2688 only applies to fields which are declared as subranges, ordinal types
2689 and enumerated types. Here is an example of how two subranges might
2690 be packed into a byte.
2691
2692 @example
2693 TYPE
2694 bits3c = [0..7] ;
2695 bits3i = [-4..3] ;
2696
2697 byte = RECORD
2698 <* bytealignment(0) *>
2699 x: bits3c ;
2700 <* bitsunused(2) *>
2701 y: bits3i ;
2702 END ;
2703 @end example
2704
2705 Notice that the user has specified that in between fields @code{x} and
2706 @code{y} there are two bits unused.
2707
2708 Now the user wishes to create a record with byte numbers zero and one
2709 occupied and then an @code{INTEGER32} field which is four byte
2710 aligned. In this case byte numbers two and three will be unused. The
2711 pragma @code{bytealignment} can be issued at the start of the record
2712 indicating the default alignment for the whole record and this can be
2713 overridden by individual fields if necessary.
2714
2715 @example
2716 rec = RECORD
2717 <* bytealignment (1) *> ;
2718 a, b: byte ;
2719 x: INTEGER32 <* bytealignment(4) *> ;
2720 END ;
2721 @end example
2722
2723 In the following example the user has specified that a record has two
2724 fields @code{p} and @code{q} but that there are three bytes unused between
2725 these fields.
2726
2727 @example
2728 header = RECORD
2729 <* bytealignment(1) *>
2730 p: byte ;
2731 <* bytesunused(3) *>
2732 q: byte ;
2733 END ;
2734 @end example
2735
2736 The pragma @code{<* bytesunused(x) *>} can only be used if the current
2737 field is on a byte boundary. There is also a @code{SYSTEM} pseudo
2738 procedure function @code{TBITSIZE(T)} which returns the minimum number of
2739 bits necessary to represent type @code{T}.
2740
2741 Another example of packing record bit fields is given below:
2742
2743 @example
2744 MODULE align21 ;
2745
2746 FROM libc IMPORT exit ;
2747
2748 TYPE
2749 colour = (red, blue, green, purple, white, black) ;
2750
2751 soc = PACKEDSET OF colour ;
2752
2753 rec = RECORD
2754 <* bytealignment(0) *>
2755 x: soc ;
2756 y: [-1..1] ;
2757 END ;
2758
2759 VAR
2760 r: rec ;
2761 v: CARDINAL ;
2762 BEGIN
2763 v := SIZE(r) ;
2764 IF SIZE(r)#1
2765 THEN
2766 exit(1)
2767 END ;
2768 r.x := soc@{blue@} ;
2769 IF r.x#soc@{blue@}
2770 THEN
2771 exit(2)
2772 END
2773 END align21.
2774 @end example
2775
2776 Here we see that the total size of this record is one byte and consists
2777 of a six bit set type followed by a 2 bit integer subrange.
2778
2779 @node Built-ins, The PIM system module, Packed, Using
2780 @section Accessing GNU Modula-2 Built-ins
2781
2782 This section describes the built-in constants and functions defined in
2783 GNU Modula-2. The following compiler constants can be accessed using
2784 the @code{__ATTRIBUTE__} @code{__BUILTIN__} keywords. These are not
2785 part of the Modula-2 language and they may differ depending upon the
2786 target architecture but they provide a method whereby common
2787 libraries can interface to a different underlying architecture.
2788
2789 The built-in constants are: @code{BITS_PER_UNIT}, @code{BITS_PER_WORD},
2790 @code{BITS_PER_CHAR} and @code{UNITS_PER_WORD}. They are integrated into
2791 GNU Modula-2 by an extension to the @code{ConstFactor} rule:
2792
2793 @example
2794 ConstFactor := ConstQualidentOrSet | Number | ConstString |
2795 "(" ConstExpression ")" | "NOT" ConstFactor |
2796 ConstAttribute =:
2797
2798 ConstAttribute := "__ATTRIBUTE__" "__BUILTIN__" "(" "(" Ident ")" ")" =:
2799 @end example
2800
2801 Here is an example taken from the ISO library @code{SYSTEM.def}:
2802
2803 @example
2804 CONST
2805 BITSPERLOC = __ATTRIBUTE__ __BUILTIN__ ((BITS_PER_UNIT)) ;
2806 LOCSPERWORD = __ATTRIBUTE__ __BUILTIN__ ((UNITS_PER_WORD)) ;
2807 @end example
2808
2809 Built-in functions are transparent to the end user. All built-in
2810 functions are declared in @code{DEFINITION MODULE}s and are imported
2811 as and when required. Built-in functions are declared in definition
2812 modules by using the @code{__BUILTIN__} keyword. Here is a section of
2813 the ISO library @code{LongMath.def} which demonstrates this feature.
2814
2815 @example
2816 PROCEDURE __BUILTIN__ sqrt (x: LONGREAL): LONGREAL;
2817 (* Returns the square root of x *)
2818 @end example
2819
2820 This indicates that the function @code{sqrt} will be implemented using
2821 the gcc built-in maths library. If gcc cannot utilize the built-in
2822 function (for example if the programmer requested the address of
2823 @code{sqrt}) then code is generated to call the alternative function
2824 implemented in the @code{IMPLEMENTATION} @code{MODULE}.
2825
2826 Sometimes a function exported from the @code{DEFINITION} @code{MODULE}
2827 will have a different name from the built-in function within gcc. In
2828 such cases the mapping between the GNU Modula-2 function name and the
2829 gcc name is expressed using the keywords @code{__ATTRIBUTE__}
2830 @code{__BUILTIN__} @code{((Ident))}. For example the function
2831 @code{sqrt} in @code{LongMath.def} maps onto the gcc built-in function
2832 @code{sqrtl} and this is expressed as:
2833
2834 @example
2835 PROCEDURE __ATTRIBUTE__ __BUILTIN__ ((sqrtl)) sqrt
2836 (x: LONGREAL) : LONGREAL;
2837 (* Returns the positive square root of x *)
2838 @end example
2839
2840 The following module @code{Builtins.def} enumerates the list of
2841 built-in functions which can be accessed in GNU Modula-2. It also
2842 serves to define the parameter and return value for each function:
2843
2844 @include m2/Builtins.texi
2845
2846 Although this module exists and will result in the generation of
2847 in-line code if optimization flags are passed to GNU Modula-2, users
2848 are advised to utilize the same functions from more generic libraries.
2849 The built-in mechanism will be applied to these generic
2850 libraries where appropriate. Note for the mathematical routines to
2851 be in-lined you need to specify the @samp{-ffast-math -O} options.
2852
2853 @node The PIM system module, The ISO system module, Built-ins, Using
2854 @section The PIM system module
2855
2856 @include m2/SYSTEM-pim.texi
2857
2858 The different dialects of Modula-2 PIM-[234] and ISO Modula-2 declare
2859 the function @code{SIZE} in different places. PIM-[34] and ISO
2860 Modula-2 declare @code{SIZE} as a pervasive function (declared in the
2861 base module). PIM-2 defined @code{SIZE} in the @code{SYSTEM} module
2862 (as shown above).
2863
2864 GNU Modula-2 allows users to specify the dialect of Modula-2 by using
2865 the @code{-fiso} and @code{-fpim2} command line switches.
2866
2867 The data types @code{CSIZE_T} and @code{CSSIZE_T} are also exported from
2868 the @code{SYSTEM} module. The type @code{CSIZE_T} is unsigned and is
2869 mapped onto the target C data type @code{size_t} whereas the type
2870 @code{CSSIZE_T} is mapped onto the signed C data type @code{ssize_t}.
2871
2872 It is anticipated that these should only be used to provide cross
2873 platform definition modules for C libraries.
2874
2875 There are also a variety of fixed sized @code{INTEGER} and
2876 @code{CARDINAL} types. The variety of the fixed sized types will
2877 depend upon the target architecture.
2878
2879 @node The ISO system module, Release map, The PIM system module, Using
2880 @section The ISO system module
2881
2882 @include m2/SYSTEM-iso.texi
2883
2884 The data types @code{CSIZE_T} and @code{CSSIZE_T} are also exported from
2885 the @code{SYSTEM} module. The type @code{CSIZE_T} is unsigned and is
2886 mapped onto the target C data type @code{size_t} whereas the type
2887 @code{CSSIZE_T} is mapped onto the signed C data type @code{ssize_t}.
2888
2889 It is anticipated that these should only be used to provide cross
2890 platform definition modules for C libraries.
2891
2892 There are also a variety of fixed sized @code{INTEGER} and
2893 @code{CARDINAL} types. The variety of the fixed sized types will
2894 depend upon the target architecture.
2895
2896 @node Release map, Documentation, The ISO system module, Using
2897 @section Release map
2898
2899 GNU Modula-2 is now part of GCC and therefore will adopt the GCC
2900 release schedule. It is intended that GNU Modula-2 implement more of
2901 the GCC builtins (vararg access) and GCC features.
2902
2903 There is an intention to implement the ISO generics and the M2R10
2904 dialect of Modula-2. It will also implement all language changes. If
2905 you wish to see something different please email
2906 @email{gm2@@nongnu.org} with your ideas.
2907
2908 @node Documentation, Regression tests, Release map, Using
2909 @section Documentation
2910
2911 The GNU Modula-2 documentation is available on line
2912 @url{https://gcc.gnu.org/onlinedocs}
2913 or in the pdf, info, html file format.
2914
2915 @node Regression tests, Limitations, Documentation, Using
2916 @section Regression tests for gm2 in the repository
2917
2918 The regression testsuite can be run from the gcc build directory:
2919
2920 @example
2921 $ cd build-gcc
2922 $ make check -j 24
2923 @end example
2924
2925 which runs the complete testsuite for all compilers using 24 parallel
2926 invocations of the compiler. Individual language testsuites can be
2927 run by specifying the language, for example the Modula-2 testsuite can
2928 be run using:
2929
2930 @example
2931 $ cd build-gcc
2932 $ make check-m2 -j 24
2933 @end example
2934
2935 Finally the results of the testsuite can be emailed to the
2936 @url{https://gcc.gnu.org/lists.html, gcc-testresults} list using the
2937 @file{test_summary} script found in the gcc source tree:
2938
2939 @example
2940 $ @samp{directory to the sources}/contrib/test_summary
2941 @end example
2942
2943 @node Limitations, Objectives, Regression tests, Using
2944 @section Limitations
2945
2946 Logitech compatibility library is incomplete. The principle modules
2947 for this platform exist however for a comprehensive list of completed
2948 modules please check the documentation
2949 @url{gm2.html}.
2950
2951 @node Objectives, FAQ, Limitations, Using
2952 @section Objectives
2953
2954 @itemize @bullet
2955
2956 @item
2957 The intention of GNU Modula-2 is to provide a production Modula-2
2958 front end to GCC.
2959
2960 @item
2961 It should support all Niklaus Wirth PIM Dialects [234] and also ISO
2962 Modula-2 including a re-implementation of all the ISO modules.
2963
2964 @item
2965 There should be an easy interface to C.
2966
2967 @item
2968 Exploit the features of GCC.
2969
2970 @item
2971 Listen to the requests of the users.
2972 @end itemize
2973
2974 @node FAQ, Community, Objectives, Using
2975 @section FAQ
2976
2977 @subsection Why use the C++ exception mechanism in GCC, rather than a bespoke Modula-2 mechanism?
2978
2979 The C++ mechanism is tried and tested, it also provides GNU Modula-2
2980 with the ability to link with C++ modules and via swig it can raise
2981 Python exceptions.
2982
2983 @node Community, Other languages, FAQ, Using
2984 @section Community
2985
2986 You can subscribe to the GNU Modula-2 mailing by sending an
2987 email to:
2988 @email{gm2-subscribe@@nongnu.org}
2989 or by
2990 @url{http://lists.nongnu.org/mailman/listinfo/gm2}.
2991 The mailing list contents can be viewed
2992 @url{http://lists.gnu.org/archive/html/gm2}.
2993
2994 @node Other languages, , Community, Using
2995 @section Other languages for GCC
2996
2997 These exist and can be found on the frontends web page on the
2998 @uref{http://gcc.gnu.org/frontends.html, gcc web site}.
2999
3000 @node License, Copying, Using, Top
3001 @section License of GNU Modula-2
3002
3003 GNU Modula-2 is free software, the compiler is held under the GPL v3
3004 @uref{http://www.gnu.org/licenses/gpl.txt},
3005 its libraries (pim, iso and Logitech compatible) are under the
3006 GPL v3 with the GCC run time library exception clause.
3007
3008 Under Section 7 of GPL version 3, you are granted additional
3009 permissions described in the GCC Runtime Library Exception, version
3010 3.1, as published by the Free Software Foundation.
3011
3012 You should have received a copy of the GNU General Public License and
3013 a copy of the GCC Runtime Library Exception along with this program;
3014 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
3015 <http://www.gnu.org/licenses/>.
3016
3017 More information on how these licenses work is available
3018 @uref{http://www.gnu.org/licenses/licenses.html} on the GNU web site.
3019
3020 @node Copying, Contributing, License, Top
3021 @include gpl_v3_without_node.texi
3022
3023 @node Contributing, EBNF, Copying, Top
3024 @section Contributing to GNU Modula-2
3025
3026 Please do and please read the GNU Emacs info under
3027
3028 @example
3029 * Standards: (standards). GNU coding standards.
3030 * Intellectual Property:: Keeping Free Software Free
3031 * Reading Non-Free Code:: Referring to Proprietary Programs
3032 * Contributions:: Accepting Contributions
3033 @end example
3034
3035 You might consider joining the GM2 Mailing list before you start
3036 coding. The mailing list may be subscribed via a web interface
3037 @uref{http://lists.nongnu.org/mailman/listinfo/gm2} or via email
3038 @email{gm2-subscribe@@nongnu.org}.
3039
3040 Many thanks and enjoy your coding!
3041
3042 @c @node Internals, , ,
3043
3044 @c This section is still being written.
3045 @c @include gm2-internals.texi
3046
3047 @node EBNF, Libraries, Contributing, Top
3048 @chapter EBNF of GNU Modula-2
3049
3050 This chapter contains the EBNF of GNU Modula-2. This grammar currently
3051 supports both PIM and ISO dialects. The rules here are automatically
3052 extracted from the crammer files in GNU Modula-2 and serve to document
3053 the syntax of the extensions described earlier and how they fit in
3054 with the base language.
3055
3056 Note that the first six productions are built into the lexical analysis
3057 phase.
3058
3059 @include m2/gm2-ebnf.texi
3060
3061 @node Libraries, Indices, EBNF, Top
3062 @chapter PIM and ISO library definitions
3063
3064 This chapter contains M2F, PIM and ISO libraries.
3065
3066 @include m2/gm2-libs.texi
3067
3068 @node Indices, , Libraries, Top
3069 @section Indices
3070
3071 @ifhtml
3072 @menu
3073 * Contents:: Section and subsections.
3074 * Functions:: Function, constants, types, ebnf indices.
3075 @end menu
3076
3077 @node Contents, , ,
3078 @section Section and subsections
3079 @printindex cp
3080
3081 @node Functions, , ,
3082 @section Function, constants, types, ebnf indices.
3083 @end ifhtml
3084
3085 @printindex fn
3086
3087 @summarycontents
3088 @contents
3089 @bye