1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1998-2008, Free Software Foundation, Inc. --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
24 ------------------------------------------------------------------------------
26 with Ada.Characters.Conversions; use Ada.Characters.Conversions;
27 with Ada.Command_Line; use Ada.Command_Line;
28 with Ada.Directories; use Ada.Directories;
29 with Ada.Streams.Stream_IO; use Ada.Streams;
30 with Ada.Text_IO; use Ada.Text_IO;
31 with System.CRTL; use System; use System.CRTL;
33 with GNAT.Command_Line; use GNAT.Command_Line;
34 with GNAT.OS_Lib; use GNAT.OS_Lib;
35 with GNAT.Heap_Sort_G;
39 with Switch; use Switch;
44 Config_File_Name : constant String_Access := new String'("gnat.adc");
45 -- The name of the file holding the GNAT configuration pragmas
47 Gcc : String_Access := new String'("gcc");
48 -- May be modified by switch --GCC=
50 Gcc_Set : Boolean := False;
51 -- True if a switch --GCC= is used
53 Gnat_Cmd : String_Access;
54 -- Command to execute the GNAT compiler
56 Gnat_Args : Argument_List_Access :=
61 new String'("-gnats"),
62 new String'("-gnatu"));
63 -- Arguments used in Gnat_Cmd call
65 EOF : constant Character := Character'Val (26);
66 -- Special character to signal end of file. Not required in input files,
67 -- but properly treated if present. Not generated in output files except
68 -- as a result of copying input file.
74 subtype File_Num is Natural;
75 subtype File_Offset is Natural;
77 type File_Entry is record
79 -- Name of chop file or directory
81 SR_Name : String_Access;
82 -- Null unless the chop file starts with a source reference pragma
83 -- in which case this field points to the file name from this pragma.
86 package File is new GNAT.Table
87 (Table_Component_Type => File_Entry,
88 Table_Index_Type => File_Num,
91 Table_Increment => 100);
93 Directory : String_Access;
94 -- Record name of directory, or a null string if no directory given
96 Compilation_Mode : Boolean := False;
97 Overwrite_Files : Boolean := False;
98 Preserve_Mode : Boolean := False;
99 Quiet_Mode : Boolean := False;
100 Source_References : Boolean := False;
101 Verbose_Mode : Boolean := False;
102 Exit_On_Error : Boolean := False;
105 Write_gnat_adc : Boolean := False;
106 -- Gets set true if we append to gnat.adc or create a new gnat.adc.
107 -- Used to inhibit complaint about no units generated.
113 type Line_Num is new Natural;
114 -- Line number (for source reference pragmas)
116 type Unit_Count_Type is new Integer;
117 subtype Unit_Num is Unit_Count_Type range 1 .. Unit_Count_Type'Last;
118 -- Used to refer to unit number in unit table
120 type SUnit_Num is new Integer;
121 -- Used to refer to entry in sorted units table. Note that entry
122 -- zero is only for use by Heapsort, and is not otherwise referenced.
124 type Unit_Kind is (Unit_Spec, Unit_Body, Config_Pragmas);
126 -- Structure to contain all necessary information for one unit.
127 -- Entries are also temporarily used to record config pragma sequences.
129 type Unit_Info is record
130 File_Name : String_Access;
131 -- File name from GNAT output line
133 Chop_File : File_Num;
134 -- File number in chop file sequence
136 Start_Line : Line_Num;
137 -- Line number from GNAT output line
139 Offset : File_Offset;
140 -- Offset name from GNAT output line
142 SR_Present : Boolean;
143 -- Set True if SR parameter present
145 Length : File_Offset;
146 -- A length of 0 means that the Unit is the last one in the file
149 -- Indicates kind of unit
151 Sorted_Index : SUnit_Num;
152 -- Index of unit in sorted unit list
154 Bufferg : String_Access;
155 -- Pointer to buffer containing configuration pragmas to be prepended.
156 -- Null if no pragmas to be prepended.
159 -- The following table stores the unit offset information
161 package Unit is new GNAT.Table
162 (Table_Component_Type => Unit_Info,
163 Table_Index_Type => Unit_Count_Type,
164 Table_Low_Bound => 1,
165 Table_Initial => 500,
166 Table_Increment => 100);
168 -- The following table is used as a sorted index to the Unit.Table.
169 -- The entries in Unit.Table are not moved, instead we just shuffle
170 -- the entries in Sorted_Units. Note that the zeroeth entry in this
171 -- table is used by GNAT.Heap_Sort_G.
173 package Sorted_Units is new GNAT.Table
174 (Table_Component_Type => Unit_Num,
175 Table_Index_Type => SUnit_Num,
176 Table_Low_Bound => 0,
177 Table_Initial => 500,
178 Table_Increment => 100);
180 function Is_Duplicated (U : SUnit_Num) return Boolean;
181 -- Returns true if U is duplicated by a later unit.
182 -- Note that this function returns false for the last entry.
184 procedure Sort_Units;
185 -- Sort units and set up sorted unit table
187 ----------------------
188 -- File_Descriptors --
189 ----------------------
191 function dup (handle : File_Descriptor) return File_Descriptor;
192 function dup2 (from, to : File_Descriptor) return File_Descriptor;
194 ---------------------
195 -- Local variables --
196 ---------------------
198 Warning_Count : Natural := 0;
199 -- Count of warnings issued so far
201 -----------------------
202 -- Local subprograms --
203 -----------------------
205 procedure Error_Msg (Message : String; Warning : Boolean := False);
206 -- Produce an error message on standard error output
208 procedure File_Time_Stamp (Name : C_File_Name; Time : OS_Time);
209 -- Given the name of a file or directory, Name, set the
210 -- time stamp. This function must be used for an unopened file.
212 function Files_Exist return Boolean;
213 -- Check Unit.Table for possible file names that already exist
214 -- in the file system. Returns true if files exist, False otherwise
216 function Get_Maximum_File_Name_Length return Integer;
217 pragma Import (C, Get_Maximum_File_Name_Length,
218 "__gnat_get_maximum_file_name_length");
219 -- Function to get maximum file name length for system
221 Maximum_File_Name_Length : constant Integer := Get_Maximum_File_Name_Length;
222 Maximum_File_Name_Length_String : constant String :=
224 (Maximum_File_Name_Length);
226 function Locate_Executable
227 (Program_Name : String;
228 Look_For_Prefix : Boolean := True) return String_Access;
229 -- Locate executable for given program name. This takes into account
230 -- the target-prefix of the current command, if Look_For_Prefix is True.
232 subtype EOL_Length is Natural range 0 .. 2;
233 -- Possible lengths of end of line sequence
235 type EOL_String (Len : EOL_Length := 0) is record
236 Str : String (1 .. Len);
240 (Source : not null access String;
241 Start : Positive) return EOL_String;
242 -- Return the line terminator used in the passed string
245 (Source : not null access String;
246 Ptr : in out Positive);
247 -- On return Source (Ptr) is the first character of the next line
248 -- or EOF. Source.all must be terminated by EOF.
250 function Parse_File (Num : File_Num) return Boolean;
251 -- Calls the GNAT compiler to parse the given source file and parses the
252 -- output using Parse_Offset_Info. Returns True if parse operation
253 -- completes, False if some system error (e.g. failure to read the
254 -- offset information) occurs.
256 procedure Parse_Offset_Info
257 (Chop_File : File_Num;
258 Source : not null access String);
259 -- Parses the output of the compiler indicating the offsets
260 -- and names of the compilation units in Chop_File.
262 procedure Parse_Token
263 (Source : not null access String;
264 Ptr : in out Positive;
265 Token_Ptr : out Positive);
266 -- Skips any separators and stores the start of the token in Token_Ptr.
267 -- Then stores the position of the next separator in Ptr.
268 -- On return Source (Token_Ptr .. Ptr - 1) is the token.
271 (FD : File_Descriptor;
272 Contents : out String_Access;
273 Success : out Boolean);
274 -- Reads file associated with FS into the newly allocated
276 -- [VMS] Success is true iff the number of bytes read is less than or
277 -- equal to the file size.
278 -- [Other] Success is true iff the number of bytes read is equal to
281 function Report_Duplicate_Units return Boolean;
282 -- Output messages about duplicate units in the input files in Unit.Table
283 -- Returns True if any duplicates found, False if no duplicates found.
285 function Scan_Arguments return Boolean;
286 -- Scan command line options and set global variables accordingly.
287 -- Also scan out file and directory arguments. Returns True if scan
288 -- was successful, and False if the scan fails for any reason.
291 -- Output message on standard output describing syntax of gnatchop command
293 procedure Warning_Msg (Message : String);
294 -- Output a warning message on standard error and update warning count
296 function Write_Chopped_Files (Input : File_Num) return Boolean;
297 -- Write all units that result from chopping the Input file
299 procedure Write_Config_File (Input : File_Num; U : Unit_Num);
300 -- Call to write configuration pragmas (append them to gnat.adc)
301 -- Input is the file number for the chop file and U identifies the
302 -- unit entry for the configuration pragmas.
304 function Get_Config_Pragmas
306 U : Unit_Num) return String_Access;
307 -- Call to read configuration pragmas from given unit entry, and
308 -- return a buffer containing the pragmas to be appended to
309 -- following units. Input is the file number for the chop file and
310 -- U identifies the unit entry for the configuration pragmas.
312 procedure Write_Source_Reference_Pragma
315 File : Stream_IO.File_Type;
317 Success : in out Boolean);
318 -- If Success is True on entry, writes a source reference pragma using
319 -- the chop file from Info, and the given line number. On return Success
320 -- indicates whether the write succeeded. If Success is False on entry,
321 -- or if the global flag Source_References is False, then the call to
322 -- Write_Source_Reference_Pragma has no effect. EOL indicates the end
323 -- of line sequence to be written at the end of the pragma.
326 (Source : not null access String;
329 Success : out Boolean);
330 -- Write one compilation unit of the source to file
336 function dup (handle : File_Descriptor) return File_Descriptor is
338 return File_Descriptor (System.CRTL.dup (int (handle)));
345 function dup2 (from, to : File_Descriptor) return File_Descriptor is
347 return File_Descriptor (System.CRTL.dup2 (int (from), int (to)));
354 procedure Error_Msg (Message : String; Warning : Boolean := False) is
356 Put_Line (Standard_Error, Message);
359 Set_Exit_Status (Failure);
361 if Exit_On_Error then
362 raise Types.Terminate_Program;
367 ---------------------
368 -- File_Time_Stamp --
369 ---------------------
371 procedure File_Time_Stamp (Name : C_File_Name; Time : OS_Time) is
372 procedure Set_File_Time (Name : C_File_Name; Time : OS_Time);
373 pragma Import (C, Set_File_Time, "__gnat_set_file_time_name");
376 Set_File_Time (Name, Time);
383 function Files_Exist return Boolean is
384 Exists : Boolean := False;
387 for SNum in 1 .. SUnit_Num (Unit.Last) loop
389 -- Only check and report for the last instance of duplicated files
391 if not Is_Duplicated (SNum) then
393 Info : constant Unit_Info :=
394 Unit.Table (Sorted_Units.Table (SNum));
397 if Is_Writable_File (Info.File_Name.all) then
398 if Hostparm.OpenVMS then
401 & " already exists, use /OVERWRITE to overwrite");
403 Error_Msg (Info.File_Name.all
404 & " already exists, use -w to overwrite");
416 ------------------------
417 -- Get_Config_Pragmas --
418 ------------------------
420 function Get_Config_Pragmas
425 Info : Unit_Info renames Unit.Table (U);
426 FD : File_Descriptor;
427 Name : aliased constant String :=
428 File.Table (Input).Name.all & ASCII.NUL;
429 Length : File_Offset;
430 Buffer : String_Access;
431 Result : String_Access;
434 pragma Warnings (Off, Success);
437 FD := Open_Read (Name'Address, Binary);
439 if FD = Invalid_FD then
440 Error_Msg ("cannot open " & File.Table (Input).Name.all);
444 Read_File (FD, Buffer, Success);
446 -- A length of 0 indicates that the rest of the file belongs to
447 -- this unit. The actual length must be calculated now. Take into
448 -- account that the last character (EOF) must not be written.
450 if Info.Length = 0 then
451 Length := Buffer'Last - (Buffer'First + Info.Offset);
453 Length := Info.Length;
456 Result := new String'(Buffer (1 .. Length));
459 end Get_Config_Pragmas;
466 (Source : not null access String;
470 Ptr : Positive := Start;
475 -- Skip to end of line
477 while Source (Ptr) /= ASCII.CR and then
478 Source (Ptr) /= ASCII.LF and then
486 if Source (Ptr) /= EOF then
498 if Source (Ptr) = ASCII.CR and then Source (Ptr + 1) = ASCII.LF then
502 return (Len => Last + 1 - First, Str => Source (First .. Last));
509 function Is_Duplicated (U : SUnit_Num) return Boolean is
511 return U < SUnit_Num (Unit.Last)
513 Unit.Table (Sorted_Units.Table (U)).File_Name.all =
514 Unit.Table (Sorted_Units.Table (U + 1)).File_Name.all;
517 -----------------------
518 -- Locate_Executable --
519 -----------------------
521 function Locate_Executable
522 (Program_Name : String;
523 Look_For_Prefix : Boolean := True) return String_Access
525 Gnatchop_Str : constant String := "gnatchop";
526 Current_Command : constant String := Normalize_Pathname (Command_Name);
527 End_Of_Prefix : Natural;
528 Start_Of_Prefix : Positive;
529 Start_Of_Suffix : Positive;
530 Result : String_Access;
533 Start_Of_Prefix := Current_Command'First;
534 Start_Of_Suffix := Current_Command'Last + 1;
535 End_Of_Prefix := Start_Of_Prefix - 1;
537 if Look_For_Prefix then
539 -- Find Start_Of_Prefix
541 for J in reverse Current_Command'Range loop
542 if Current_Command (J) = '/' or
543 Current_Command (J) = Directory_Separator or
544 Current_Command (J) = ':'
546 Start_Of_Prefix := J + 1;
551 -- Find End_Of_Prefix
553 for J in Start_Of_Prefix ..
554 Current_Command'Last - Gnatchop_Str'Length + 1
556 if Current_Command (J .. J + Gnatchop_Str'Length - 1) =
559 End_Of_Prefix := J - 1;
565 if End_Of_Prefix > Current_Command'First then
566 Start_Of_Suffix := End_Of_Prefix + Gnatchop_Str'Length + 1;
570 Command : constant String :=
571 Current_Command (Start_Of_Prefix .. End_Of_Prefix)
573 & Current_Command (Start_Of_Suffix ..
574 Current_Command'Last);
576 Result := Locate_Exec_On_Path (Command);
578 if Result = null then
580 (Command & ": installation problem, executable not found");
585 end Locate_Executable;
592 (Source : not null access String;
593 Ptr : in out Positive) is
595 -- Skip to end of line
597 while Source (Ptr) /= ASCII.CR and then Source (Ptr) /= ASCII.LF
598 and then Source (Ptr) /= EOF
603 if Source (Ptr) /= EOF then
604 Ptr := Ptr + 1; -- skip CR or LF
607 -- Skip past CR/LF or LF/CR combination
609 if (Source (Ptr) = ASCII.CR or Source (Ptr) = ASCII.LF)
610 and then Source (Ptr) /= Source (Ptr - 1)
620 function Parse_File (Num : File_Num) return Boolean is
621 Chop_Name : constant String_Access := File.Table (Num).Name;
622 Save_Stdout : constant File_Descriptor := dup (Standout);
623 Offset_Name : Temp_File_Name;
624 Offset_FD : File_Descriptor;
625 Buffer : String_Access;
630 -- Display copy of GNAT command if verbose mode
635 for J in 1 .. Gnat_Args'Length loop
637 Put (Gnat_Args (J).all);
641 Put_Line (Chop_Name.all);
644 -- Create temporary file
646 Create_Temp_File (Offset_FD, Offset_Name);
648 if Offset_FD = Invalid_FD then
649 Error_Msg ("gnatchop: cannot create temporary file");
654 -- Redirect Stdout to this temporary file in the Unix way
656 if dup2 (Offset_FD, Standout) = Invalid_FD then
657 Error_Msg ("gnatchop: cannot redirect stdout to temporary file");
663 -- Call Gnat on the source filename argument with special options
664 -- to generate offset information. If this special compilation completes
665 -- successfully then we can do the actual gnatchop operation.
667 Spawn (Gnat_Cmd.all, Gnat_Args.all & Chop_Name, Success);
670 Error_Msg (Chop_Name.all & ": parse errors detected");
671 Error_Msg (Chop_Name.all & ": chop may not be successful");
676 if dup2 (Save_Stdout, Standout) = Invalid_FD then
677 Error_Msg ("gnatchop: cannot restore stdout");
680 -- Reopen the file to start reading from the beginning
684 Offset_FD := Open_Read (Offset_Name'Address, Binary);
686 if Offset_FD = Invalid_FD then
687 Error_Msg ("gnatchop: cannot access offset info");
691 Read_File (Offset_FD, Buffer, Success);
694 Error_Msg ("gnatchop: error reading offset info");
698 Parse_Offset_Info (Num, Buffer);
701 -- Close and delete temporary file
704 Delete_File (Offset_Name'Address, Success);
709 when Failure | Types.Terminate_Program =>
711 Delete_File (Offset_Name'Address, Success);
716 -----------------------
717 -- Parse_Offset_Info --
718 -----------------------
720 procedure Parse_Offset_Info
721 (Chop_File : File_Num;
722 Source : not null access String)
724 First_Unit : constant Unit_Num := Unit.Last + 1;
725 Bufferg : String_Access := null;
726 Parse_Ptr : File_Offset := Source'First;
727 Token_Ptr : File_Offset;
730 function Match (Literal : String) return Boolean;
731 -- Checks if given string appears at the current Token_Ptr location
732 -- and if so, bumps Parse_Ptr past the token and returns True. If
733 -- the string is not present, sets Parse_Ptr to Token_Ptr and
740 function Match (Literal : String) return Boolean is
742 Parse_Token (Source, Parse_Ptr, Token_Ptr);
744 if Source'Last + 1 - Token_Ptr < Literal'Length
746 Source (Token_Ptr .. Token_Ptr + Literal'Length - 1) /= Literal
748 Parse_Ptr := Token_Ptr;
752 Parse_Ptr := Token_Ptr + Literal'Length;
756 -- Start of processing for Parse_Offset_Info
760 -- Set default values, should get changed for all
761 -- units/pragmas except for the last
763 Info.Chop_File := Chop_File;
766 -- Parse the current line of offset information into Info
767 -- and exit the loop if there are any errors or on EOF.
769 -- First case, parse a line in the following format:
771 -- Unit x (spec) line 7, file offset 142, [SR, ]file name x.ads
773 -- Note that the unit name can be an operator name in quotes.
774 -- This is of course illegal, but both GNAT and gnatchop handle
775 -- the case so that this error does not interfere with chopping.
777 -- The SR ir present indicates that a source reference pragma
778 -- was processed as part of this unit (and that therefore no
779 -- Source_Reference pragma should be generated.
781 if Match ("Unit") then
782 Parse_Token (Source, Parse_Ptr, Token_Ptr);
784 if Match ("(body)") then
785 Info.Kind := Unit_Body;
786 elsif Match ("(spec)") then
787 Info.Kind := Unit_Spec;
792 exit when not Match ("line");
793 Parse_Token (Source, Parse_Ptr, Token_Ptr);
794 Info.Start_Line := Line_Num'Value
795 (Source (Token_Ptr .. Parse_Ptr - 1));
797 exit when not Match ("file offset");
798 Parse_Token (Source, Parse_Ptr, Token_Ptr);
799 Info.Offset := File_Offset'Value
800 (Source (Token_Ptr .. Parse_Ptr - 1));
802 Info.SR_Present := Match ("SR, ");
804 exit when not Match ("file name");
805 Parse_Token (Source, Parse_Ptr, Token_Ptr);
806 Info.File_Name := new String'
807 (Directory.all & Source (Token_Ptr .. Parse_Ptr - 1));
808 Parse_EOL (Source, Parse_Ptr);
810 -- Second case, parse a line of the following form
812 -- Configuration pragmas at line 10, file offset 223
814 elsif Match ("Configuration pragmas at") then
815 Info.Kind := Config_Pragmas;
816 Info.File_Name := Config_File_Name;
818 exit when not Match ("line");
819 Parse_Token (Source, Parse_Ptr, Token_Ptr);
820 Info.Start_Line := Line_Num'Value
821 (Source (Token_Ptr .. Parse_Ptr - 1));
823 exit when not Match ("file offset");
824 Parse_Token (Source, Parse_Ptr, Token_Ptr);
825 Info.Offset := File_Offset'Value
826 (Source (Token_Ptr .. Parse_Ptr - 1));
828 Parse_EOL (Source, Parse_Ptr);
830 -- Third case, parse a line of the following form
832 -- Source_Reference pragma for file "filename"
834 -- This appears at the start of the file only, and indicates
835 -- the name to be used on any generated Source_Reference pragmas.
837 elsif Match ("Source_Reference pragma for file ") then
838 Parse_Token (Source, Parse_Ptr, Token_Ptr);
839 File.Table (Chop_File).SR_Name :=
840 new String'(Source (Token_Ptr + 1 .. Parse_Ptr - 2));
841 Parse_EOL (Source, Parse_Ptr);
844 -- Unrecognized keyword or end of file
850 -- Store the data in the Info record in the Unit.Table
853 Unit.Table (Unit.Last) := Info;
855 -- If this is not the first unit from the file, calculate
856 -- the length of the previous unit as difference of the offsets
858 if Unit.Last > First_Unit then
859 Unit.Table (Unit.Last - 1).Length :=
860 Info.Offset - Unit.Table (Unit.Last - 1).Offset;
863 -- If not in compilation mode combine current unit with any
864 -- preceding configuration pragmas.
866 if not Compilation_Mode
867 and then Unit.Last > First_Unit
868 and then Unit.Table (Unit.Last - 1).Kind = Config_Pragmas
870 Info.Start_Line := Unit.Table (Unit.Last - 1).Start_Line;
871 Info.Offset := Unit.Table (Unit.Last - 1).Offset;
873 -- Delete the configuration pragma entry
875 Unit.Table (Unit.Last - 1) := Info;
879 -- If in compilation mode, and previous entry is the initial
880 -- entry for the file and is for configuration pragmas, then
881 -- they are to be appended to every unit in the file.
884 and then Unit.Last = First_Unit + 1
885 and then Unit.Table (First_Unit).Kind = Config_Pragmas
889 (Unit.Table (Unit.Last - 1).Chop_File, First_Unit);
890 Unit.Table (Unit.Last - 1) := Info;
894 Unit.Table (Unit.Last).Bufferg := Bufferg;
896 -- If in compilation mode, and this is not the first item,
897 -- combine configuration pragmas with previous unit, which
898 -- will cause an error message to be generated when the unit
902 and then Unit.Last > First_Unit
903 and then Unit.Table (Unit.Last).Kind = Config_Pragmas
913 -- Find out if the loop was exited prematurely because of
914 -- an error or if the EOF marker was found.
916 if Source (Parse_Ptr) /= EOF then
918 (File.Table (Chop_File).Name.all & ": error parsing offset info");
922 -- Handle case of a chop file consisting only of config pragmas
924 if Unit.Last = First_Unit
925 and then Unit.Table (Unit.Last).Kind = Config_Pragmas
927 -- In compilation mode, we append such a file to gnat.adc
929 if Compilation_Mode then
930 Write_Config_File (Unit.Table (Unit.Last).Chop_File, First_Unit);
933 -- In default (non-compilation) mode, this is invalid
937 (File.Table (Chop_File).Name.all &
938 ": no units found (only pragmas)");
943 -- Handle case of a chop file ending with config pragmas. This can
944 -- happen only in default non-compilation mode, since in compilation
945 -- mode such configuration pragmas are part of the preceding unit.
946 -- We simply concatenate such pragmas to the previous file which
947 -- will cause a compilation error, which is appropriate.
949 if Unit.Last > First_Unit
950 and then Unit.Table (Unit.Last).Kind = Config_Pragmas
954 end Parse_Offset_Info;
960 procedure Parse_Token
961 (Source : not null access String;
962 Ptr : in out Positive;
963 Token_Ptr : out Positive)
965 In_Quotes : Boolean := False;
970 while Source (Ptr) = ' ' or Source (Ptr) = ',' loop
978 while (In_Quotes or else not (Source (Ptr) = ' ' or Source (Ptr) = ','))
979 and then Source (Ptr) >= ' '
981 if Source (Ptr) = '"' then
982 In_Quotes := not In_Quotes;
994 (FD : File_Descriptor;
995 Contents : out String_Access;
996 Success : out Boolean)
998 Length : constant File_Offset := File_Offset (File_Length (FD));
999 -- Include room for EOF char
1000 Buffer : constant String_Access := new String (1 .. Length + 1);
1002 This_Read : Integer;
1003 Read_Ptr : File_Offset := 1;
1008 This_Read := Read (FD,
1009 A => Buffer (Read_Ptr)'Address,
1010 N => Length + 1 - Read_Ptr);
1011 Read_Ptr := Read_Ptr + Integer'Max (This_Read, 0);
1012 exit when This_Read <= 0;
1015 Buffer (Read_Ptr) := EOF;
1016 Contents := new String (1 .. Read_Ptr);
1017 Contents.all := Buffer (1 .. Read_Ptr);
1019 -- Things aren't simple on VMS due to the plethora of file types and
1020 -- organizations. It seems clear that there shouldn't be more bytes
1021 -- read than are contained in the file though.
1023 if Hostparm.OpenVMS then
1024 Success := Read_Ptr <= Length + 1;
1026 Success := Read_Ptr = Length + 1;
1030 ----------------------------
1031 -- Report_Duplicate_Units --
1032 ----------------------------
1034 function Report_Duplicate_Units return Boolean is
1038 Duplicates : Boolean := False;
1042 while US < SUnit_Num (Unit.Last) loop
1043 U := Sorted_Units.Table (US);
1045 if Is_Duplicated (US) then
1048 -- Move to last two versions of duplicated file to make it clearer
1049 -- to understand which file is retained in case of overwriting.
1051 while US + 1 < SUnit_Num (Unit.Last) loop
1052 exit when not Is_Duplicated (US + 1);
1056 U := Sorted_Units.Table (US);
1058 if Overwrite_Files then
1059 Warning_Msg (Unit.Table (U).File_Name.all
1060 & " is duplicated (all but last will be skipped)");
1062 elsif Unit.Table (U).Chop_File =
1063 Unit.Table (Sorted_Units.Table (US + 1)).Chop_File
1065 Error_Msg (Unit.Table (U).File_Name.all
1066 & " is duplicated in "
1067 & File.Table (Unit.Table (U).Chop_File).Name.all);
1070 Error_Msg (Unit.Table (U).File_Name.all
1072 & File.Table (Unit.Table (U).Chop_File).Name.all
1073 & " is duplicated in "
1076 (Sorted_Units.Table (US + 1)).Chop_File).Name.all);
1083 if Duplicates and not Overwrite_Files then
1084 if Hostparm.OpenVMS then
1086 ("use /OVERWRITE to overwrite files and keep last version");
1088 Put_Line ("use -w to overwrite files and keep last version");
1093 end Report_Duplicate_Units;
1095 --------------------
1096 -- Scan_Arguments --
1097 --------------------
1099 function Scan_Arguments return Boolean is
1100 Kset : Boolean := False;
1101 -- Set true if -k switch found
1104 Initialize_Option_Scan;
1106 -- Scan options first
1109 case Getopt ("c gnat? h k? p q r v w x -GCC=!") is
1114 Gcc := new String'(Parameter);
1118 Compilation_Mode := True;
1122 new Argument_List'(Gnat_Args.all &
1123 new String'("-gnat" & Parameter));
1127 raise Types.Terminate_Program;
1131 Param : String_Access := new String'(Parameter);
1134 if Param.all /= "" then
1135 for J in Param'Range loop
1136 if Param (J) not in '0' .. '9' then
1137 if Hostparm.OpenVMS then
1138 Error_Msg ("/FILE_NAME_MAX_LENGTH=nnn" &
1139 " requires numeric parameter");
1141 Error_Msg ("-k# requires numeric parameter");
1149 if Hostparm.OpenVMS then
1150 Param := new String'("39");
1152 Param := new String'("8");
1157 new Argument_List'(Gnat_Args.all &
1158 new String'("-gnatk" & Param.all));
1163 Preserve_Mode := True;
1169 Source_References := True;
1172 Verbose_Mode := True;
1173 Display_Version ("GNATCHOP", "1998");
1176 Overwrite_Files := True;
1179 Exit_On_Error := True;
1186 if not Kset and then Maximum_File_Name_Length > 0 then
1188 -- If this system has restricted filename lengths, tell gnat1
1189 -- about them, removing the leading blank from the image string.
1192 new Argument_List'(Gnat_Args.all
1193 & new String'("-gnatk"
1194 & Maximum_File_Name_Length_String
1195 (Maximum_File_Name_Length_String'First + 1
1196 .. Maximum_File_Name_Length_String'Last)));
1203 S : constant String := Get_Argument (Do_Expansion => True);
1207 File.Increment_Last;
1208 File.Table (File.Last).Name := new String'(S);
1209 File.Table (File.Last).SR_Name := null;
1213 -- Case of more than one file where last file is a directory
1216 and then Is_Directory (File.Table (File.Last).Name.all)
1218 Directory := File.Table (File.Last).Name;
1219 File.Decrement_Last;
1221 -- Make sure Directory is terminated with a directory separator,
1222 -- so we can generate the output by just appending a filename.
1224 if Directory (Directory'Last) /= Directory_Separator
1225 and then Directory (Directory'Last) /= '/'
1227 Directory := new String'(Directory.all & Directory_Separator);
1230 -- At least one filename must be given
1232 elsif File.Last = 0 then
1236 -- No directory given, set directory to null, so that we can just
1237 -- concatenate the directory name to the file name unconditionally.
1240 Directory := new String'("");
1243 -- Finally check all filename arguments
1245 for File_Num in 1 .. File.Last loop
1247 F : constant String := File.Table (File_Num).Name.all;
1250 if Is_Directory (F) then
1251 Error_Msg (F & " is a directory, cannot be chopped");
1254 elsif not Is_Regular_File (F) then
1255 Error_Msg (F & " not found");
1264 when Invalid_Switch =>
1265 Error_Msg ("invalid switch " & Full_Switch);
1268 when Invalid_Parameter =>
1269 if Hostparm.OpenVMS then
1270 Error_Msg ("/FILE_NAME_MAX_LENGTH=nnn qualifier" &
1271 " requires numeric parameter");
1273 Error_Msg ("-k switch requires numeric parameter");
1283 procedure Sort_Units is
1285 procedure Move (From : Natural; To : Natural);
1286 -- Procedure used to sort the unit list
1287 -- Unit.Table (To) := Unit_List (From); used by sort
1289 function Lt (Left, Right : Natural) return Boolean;
1290 -- Compares Left and Right units based on file name (first),
1291 -- Chop_File (second) and Offset (third). This ordering is
1292 -- important to keep the last version in case of duplicate files.
1294 package Unit_Sort is new GNAT.Heap_Sort_G (Move, Lt);
1295 -- Used for sorting on filename to detect duplicates
1301 function Lt (Left, Right : Natural) return Boolean is
1302 L : Unit_Info renames
1303 Unit.Table (Sorted_Units.Table (SUnit_Num (Left)));
1305 R : Unit_Info renames
1306 Unit.Table (Sorted_Units.Table (SUnit_Num (Right)));
1309 return L.File_Name.all < R.File_Name.all
1310 or else (L.File_Name.all = R.File_Name.all
1311 and then (L.Chop_File < R.Chop_File
1312 or else (L.Chop_File = R.Chop_File
1313 and then L.Offset < R.Offset)));
1320 procedure Move (From : Natural; To : Natural) is
1322 Sorted_Units.Table (SUnit_Num (To)) :=
1323 Sorted_Units.Table (SUnit_Num (From));
1326 -- Start of processing for Sort_Units
1329 Sorted_Units.Set_Last (SUnit_Num (Unit.Last));
1331 for J in 1 .. Unit.Last loop
1332 Sorted_Units.Table (SUnit_Num (J)) := J;
1335 -- Sort Unit.Table, using Sorted_Units.Table (0) as scratch
1337 Unit_Sort.Sort (Natural (Unit.Last));
1339 -- Set the Sorted_Index fields in the unit tables
1341 for J in 1 .. SUnit_Num (Unit.Last) loop
1342 Unit.Table (Sorted_Units.Table (J)).Sorted_Index := J;
1353 ("Usage: gnatchop [-c] [-h] [-k#] " &
1354 "[-r] [-p] [-q] [-v] [-w] [-x] [--GCC=xx] file [file ...] [dir]");
1358 (" -c compilation mode, configuration pragmas " &
1362 (" -gnatxxx passes the -gnatxxx switch to gnat parser");
1365 (" -h help: output this usage information");
1368 (" -k# krunch file names of generated files to " &
1369 "no more than # characters");
1372 (" -k krunch file names of generated files to " &
1373 "no more than 8 characters");
1376 (" -p preserve time stamp, output files will " &
1377 "have same stamp as input");
1380 (" -q quiet mode, no output of generated file " &
1384 (" -r generate Source_Reference pragmas refer" &
1385 "encing original source file");
1388 (" -v verbose mode, output version and generat" &
1392 (" -w overwrite existing filenames");
1395 (" -x exit on error");
1398 (" --GCC=xx specify the path of the gnat parser to be used");
1402 (" file... list of source files to be chopped");
1405 (" dir directory location for split files (defa" &
1406 "ult = current directory)");
1413 procedure Warning_Msg (Message : String) is
1415 Warning_Count := Warning_Count + 1;
1416 Put_Line (Standard_Error, "warning: " & Message);
1419 -------------------------
1420 -- Write_Chopped_Files --
1421 -------------------------
1423 function Write_Chopped_Files (Input : File_Num) return Boolean is
1424 Name : aliased constant String :=
1425 File.Table (Input).Name.all & ASCII.NUL;
1426 FD : File_Descriptor;
1427 Buffer : String_Access;
1432 FD := Open_Read (Name'Address, Binary);
1433 TS_Time := File_Time_Stamp (FD);
1435 if FD = Invalid_FD then
1436 Error_Msg ("cannot open " & File.Table (Input).Name.all);
1440 Read_File (FD, Buffer, Success);
1443 Error_Msg ("cannot read " & File.Table (Input).Name.all);
1448 if not Quiet_Mode then
1449 Put_Line ("splitting " & File.Table (Input).Name.all & " into:");
1452 -- Only chop those units that come from this file
1454 for Num in 1 .. Unit.Last loop
1455 if Unit.Table (Num).Chop_File = Input then
1456 Write_Unit (Buffer, Num, TS_Time, Success);
1457 exit when not Success;
1463 end Write_Chopped_Files;
1465 -----------------------
1466 -- Write_Config_File --
1467 -----------------------
1469 procedure Write_Config_File (Input : File_Num; U : Unit_Num) is
1470 FD : File_Descriptor;
1471 Name : aliased constant String := "gnat.adc" & ASCII.NUL;
1472 Buffer : String_Access;
1475 Buffera : String_Access;
1479 Write_gnat_adc := True;
1480 FD := Open_Read_Write (Name'Address, Binary);
1482 if FD = Invalid_FD then
1483 FD := Create_File (Name'Address, Binary);
1486 if not Quiet_Mode then
1487 Put_Line ("writing configuration pragmas from " &
1488 File.Table (Input).Name.all & " to gnat.adc");
1494 if not Quiet_Mode then
1496 ("appending configuration pragmas from " &
1497 File.Table (Input).Name.all & " to gnat.adc");
1501 Success := FD /= Invalid_FD;
1504 Error_Msg ("cannot create gnat.adc");
1508 -- In append mode, acquire existing gnat.adc file
1511 Read_File (FD, Buffera, Success);
1514 Error_Msg ("cannot read gnat.adc");
1518 -- Find location of EOF byte if any to exclude from append
1521 while Bufferl <= Buffera'Last
1522 and then Buffera (Bufferl) /= EOF
1524 Bufferl := Bufferl + 1;
1527 Bufferl := Bufferl - 1;
1530 -- Write existing gnat.adc to new gnat.adc file
1532 FD := Create_File (Name'Address, Binary);
1533 Success := Write (FD, Buffera (1)'Address, Bufferl) = Bufferl;
1536 Error_Msg ("error writing gnat.adc");
1541 Buffer := Get_Config_Pragmas (Input, U);
1543 if Buffer /= null then
1544 Success := Write (FD, Buffer.all'Address, Buffer'Length) =
1548 Error_Msg ("disk full writing gnat.adc");
1554 end Write_Config_File;
1556 -----------------------------------
1557 -- Write_Source_Reference_Pragma --
1558 -----------------------------------
1560 procedure Write_Source_Reference_Pragma
1563 File : Stream_IO.File_Type;
1565 Success : in out Boolean)
1567 FTE : File_Entry renames Gnatchop.File.Table (Info.Chop_File);
1568 Nam : String_Access;
1571 if Success and Source_References and not Info.SR_Present then
1572 if FTE.SR_Name /= null then
1579 Reference : String :=
1580 "pragma Source_Reference (000000, """
1581 & Nam.all & """);" & EOL.Str;
1583 Pos : Positive := Reference'First;
1584 Lin : Line_Num := Line;
1587 while Reference (Pos + 1) /= ',' loop
1591 while Reference (Pos) = '0' loop
1592 Reference (Pos) := Character'Val
1593 (Character'Pos ('0') + Lin mod 10);
1598 -- Assume there are enough zeroes for any program length
1600 pragma Assert (Lin = 0);
1603 String'Write (Stream_IO.Stream (File), Reference);
1611 end Write_Source_Reference_Pragma;
1617 procedure Write_Unit
1618 (Source : not null access String;
1621 Success : out Boolean)
1624 procedure OS_Filename
1626 W_Name : Wide_String;
1628 N_Length : access Natural;
1630 E_Length : access Natural);
1631 pragma Import (C, OS_Filename, "__gnat_os_filename");
1632 -- Returns in OS_Name the proper name for the OS when used with the
1633 -- returned Encoding value. For example on Windows this will return the
1634 -- UTF-8 encoded name into OS_Name and set Encoding to encoding=utf8
1635 -- (the form parameter for Stream_IO).
1637 -- Name is the filename and W_Name the same filename in Unicode 16 bits
1638 -- (this corresponds to Win32 Unicode ISO/IEC 10646). N_Length/E_Length
1639 -- are the length returned in OS_Name/Encoding respectively.
1641 Info : Unit_Info renames Unit.Table (Num);
1642 Name : aliased constant String := Info.File_Name.all & ASCII.NUL;
1643 W_Name : aliased constant Wide_String := To_Wide_String (Name);
1644 EOL : constant EOL_String :=
1645 Get_EOL (Source, Source'First + Info.Offset);
1647 OS_Name : aliased String (1 .. Name'Length * 2);
1648 O_Length : aliased Natural := OS_Name'Length;
1649 Encoding : aliased String (1 .. 64);
1650 E_Length : aliased Natural := Encoding'Length;
1652 Length : File_Offset;
1655 -- Skip duplicated files
1657 if Is_Duplicated (Info.Sorted_Index) then
1658 Put_Line (" " & Info.File_Name.all & " skipped");
1659 Success := Overwrite_Files;
1667 OS_Name'Address, O_Length'Access,
1668 Encoding'Address, E_Length'Access);
1671 E_Name : constant String := OS_Name (1 .. O_Length);
1672 C_Name : aliased constant String := E_Name & ASCII.NUL;
1673 OS_Encoding : constant String := Encoding (1 .. E_Length);
1674 File : Stream_IO.File_Type;
1678 if not Overwrite_Files and then Exists (E_Name) then
1679 raise Stream_IO.Name_Error;
1682 (File, Stream_IO.Out_File, E_Name, OS_Encoding);
1687 when Stream_IO.Name_Error | Stream_IO.Use_Error =>
1688 Error_Msg ("cannot create " & Info.File_Name.all);
1692 -- A length of 0 indicates that the rest of the file belongs to
1693 -- this unit. The actual length must be calculated now. Take into
1694 -- account that the last character (EOF) must not be written.
1696 if Info.Length = 0 then
1697 Length := Source'Last - (Source'First + Info.Offset);
1699 Length := Info.Length;
1702 -- Prepend configuration pragmas if necessary
1704 if Success and then Info.Bufferg /= null then
1705 Write_Source_Reference_Pragma (Info, 1, File, EOL, Success);
1706 String'Write (Stream_IO.Stream (File), Info.Bufferg.all);
1709 Write_Source_Reference_Pragma
1710 (Info, Info.Start_Line, File, EOL, Success);
1715 (Stream_IO.Stream (File),
1716 Source (Source'First + Info.Offset ..
1717 Source'First + Info.Offset + Length - 1));
1719 when Stream_IO.Use_Error | Stream_IO.Device_Error =>
1720 Error_Msg ("disk full writing " & Info.File_Name.all);
1725 if not Quiet_Mode then
1726 Put_Line (" " & Info.File_Name.all);
1729 Stream_IO.Close (File);
1731 if Preserve_Mode then
1732 File_Time_Stamp (C_Name'Address, TS_Time);
1737 procedure Check_Version_And_Help is new Check_Version_And_Help_G (Usage);
1739 -- Start of processing for gnatchop
1742 -- Add the directory where gnatchop is invoked in front of the path, if
1743 -- gnatchop is invoked with directory information. Only do this if the
1744 -- platform is not VMS, where the notion of path does not really exist.
1746 if not Hostparm.OpenVMS then
1748 Command : constant String := Command_Name;
1751 for Index in reverse Command'Range loop
1752 if Command (Index) = Directory_Separator then
1754 Absolute_Dir : constant String :=
1756 (Command (Command'First .. Index));
1757 PATH : constant String :=
1760 & Getenv ("PATH").all;
1762 Setenv ("PATH", PATH);
1771 -- Process command line options and initialize global variables
1773 -- First, scan to detect --version and/or --help
1775 Check_Version_And_Help ("GNATCHOP", "1998");
1777 if not Scan_Arguments then
1778 Set_Exit_Status (Failure);
1782 -- Check presence of required executables
1784 Gnat_Cmd := Locate_Executable (Gcc.all, not Gcc_Set);
1786 if Gnat_Cmd = null then
1787 goto No_Files_Written;
1790 -- First parse all files and read offset information
1792 for Num in 1 .. File.Last loop
1793 if not Parse_File (Num) then
1794 goto No_Files_Written;
1798 -- Check if any units have been found (assumes non-empty Unit.Table)
1800 if Unit.Last = 0 then
1801 if not Write_gnat_adc then
1802 Error_Msg ("no compilation units found", Warning => True);
1805 goto No_Files_Written;
1810 -- Check if any duplicate files would be created. If so, emit a warning if
1811 -- Overwrite_Files is true, otherwise generate an error.
1813 if Report_Duplicate_Units and then not Overwrite_Files then
1814 goto No_Files_Written;
1817 -- Check if any files exist, if so do not write anything Because all files
1818 -- have been parsed and checked already, there won't be any duplicates
1820 if not Overwrite_Files and then Files_Exist then
1821 goto No_Files_Written;
1824 -- After this point, all source files are read in succession and chopped
1825 -- into their destination files.
1827 -- Source_File_Name pragmas are handled as logical file 0 so write it first
1829 for F in 1 .. File.Last loop
1830 if not Write_Chopped_Files (F) then
1831 Set_Exit_Status (Failure);
1836 if Warning_Count > 0 then
1838 Warnings_Msg : constant String := Warning_Count'Img & " warning(s)";
1840 Error_Msg (Warnings_Msg (2 .. Warnings_Msg'Last), Warning => True);
1846 <<No_Files_Written>>
1848 -- Special error exit for all situations where no files have
1851 if not Write_gnat_adc then
1852 Error_Msg ("no source files written", Warning => True);
1858 when Types.Terminate_Program =>