1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT RUN-TIME COMPONENTS                         --
4--                                                                          --
5--                          A D A . T E X T _ I O                           --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1992-2015, Free Software Foundation, Inc.         --
10--                                                                          --
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.                                     --
17--                                                                          --
18-- As a special exception under Section 7 of GPL version 3, you are granted --
19-- additional permissions described in the GCC Runtime Library Exception,   --
20-- version 3.1, as published by the Free Software Foundation.               --
21--                                                                          --
22-- You should have received a copy of the GNU General Public License and    --
23-- a copy of the GCC Runtime Library Exception along with this program;     --
24-- see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see    --
25-- <http://www.gnu.org/licenses/>.                                          --
26--                                                                          --
27-- GNAT was originally developed  by the GNAT team at  New York University. --
28-- Extensive contributions were provided by Ada Core Technologies Inc.      --
29--                                                                          --
30------------------------------------------------------------------------------
31
32with Ada.Streams;             use Ada.Streams;
33with Interfaces.C_Streams;    use Interfaces.C_Streams;
34
35with System.File_IO;
36with System.CRTL;
37with System.WCh_Cnv;          use System.WCh_Cnv;
38with System.WCh_Con;          use System.WCh_Con;
39
40with Ada.Unchecked_Conversion;
41with Ada.Unchecked_Deallocation;
42
43pragma Elaborate_All (System.File_IO);
44--  Needed because of calls to Chain_File in package body elaboration
45
46package body Ada.Text_IO is
47
48   package FIO renames System.File_IO;
49
50   subtype AP is FCB.AFCB_Ptr;
51
52   function To_FCB is new Ada.Unchecked_Conversion (File_Mode, FCB.File_Mode);
53   function To_TIO is new Ada.Unchecked_Conversion (FCB.File_Mode, File_Mode);
54   use type FCB.File_Mode;
55
56   use type System.CRTL.size_t;
57
58   WC_Encoding : Character;
59   pragma Import (C, WC_Encoding, "__gl_wc_encoding");
60   --  Default wide character encoding
61
62   Err_Name : aliased String := "*stderr" & ASCII.NUL;
63   In_Name  : aliased String := "*stdin" & ASCII.NUL;
64   Out_Name : aliased String := "*stdout" & ASCII.NUL;
65   --  Names of standard files
66   --
67   --  Use "preallocated" strings to avoid calling "new" during the elaboration
68   --  of the run time. This is needed in the tasking case to avoid calling
69   --  Task_Lock too early. A filename is expected to end with a null character
70   --  in the runtime, here the null characters are added just to have a
71   --  correct filename length.
72   --
73   --  Note: the names for these files are bogus, and probably it would be
74   --  better for these files to have no names, but the ACVC tests insist.
75   --  We use names that are bound to fail in open etc.
76
77   Null_Str : aliased constant String := "";
78   --  Used as form string for standard files
79
80   -----------------------
81   -- Local Subprograms --
82   -----------------------
83
84   function Get_Upper_Half_Char
85     (C    : Character;
86      File : File_Type) return Character;
87   --  This function is shared by Get and Get_Immediate to extract an encoded
88   --  upper half character value from the given File. The first byte has
89   --  already been read and is passed in C. The character value is returned as
90   --  the result, and the file pointer is bumped past the character.
91   --  Constraint_Error is raised if the encoded value is outside the bounds of
92   --  type Character.
93
94   function Get_Upper_Half_Char_Immed
95     (C    : Character;
96      File : File_Type) return Character;
97   --  This routine is identical to Get_Upper_Half_Char, except that the reads
98   --  are done in Get_Immediate mode (i.e. without waiting for a line return).
99
100   function Getc (File : File_Type) return int;
101   --  Gets next character from file, which has already been checked for being
102   --  in read status, and returns the character read if no error occurs. The
103   --  result is EOF if the end of file was read.
104
105   function Getc_Immed (File : File_Type) return int;
106   --  This routine is identical to Getc, except that the read is done in
107   --  Get_Immediate mode (i.e. without waiting for a line return).
108
109   function Has_Upper_Half_Character (Item : String) return Boolean;
110   --  Returns True if any of the characters is in the range 16#80#-16#FF#
111
112   function Nextc (File : File_Type) return int;
113   --  Returns next character from file without skipping past it (i.e. it is a
114   --  combination of Getc followed by an Ungetc).
115
116   procedure Put_Encoded (File : File_Type; Char : Character);
117   --  Called to output a character Char to the given File, when the encoding
118   --  method for the file is other than brackets, and Char is upper half.
119
120   procedure Putc (ch : int; File : File_Type);
121   --  Outputs the given character to the file, which has already been checked
122   --  for being in output status. Device_Error is raised if the character
123   --  cannot be written.
124
125   procedure Set_WCEM (File : in out File_Type);
126   --  Called by Open and Create to set the wide character encoding method for
127   --  the file, processing a WCEM form parameter if one is present. File is
128   --  IN OUT because it may be closed in case of an error.
129
130   procedure Terminate_Line (File : File_Type);
131   --  If the file is in Write_File or Append_File mode, and the current line
132   --  is not terminated, then a line terminator is written using New_Line.
133   --  Note that there is no Terminate_Page routine, because the page mark at
134   --  the end of the file is implied if necessary.
135
136   procedure Ungetc (ch : int; File : File_Type);
137   --  Pushes back character into stream, using ungetc. The caller has checked
138   --  that the file is in read status. Device_Error is raised if the character
139   --  cannot be pushed back. An attempt to push back and end of file character
140   --  (EOF) is ignored.
141
142   -------------------
143   -- AFCB_Allocate --
144   -------------------
145
146   function AFCB_Allocate (Control_Block : Text_AFCB) return FCB.AFCB_Ptr is
147      pragma Unreferenced (Control_Block);
148   begin
149      return new Text_AFCB;
150   end AFCB_Allocate;
151
152   ----------------
153   -- AFCB_Close --
154   ----------------
155
156   procedure AFCB_Close (File : not null access Text_AFCB) is
157   begin
158      --  If the file being closed is one of the current files, then close
159      --  the corresponding current file. It is not clear that this action
160      --  is required (RM A.10.3(23)) but it seems reasonable, and besides
161      --  ACVC test CE3208A expects this behavior.
162
163      if File_Type (File) = Current_In then
164         Current_In := null;
165      elsif File_Type (File) = Current_Out then
166         Current_Out := null;
167      elsif File_Type (File) = Current_Err then
168         Current_Err := null;
169      end if;
170
171      Terminate_Line (File_Type (File));
172   end AFCB_Close;
173
174   ---------------
175   -- AFCB_Free --
176   ---------------
177
178   procedure AFCB_Free (File : not null access Text_AFCB) is
179      type FCB_Ptr is access all Text_AFCB;
180      FT : FCB_Ptr := FCB_Ptr (File);
181
182      procedure Free is new Ada.Unchecked_Deallocation (Text_AFCB, FCB_Ptr);
183
184   begin
185      Free (FT);
186   end AFCB_Free;
187
188   -----------
189   -- Close --
190   -----------
191
192   procedure Close (File : in out File_Type) is
193   begin
194      FIO.Close (AP (File)'Unrestricted_Access);
195   end Close;
196
197   ---------
198   -- Col --
199   ---------
200
201   --  Note: we assume that it is impossible in practice for the column
202   --  to exceed the value of Count'Last, i.e. no check is required for
203   --  overflow raising layout error.
204
205   function Col (File : File_Type) return Positive_Count is
206   begin
207      FIO.Check_File_Open (AP (File));
208      return File.Col;
209   end Col;
210
211   function Col return Positive_Count is
212   begin
213      return Col (Current_Out);
214   end Col;
215
216   ------------
217   -- Create --
218   ------------
219
220   procedure Create
221     (File : in out File_Type;
222      Mode : File_Mode := Out_File;
223      Name : String := "";
224      Form : String := "")
225   is
226      Dummy_File_Control_Block : Text_AFCB;
227      pragma Warnings (Off, Dummy_File_Control_Block);
228      --  Yes, we know this is never assigned a value, only the tag
229      --  is used for dispatching purposes, so that's expected.
230
231   begin
232      FIO.Open (File_Ptr  => AP (File),
233                Dummy_FCB => Dummy_File_Control_Block,
234                Mode      => To_FCB (Mode),
235                Name      => Name,
236                Form      => Form,
237                Amethod   => 'T',
238                Creat     => True,
239                Text      => True);
240
241      File.Self := File;
242      Set_WCEM (File);
243   end Create;
244
245   -------------------
246   -- Current_Error --
247   -------------------
248
249   function Current_Error return File_Type is
250   begin
251      return Current_Err;
252   end Current_Error;
253
254   function Current_Error return File_Access is
255   begin
256      return Current_Err.Self'Access;
257   end Current_Error;
258
259   -------------------
260   -- Current_Input --
261   -------------------
262
263   function Current_Input return File_Type is
264   begin
265      return Current_In;
266   end Current_Input;
267
268   function Current_Input return File_Access is
269   begin
270      return Current_In.Self'Access;
271   end Current_Input;
272
273   --------------------
274   -- Current_Output --
275   --------------------
276
277   function Current_Output return File_Type is
278   begin
279      return Current_Out;
280   end Current_Output;
281
282   function Current_Output return File_Access is
283   begin
284      return Current_Out.Self'Access;
285   end Current_Output;
286
287   ------------
288   -- Delete --
289   ------------
290
291   procedure Delete (File : in out File_Type) is
292   begin
293      FIO.Delete (AP (File)'Unrestricted_Access);
294   end Delete;
295
296   -----------------
297   -- End_Of_File --
298   -----------------
299
300   function End_Of_File (File : File_Type) return Boolean is
301      ch : int;
302
303   begin
304      FIO.Check_Read_Status (AP (File));
305
306      if File.Before_Upper_Half_Character then
307         return False;
308
309      elsif File.Before_LM then
310         if File.Before_LM_PM then
311            return Nextc (File) = EOF;
312         end if;
313
314      else
315         ch := Getc (File);
316
317         if ch = EOF then
318            return True;
319
320         elsif ch /= LM then
321            Ungetc (ch, File);
322            return False;
323
324         else -- ch = LM
325            File.Before_LM := True;
326         end if;
327      end if;
328
329      --  Here we are just past the line mark with Before_LM set so that we
330      --  do not have to try to back up past the LM, thus avoiding the need
331      --  to back up more than one character.
332
333      ch := Getc (File);
334
335      if ch = EOF then
336         return True;
337
338      elsif ch = PM and then File.Is_Regular_File then
339         File.Before_LM_PM := True;
340         return Nextc (File) = EOF;
341
342      --  Here if neither EOF nor PM followed end of line
343
344      else
345         Ungetc (ch, File);
346         return False;
347      end if;
348
349   end End_Of_File;
350
351   function End_Of_File return Boolean is
352   begin
353      return End_Of_File (Current_In);
354   end End_Of_File;
355
356   -----------------
357   -- End_Of_Line --
358   -----------------
359
360   function End_Of_Line (File : File_Type) return Boolean is
361      ch : int;
362
363   begin
364      FIO.Check_Read_Status (AP (File));
365
366      if File.Before_Upper_Half_Character then
367         return False;
368
369      elsif File.Before_LM then
370         return True;
371
372      else
373         ch := Getc (File);
374
375         if ch = EOF then
376            return True;
377
378         else
379            Ungetc (ch, File);
380            return (ch = LM);
381         end if;
382      end if;
383   end End_Of_Line;
384
385   function End_Of_Line return Boolean is
386   begin
387      return End_Of_Line (Current_In);
388   end End_Of_Line;
389
390   -----------------
391   -- End_Of_Page --
392   -----------------
393
394   function End_Of_Page (File : File_Type) return Boolean is
395      ch  : int;
396
397   begin
398      FIO.Check_Read_Status (AP (File));
399
400      if not File.Is_Regular_File then
401         return False;
402
403      elsif File.Before_Upper_Half_Character then
404         return False;
405
406      elsif File.Before_LM then
407         if File.Before_LM_PM then
408            return True;
409         end if;
410
411      else
412         ch := Getc (File);
413
414         if ch = EOF then
415            return True;
416
417         elsif ch /= LM then
418            Ungetc (ch, File);
419            return False;
420
421         else -- ch = LM
422            File.Before_LM := True;
423         end if;
424      end if;
425
426      --  Here we are just past the line mark with Before_LM set so that we
427      --  do not have to try to back up past the LM, thus avoiding the need
428      --  to back up more than one character.
429
430      ch := Nextc (File);
431
432      return ch = PM or else ch = EOF;
433   end End_Of_Page;
434
435   function End_Of_Page return Boolean is
436   begin
437      return End_Of_Page (Current_In);
438   end End_Of_Page;
439
440   --------------
441   -- EOF_Char --
442   --------------
443
444   function EOF_Char return Integer is
445   begin
446      return EOF;
447   end EOF_Char;
448
449   -----------
450   -- Flush --
451   -----------
452
453   procedure Flush (File : File_Type) is
454   begin
455      FIO.Flush (AP (File));
456   end Flush;
457
458   procedure Flush is
459   begin
460      Flush (Current_Out);
461   end Flush;
462
463   ----------
464   -- Form --
465   ----------
466
467   function Form (File : File_Type) return String is
468   begin
469      return FIO.Form (AP (File));
470   end Form;
471
472   ---------
473   -- Get --
474   ---------
475
476   procedure Get
477     (File : File_Type;
478      Item : out Character)
479   is
480      ch : int;
481
482   begin
483      FIO.Check_Read_Status (AP (File));
484
485      if File.Before_Upper_Half_Character then
486         File.Before_Upper_Half_Character := False;
487         Item := File.Saved_Upper_Half_Character;
488
489      elsif File.Before_LM then
490         File.Before_LM := False;
491         File.Col := 1;
492
493         if File.Before_LM_PM then
494            File.Line := 1;
495            File.Page := File.Page + 1;
496            File.Before_LM_PM := False;
497         else
498            File.Line := File.Line + 1;
499         end if;
500      end if;
501
502      loop
503         ch := Getc (File);
504
505         if ch = EOF then
506            raise End_Error;
507
508         elsif ch = LM then
509            File.Line := File.Line + 1;
510            File.Col := 1;
511
512         elsif ch = PM and then File.Is_Regular_File then
513            File.Page := File.Page + 1;
514            File.Line := 1;
515
516         else
517            Item := Character'Val (ch);
518            File.Col := File.Col + 1;
519            return;
520         end if;
521      end loop;
522   end Get;
523
524   procedure Get (Item : out Character) is
525   begin
526      Get (Current_In, Item);
527   end Get;
528
529   procedure Get
530     (File : File_Type;
531      Item : out String)
532   is
533      ch : int;
534      J  : Natural;
535
536   begin
537      FIO.Check_Read_Status (AP (File));
538
539      if File.Before_LM then
540         File.Before_LM := False;
541         File.Before_LM_PM := False;
542         File.Col := 1;
543
544         if File.Before_LM_PM then
545            File.Line := 1;
546            File.Page := File.Page + 1;
547            File.Before_LM_PM := False;
548
549         else
550            File.Line := File.Line + 1;
551         end if;
552      end if;
553
554      J := Item'First;
555      while J <= Item'Last loop
556         ch := Getc (File);
557
558         if ch = EOF then
559            raise End_Error;
560
561         elsif ch = LM then
562            File.Line := File.Line + 1;
563            File.Col := 1;
564
565         elsif ch = PM and then File.Is_Regular_File then
566            File.Page := File.Page + 1;
567            File.Line := 1;
568
569         else
570            Item (J) := Character'Val (ch);
571            J := J + 1;
572            File.Col := File.Col + 1;
573         end if;
574      end loop;
575   end Get;
576
577   procedure Get (Item : out String) is
578   begin
579      Get (Current_In, Item);
580   end Get;
581
582   -------------------
583   -- Get_Immediate --
584   -------------------
585
586   procedure Get_Immediate
587     (File : File_Type;
588      Item : out Character)
589   is
590      ch          : int;
591
592   begin
593      FIO.Check_Read_Status (AP (File));
594
595      if File.Before_Upper_Half_Character then
596         File.Before_Upper_Half_Character := False;
597         Item := File.Saved_Upper_Half_Character;
598
599      elsif File.Before_LM then
600         File.Before_LM := False;
601         File.Before_LM_PM := False;
602         Item := Character'Val (LM);
603
604      else
605         ch := Getc_Immed (File);
606
607         if ch = EOF then
608            raise End_Error;
609         else
610            Item :=
611              (if not Is_Start_Of_Encoding (Character'Val (ch), File.WC_Method)
612               then Character'Val (ch)
613               else Get_Upper_Half_Char_Immed (Character'Val (ch), File));
614         end if;
615      end if;
616   end Get_Immediate;
617
618   procedure Get_Immediate
619     (Item : out Character)
620   is
621   begin
622      Get_Immediate (Current_In, Item);
623   end Get_Immediate;
624
625   procedure Get_Immediate
626     (File      : File_Type;
627      Item      : out Character;
628      Available : out Boolean)
629   is
630      ch          : int;
631      end_of_file : int;
632      avail       : int;
633
634      procedure getc_immediate_nowait
635        (stream      : FILEs;
636         ch          : out int;
637         end_of_file : out int;
638         avail       : out int);
639      pragma Import (C, getc_immediate_nowait, "getc_immediate_nowait");
640
641   begin
642      FIO.Check_Read_Status (AP (File));
643      Available := True;
644
645      if File.Before_Upper_Half_Character then
646         File.Before_Upper_Half_Character := False;
647         Item := File.Saved_Upper_Half_Character;
648
649      elsif File.Before_LM then
650         File.Before_LM := False;
651         File.Before_LM_PM := False;
652         Item := Character'Val (LM);
653
654      else
655         getc_immediate_nowait (File.Stream, ch, end_of_file, avail);
656
657         if ferror (File.Stream) /= 0 then
658            raise Device_Error;
659
660         elsif end_of_file /= 0 then
661            raise End_Error;
662
663         elsif avail = 0 then
664            Available := False;
665            Item := ASCII.NUL;
666
667         else
668            Available := True;
669
670            Item :=
671              (if not Is_Start_Of_Encoding (Character'Val (ch), File.WC_Method)
672               then Character'Val (ch)
673               else Get_Upper_Half_Char_Immed (Character'Val (ch), File));
674         end if;
675      end if;
676
677   end Get_Immediate;
678
679   procedure Get_Immediate
680     (Item      : out Character;
681      Available : out Boolean)
682   is
683   begin
684      Get_Immediate (Current_In, Item, Available);
685   end Get_Immediate;
686
687   --------------
688   -- Get_Line --
689   --------------
690
691   procedure Get_Line
692     (File : File_Type;
693      Item : out String;
694      Last : out Natural) is separate;
695   --  The implementation of Ada.Text_IO.Get_Line is split into a subunit so
696   --  that different implementations can be used on different systems.
697
698   procedure Get_Line
699     (Item : out String;
700      Last : out Natural)
701   is
702   begin
703      Get_Line (Current_In, Item, Last);
704   end Get_Line;
705
706   function Get_Line (File : File_Type) return String is
707      Buffer : String (1 .. 500);
708      Last   : Natural;
709
710      function Get_Rest (S : String) return String;
711      --  This is a recursive function that reads the rest of the line and
712      --  returns it. S is the part read so far.
713
714      --------------
715      -- Get_Rest --
716      --------------
717
718      function Get_Rest (S : String) return String is
719
720         --  Each time we allocate a buffer the same size as what we have
721         --  read so far. This limits us to a logarithmic number of calls
722         --  to Get_Rest and also ensures only a linear use of stack space.
723
724         Buffer : String (1 .. S'Length);
725         Last   : Natural;
726
727      begin
728         Get_Line (File, Buffer, Last);
729
730         declare
731            R : constant String := S & Buffer (1 .. Last);
732         begin
733            if Last < Buffer'Last then
734               return R;
735            else
736               return Get_Rest (R);
737            end if;
738         end;
739      end Get_Rest;
740
741   --  Start of processing for Get_Line
742
743   begin
744      Get_Line (File, Buffer, Last);
745
746      if Last < Buffer'Last then
747         return Buffer (1 .. Last);
748      else
749         return Get_Rest (Buffer (1 .. Last));
750      end if;
751   end Get_Line;
752
753   function Get_Line return String is
754   begin
755      return Get_Line (Current_In);
756   end Get_Line;
757
758   -------------------------
759   -- Get_Upper_Half_Char --
760   -------------------------
761
762   function Get_Upper_Half_Char
763     (C    : Character;
764      File : File_Type) return Character
765   is
766      Result : Wide_Character;
767
768      function In_Char return Character;
769      --  Function used to obtain additional characters it the wide character
770      --  sequence is more than one character long.
771
772      function WC_In is new Char_Sequence_To_Wide_Char (In_Char);
773
774      -------------
775      -- In_Char --
776      -------------
777
778      function In_Char return Character is
779         ch : constant Integer := Getc (File);
780      begin
781         if ch = EOF then
782            raise End_Error;
783         else
784            return Character'Val (ch);
785         end if;
786      end In_Char;
787
788   --  Start of processing for Get_Upper_Half_Char
789
790   begin
791      Result := WC_In (C, File.WC_Method);
792
793      if Wide_Character'Pos (Result) > 16#FF# then
794         raise Constraint_Error with
795           "invalid wide character in Text_'I'O input";
796      else
797         return Character'Val (Wide_Character'Pos (Result));
798      end if;
799   end Get_Upper_Half_Char;
800
801   -------------------------------
802   -- Get_Upper_Half_Char_Immed --
803   -------------------------------
804
805   function Get_Upper_Half_Char_Immed
806     (C    : Character;
807      File : File_Type) return Character
808   is
809      Result : Wide_Character;
810
811      function In_Char return Character;
812      --  Function used to obtain additional characters it the wide character
813      --  sequence is more than one character long.
814
815      function WC_In is new Char_Sequence_To_Wide_Char (In_Char);
816
817      -------------
818      -- In_Char --
819      -------------
820
821      function In_Char return Character is
822         ch : constant Integer := Getc_Immed (File);
823      begin
824         if ch = EOF then
825            raise End_Error;
826         else
827            return Character'Val (ch);
828         end if;
829      end In_Char;
830
831   --  Start of processing for Get_Upper_Half_Char_Immed
832
833   begin
834      Result := WC_In (C, File.WC_Method);
835
836      if Wide_Character'Pos (Result) > 16#FF# then
837         raise Constraint_Error with
838           "invalid wide character in Text_'I'O input";
839      else
840         return Character'Val (Wide_Character'Pos (Result));
841      end if;
842   end Get_Upper_Half_Char_Immed;
843
844   ----------
845   -- Getc --
846   ----------
847
848   function Getc (File : File_Type) return int is
849      ch : int;
850
851   begin
852      ch := fgetc (File.Stream);
853
854      if ch = EOF and then ferror (File.Stream) /= 0 then
855         raise Device_Error;
856      else
857         return ch;
858      end if;
859   end Getc;
860
861   ----------------
862   -- Getc_Immed --
863   ----------------
864
865   function Getc_Immed (File : File_Type) return int is
866      ch          : int;
867      end_of_file : int;
868
869      procedure getc_immediate
870        (stream : FILEs; ch : out int; end_of_file : out int);
871      pragma Import (C, getc_immediate, "getc_immediate");
872
873   begin
874      FIO.Check_Read_Status (AP (File));
875
876      if File.Before_LM then
877         File.Before_LM := False;
878         File.Before_LM_PM := False;
879         ch := LM;
880
881      else
882         getc_immediate (File.Stream, ch, end_of_file);
883
884         if ferror (File.Stream) /= 0 then
885            raise Device_Error;
886         elsif end_of_file /= 0 then
887            return EOF;
888         end if;
889      end if;
890
891      return ch;
892   end Getc_Immed;
893
894   ------------------------------
895   -- Has_Upper_Half_Character --
896   ------------------------------
897
898   function Has_Upper_Half_Character (Item : String) return Boolean is
899   begin
900      for J in Item'Range loop
901         if Character'Pos (Item (J)) >= 16#80# then
902            return True;
903         end if;
904      end loop;
905
906      return False;
907   end Has_Upper_Half_Character;
908
909   -------------------------------
910   -- Initialize_Standard_Files --
911   -------------------------------
912
913   procedure Initialize_Standard_Files is
914   begin
915      Standard_Err.Stream            := stderr;
916      Standard_Err.Name              := Err_Name'Access;
917      Standard_Err.Form              := Null_Str'Unrestricted_Access;
918      Standard_Err.Mode              := FCB.Out_File;
919      Standard_Err.Is_Regular_File   := is_regular_file (fileno (stderr)) /= 0;
920      Standard_Err.Is_Temporary_File := False;
921      Standard_Err.Is_System_File    := True;
922      Standard_Err.Text_Encoding     := Default_Text;
923      Standard_Err.Access_Method     := 'T';
924      Standard_Err.Self              := Standard_Err;
925      Standard_Err.WC_Method         := Default_WCEM;
926
927      Standard_In.Stream             := stdin;
928      Standard_In.Name               := In_Name'Access;
929      Standard_In.Form               := Null_Str'Unrestricted_Access;
930      Standard_In.Mode               := FCB.In_File;
931      Standard_In.Is_Regular_File    := is_regular_file (fileno (stdin)) /= 0;
932      Standard_In.Is_Temporary_File  := False;
933      Standard_In.Is_System_File     := True;
934      Standard_In.Text_Encoding      := Default_Text;
935      Standard_In.Access_Method      := 'T';
936      Standard_In.Self               := Standard_In;
937      Standard_In.WC_Method          := Default_WCEM;
938
939      Standard_Out.Stream            := stdout;
940      Standard_Out.Name              := Out_Name'Access;
941      Standard_Out.Form              := Null_Str'Unrestricted_Access;
942      Standard_Out.Mode              := FCB.Out_File;
943      Standard_Out.Is_Regular_File   := is_regular_file (fileno (stdout)) /= 0;
944      Standard_Out.Is_Temporary_File := False;
945      Standard_Out.Is_System_File    := True;
946      Standard_Out.Text_Encoding     := Default_Text;
947      Standard_Out.Access_Method     := 'T';
948      Standard_Out.Self              := Standard_Out;
949      Standard_Out.WC_Method         := Default_WCEM;
950
951      FIO.Make_Unbuffered (AP (Standard_Out));
952      FIO.Make_Unbuffered (AP (Standard_Err));
953   end Initialize_Standard_Files;
954
955   -------------
956   -- Is_Open --
957   -------------
958
959   function Is_Open (File : File_Type) return Boolean is
960   begin
961      return FIO.Is_Open (AP (File));
962   end Is_Open;
963
964   ----------
965   -- Line --
966   ----------
967
968   --  Note: we assume that it is impossible in practice for the line
969   --  to exceed the value of Count'Last, i.e. no check is required for
970   --  overflow raising layout error.
971
972   function Line (File : File_Type) return Positive_Count is
973   begin
974      FIO.Check_File_Open (AP (File));
975      return File.Line;
976   end Line;
977
978   function Line return Positive_Count is
979   begin
980      return Line (Current_Out);
981   end Line;
982
983   -----------------
984   -- Line_Length --
985   -----------------
986
987   function Line_Length (File : File_Type) return Count is
988   begin
989      FIO.Check_Write_Status (AP (File));
990      return File.Line_Length;
991   end Line_Length;
992
993   function Line_Length return Count is
994   begin
995      return Line_Length (Current_Out);
996   end Line_Length;
997
998   ----------------
999   -- Look_Ahead --
1000   ----------------
1001
1002   procedure Look_Ahead
1003     (File        : File_Type;
1004      Item        : out Character;
1005      End_Of_Line : out Boolean)
1006   is
1007      ch : int;
1008
1009   begin
1010      FIO.Check_Read_Status (AP (File));
1011
1012      --  If we are logically before a line mark, we can return immediately
1013
1014      if File.Before_LM then
1015         End_Of_Line := True;
1016         Item := ASCII.NUL;
1017
1018      --  If we are before an upper half character just return it (this can
1019      --  happen if there are two calls to Look_Ahead in a row).
1020
1021      elsif File.Before_Upper_Half_Character then
1022         End_Of_Line := False;
1023         Item := File.Saved_Upper_Half_Character;
1024
1025      --  Otherwise we must read a character from the input stream
1026
1027      else
1028         ch := Getc (File);
1029
1030         if ch = LM
1031           or else ch = EOF
1032           or else (ch = PM and then File.Is_Regular_File)
1033         then
1034            End_Of_Line := True;
1035            Ungetc (ch, File);
1036            Item := ASCII.NUL;
1037
1038         --  Case where character obtained does not represent the start of an
1039         --  encoded sequence so it stands for itself and we can unget it with
1040         --  no difficulty.
1041
1042         elsif not Is_Start_Of_Encoding
1043                     (Character'Val (ch), File.WC_Method)
1044         then
1045            End_Of_Line := False;
1046            Ungetc (ch, File);
1047            Item := Character'Val (ch);
1048
1049         --  For the start of an encoding, we read the character using the
1050         --  Get_Upper_Half_Char routine. It will occupy more than one byte
1051         --  so we can't put it back with ungetc. Instead we save it in the
1052         --  control block, setting a flag that everyone interested in reading
1053         --  characters must test before reading the stream.
1054
1055         else
1056            Item := Get_Upper_Half_Char (Character'Val (ch), File);
1057            End_Of_Line := False;
1058            File.Saved_Upper_Half_Character := Item;
1059            File.Before_Upper_Half_Character := True;
1060         end if;
1061      end if;
1062   end Look_Ahead;
1063
1064   procedure Look_Ahead
1065     (Item        : out Character;
1066      End_Of_Line : out Boolean)
1067   is
1068   begin
1069      Look_Ahead (Current_In, Item, End_Of_Line);
1070   end Look_Ahead;
1071
1072   ----------
1073   -- Mode --
1074   ----------
1075
1076   function Mode (File : File_Type) return File_Mode is
1077   begin
1078      return To_TIO (FIO.Mode (AP (File)));
1079   end Mode;
1080
1081   ----------
1082   -- Name --
1083   ----------
1084
1085   function Name (File : File_Type) return String is
1086   begin
1087      return FIO.Name (AP (File));
1088   end Name;
1089
1090   --------------
1091   -- New_Line --
1092   --------------
1093
1094   procedure New_Line
1095     (File    : File_Type;
1096      Spacing : Positive_Count := 1)
1097   is
1098   begin
1099      --  Raise Constraint_Error if out of range value. The reason for this
1100      --  explicit test is that we don't want junk values around, even if
1101      --  checks are off in the caller.
1102
1103      if not Spacing'Valid then
1104         raise Constraint_Error;
1105      end if;
1106
1107      FIO.Check_Write_Status (AP (File));
1108
1109      for K in 1 .. Spacing loop
1110         Putc (LM, File);
1111         File.Line := File.Line + 1;
1112
1113         if File.Page_Length /= 0
1114           and then File.Line > File.Page_Length
1115         then
1116            Putc (PM, File);
1117            File.Line := 1;
1118            File.Page := File.Page + 1;
1119         end if;
1120      end loop;
1121
1122      File.Col := 1;
1123   end New_Line;
1124
1125   procedure New_Line (Spacing : Positive_Count := 1) is
1126   begin
1127      New_Line (Current_Out, Spacing);
1128   end New_Line;
1129
1130   --------------
1131   -- New_Page --
1132   --------------
1133
1134   procedure New_Page (File : File_Type) is
1135   begin
1136      FIO.Check_Write_Status (AP (File));
1137
1138      if File.Col /= 1 or else File.Line = 1 then
1139         Putc (LM, File);
1140      end if;
1141
1142      Putc (PM, File);
1143      File.Page := File.Page + 1;
1144      File.Line := 1;
1145      File.Col := 1;
1146   end New_Page;
1147
1148   procedure New_Page is
1149   begin
1150      New_Page (Current_Out);
1151   end New_Page;
1152
1153   -----------
1154   -- Nextc --
1155   -----------
1156
1157   function Nextc (File : File_Type) return int is
1158      ch : int;
1159
1160   begin
1161      ch := fgetc (File.Stream);
1162
1163      if ch = EOF then
1164         if ferror (File.Stream) /= 0 then
1165            raise Device_Error;
1166         end if;
1167
1168      else
1169         if ungetc (ch, File.Stream) = EOF then
1170            raise Device_Error;
1171         end if;
1172      end if;
1173
1174      return ch;
1175   end Nextc;
1176
1177   ----------
1178   -- Open --
1179   ----------
1180
1181   procedure Open
1182     (File : in out File_Type;
1183      Mode : File_Mode;
1184      Name : String;
1185      Form : String := "")
1186   is
1187      Dummy_File_Control_Block : Text_AFCB;
1188      pragma Warnings (Off, Dummy_File_Control_Block);
1189      --  Yes, we know this is never assigned a value, only the tag
1190      --  is used for dispatching purposes, so that's expected.
1191
1192   begin
1193      FIO.Open (File_Ptr  => AP (File),
1194                Dummy_FCB => Dummy_File_Control_Block,
1195                Mode      => To_FCB (Mode),
1196                Name      => Name,
1197                Form      => Form,
1198                Amethod   => 'T',
1199                Creat     => False,
1200                Text      => True);
1201
1202      File.Self := File;
1203      Set_WCEM (File);
1204   end Open;
1205
1206   ----------
1207   -- Page --
1208   ----------
1209
1210   --  Note: we assume that it is impossible in practice for the page
1211   --  to exceed the value of Count'Last, i.e. no check is required for
1212   --  overflow raising layout error.
1213
1214   function Page (File : File_Type) return Positive_Count is
1215   begin
1216      FIO.Check_File_Open (AP (File));
1217      return File.Page;
1218   end Page;
1219
1220   function Page return Positive_Count is
1221   begin
1222      return Page (Current_Out);
1223   end Page;
1224
1225   -----------------
1226   -- Page_Length --
1227   -----------------
1228
1229   function Page_Length (File : File_Type) return Count is
1230   begin
1231      FIO.Check_Write_Status (AP (File));
1232      return File.Page_Length;
1233   end Page_Length;
1234
1235   function Page_Length return Count is
1236   begin
1237      return Page_Length (Current_Out);
1238   end Page_Length;
1239
1240   ---------
1241   -- Put --
1242   ---------
1243
1244   procedure Put
1245     (File : File_Type;
1246      Item : Character)
1247   is
1248   begin
1249      FIO.Check_Write_Status (AP (File));
1250
1251      if File.Line_Length /= 0 and then File.Col > File.Line_Length then
1252         New_Line (File);
1253      end if;
1254
1255      --  If lower half character, or brackets encoding, output directly
1256
1257      if Character'Pos (Item) < 16#80#
1258        or else File.WC_Method = WCEM_Brackets
1259      then
1260         if fputc (Character'Pos (Item), File.Stream) = EOF then
1261            raise Device_Error;
1262         end if;
1263
1264      --  Case of upper half character with non-brackets encoding
1265
1266      else
1267         Put_Encoded (File, Item);
1268      end if;
1269
1270      File.Col := File.Col + 1;
1271   end Put;
1272
1273   procedure Put (Item : Character) is
1274   begin
1275      Put (Current_Out, Item);
1276   end Put;
1277
1278   ---------
1279   -- Put --
1280   ---------
1281
1282   procedure Put
1283     (File : File_Type;
1284      Item : String)
1285   is
1286   begin
1287      FIO.Check_Write_Status (AP (File));
1288
1289      --  Only have something to do if string is non-null
1290
1291      if Item'Length > 0 then
1292
1293         --  If we have bounded lines, or if the file encoding is other than
1294         --  Brackets and the string has at least one upper half character,
1295         --  then output the string character by character.
1296
1297         if File.Line_Length /= 0
1298           or else (File.WC_Method /= WCEM_Brackets
1299                      and then Has_Upper_Half_Character (Item))
1300         then
1301            for J in Item'Range loop
1302               Put (File, Item (J));
1303            end loop;
1304
1305         --  Otherwise we can output the entire string at once. Note that if
1306         --  there are LF or FF characters in the string, we do not bother to
1307         --  count them as line or page terminators.
1308
1309         else
1310            FIO.Write_Buf (AP (File), Item'Address, Item'Length);
1311            File.Col := File.Col + Item'Length;
1312         end if;
1313      end if;
1314   end Put;
1315
1316   procedure Put (Item : String) is
1317   begin
1318      Put (Current_Out, Item);
1319   end Put;
1320
1321   -----------------
1322   -- Put_Encoded --
1323   -----------------
1324
1325   procedure Put_Encoded (File : File_Type; Char : Character) is
1326      procedure Out_Char (C : Character);
1327      --  Procedure to output one character of an upper half encoded sequence
1328
1329      procedure WC_Out is new Wide_Char_To_Char_Sequence (Out_Char);
1330
1331      --------------
1332      -- Out_Char --
1333      --------------
1334
1335      procedure Out_Char (C : Character) is
1336      begin
1337         Putc (Character'Pos (C), File);
1338      end Out_Char;
1339
1340   --  Start of processing for Put_Encoded
1341
1342   begin
1343      WC_Out (Wide_Character'Val (Character'Pos (Char)), File.WC_Method);
1344   end Put_Encoded;
1345
1346   --------------
1347   -- Put_Line --
1348   --------------
1349
1350   procedure Put_Line
1351     (File : File_Type;
1352      Item : String)
1353   is
1354      Ilen   : Natural := Item'Length;
1355      Istart : Natural := Item'First;
1356
1357   begin
1358      FIO.Check_Write_Status (AP (File));
1359
1360      --  If we have bounded lines, or if the file encoding is other than
1361      --  Brackets and the string has at least one upper half character, then
1362      --  output the string character by character.
1363
1364      if File.Line_Length /= 0
1365        or else (File.WC_Method /= WCEM_Brackets
1366                   and then Has_Upper_Half_Character (Item))
1367      then
1368         for J in Item'Range loop
1369            Put (File, Item (J));
1370         end loop;
1371
1372         New_Line (File);
1373         return;
1374      end if;
1375
1376      --  Normal case where we do not need to output character by character
1377
1378      --  We setup a single string that has the necessary terminators and
1379      --  then write it with a single call. The reason for doing this is
1380      --  that it gives better behavior for the use of Put_Line in multi-
1381      --  tasking programs, since often the OS will treat the entire put
1382      --  operation as an atomic operation.
1383
1384      --  We only do this if the message is 512 characters or less in length,
1385      --  since otherwise Put_Line would use an unbounded amount of stack
1386      --  space and could cause undetected stack overflow. If we have a
1387      --  longer string, then output the first part separately to avoid this.
1388
1389      if Ilen > 512 then
1390         FIO.Write_Buf (AP (File), Item'Address, size_t (Ilen - 512));
1391         Istart := Istart + Ilen - 512;
1392         Ilen   := 512;
1393      end if;
1394
1395      --  Now prepare the string with its terminator
1396
1397      declare
1398         Buffer : String (1 .. Ilen + 2);
1399         Plen   : size_t;
1400
1401      begin
1402         Buffer (1 .. Ilen) := Item (Istart .. Item'Last);
1403         Buffer (Ilen + 1) := Character'Val (LM);
1404
1405         if File.Page_Length /= 0
1406           and then File.Line > File.Page_Length
1407         then
1408            Buffer (Ilen + 2) := Character'Val (PM);
1409            Plen := size_t (Ilen) + 2;
1410            File.Line := 1;
1411            File.Page := File.Page + 1;
1412
1413         else
1414            Plen := size_t (Ilen) + 1;
1415            File.Line := File.Line + 1;
1416         end if;
1417
1418         FIO.Write_Buf (AP (File), Buffer'Address, Plen);
1419
1420         File.Col := 1;
1421      end;
1422   end Put_Line;
1423
1424   procedure Put_Line (Item : String) is
1425   begin
1426      Put_Line (Current_Out, Item);
1427   end Put_Line;
1428
1429   ----------
1430   -- Putc --
1431   ----------
1432
1433   procedure Putc (ch : int; File : File_Type) is
1434   begin
1435      if fputc (ch, File.Stream) = EOF then
1436         raise Device_Error;
1437      end if;
1438   end Putc;
1439
1440   ----------
1441   -- Read --
1442   ----------
1443
1444   --  This is the primitive Stream Read routine, used when a Text_IO file
1445   --  is treated directly as a stream using Text_IO.Streams.Stream.
1446
1447   procedure Read
1448     (File : in out Text_AFCB;
1449      Item : out Stream_Element_Array;
1450      Last : out Stream_Element_Offset)
1451   is
1452      Discard_ch : int;
1453      pragma Warnings (Off, Discard_ch);
1454
1455   begin
1456      --  Need to deal with Before_Upper_Half_Character ???
1457
1458      if File.Mode /= FCB.In_File then
1459         raise Mode_Error;
1460      end if;
1461
1462      --  Deal with case where our logical and physical position do not match
1463      --  because of being after an LM or LM-PM sequence when in fact we are
1464      --  logically positioned before it.
1465
1466      if File.Before_LM then
1467
1468         --  If we are before a PM, then it is possible for a stream read
1469         --  to leave us after the LM and before the PM, which is a bit
1470         --  odd. The easiest way to deal with this is to unget the PM,
1471         --  so we are indeed positioned between the characters. This way
1472         --  further stream read operations will work correctly, and the
1473         --  effect on text processing is a little weird, but what can
1474         --  be expected if stream and text input are mixed this way?
1475
1476         if File.Before_LM_PM then
1477            Discard_ch := ungetc (PM, File.Stream);
1478            File.Before_LM_PM := False;
1479         end if;
1480
1481         File.Before_LM := False;
1482
1483         Item (Item'First) := Stream_Element (Character'Pos (ASCII.LF));
1484
1485         if Item'Length = 1 then
1486            Last := Item'Last;
1487
1488         else
1489            Last :=
1490              Item'First +
1491                Stream_Element_Offset
1492                  (fread (buffer => Item'Address,
1493                          index  => size_t (Item'First + 1),
1494                          size   => 1,
1495                          count  => Item'Length - 1,
1496                          stream => File.Stream));
1497         end if;
1498
1499         return;
1500      end if;
1501
1502      --  Now we do the read. Since this is a text file, it is normally in
1503      --  text mode, but stream data must be read in binary mode, so we
1504      --  temporarily set binary mode for the read, resetting it after.
1505      --  These calls have no effect in a system (like Unix) where there is
1506      --  no distinction between text and binary files.
1507
1508      set_binary_mode (fileno (File.Stream));
1509
1510      Last :=
1511        Item'First +
1512          Stream_Element_Offset
1513            (fread (Item'Address, 1, Item'Length, File.Stream)) - 1;
1514
1515      if Last < Item'Last then
1516         if ferror (File.Stream) /= 0 then
1517            raise Device_Error;
1518         end if;
1519      end if;
1520
1521      set_text_mode (fileno (File.Stream));
1522   end Read;
1523
1524   -----------
1525   -- Reset --
1526   -----------
1527
1528   procedure Reset
1529     (File : in out File_Type;
1530      Mode : File_Mode)
1531   is
1532   begin
1533      --  Don't allow change of mode for current file (RM A.10.2(5))
1534
1535      if (File = Current_In  or else
1536          File = Current_Out or else
1537          File = Current_Error)
1538        and then To_FCB (Mode) /= File.Mode
1539      then
1540         raise Mode_Error;
1541      end if;
1542
1543      Terminate_Line (File);
1544      FIO.Reset (AP (File)'Unrestricted_Access, To_FCB (Mode));
1545      File.Page := 1;
1546      File.Line := 1;
1547      File.Col  := 1;
1548      File.Line_Length := 0;
1549      File.Page_Length := 0;
1550      File.Before_LM := False;
1551      File.Before_LM_PM := False;
1552   end Reset;
1553
1554   procedure Reset (File : in out File_Type) is
1555   begin
1556      Terminate_Line (File);
1557      FIO.Reset (AP (File)'Unrestricted_Access);
1558      File.Page := 1;
1559      File.Line := 1;
1560      File.Col  := 1;
1561      File.Line_Length := 0;
1562      File.Page_Length := 0;
1563      File.Before_LM := False;
1564      File.Before_LM_PM := False;
1565   end Reset;
1566
1567   -------------
1568   -- Set_Col --
1569   -------------
1570
1571   procedure Set_Col
1572     (File : File_Type;
1573      To   : Positive_Count)
1574   is
1575      ch : int;
1576
1577   begin
1578      --  Raise Constraint_Error if out of range value. The reason for this
1579      --  explicit test is that we don't want junk values around, even if
1580      --  checks are off in the caller.
1581
1582      if not To'Valid then
1583         raise Constraint_Error;
1584      end if;
1585
1586      FIO.Check_File_Open (AP (File));
1587
1588      --  Output case
1589
1590      if Mode (File) >= Out_File then
1591
1592         --  Error if we attempt to set Col to a value greater than the
1593         --  maximum permissible line length.
1594
1595         if File.Line_Length /= 0 and then To > File.Line_Length then
1596            raise Layout_Error;
1597         end if;
1598
1599         --  If we are behind current position, then go to start of new line
1600
1601         if To < File.Col then
1602            New_Line (File);
1603         end if;
1604
1605         --  Loop to output blanks till we are at the required column
1606
1607         while File.Col < To loop
1608            Put (File, ' ');
1609         end loop;
1610
1611      --  Input case
1612
1613      else
1614         --  If we are logically before a LM, but physically after it, the
1615         --  file position still reflects the position before the LM, so eat
1616         --  it now and adjust the file position appropriately.
1617
1618         if File.Before_LM then
1619            File.Before_LM := False;
1620            File.Before_LM_PM := False;
1621            File.Line := File.Line + 1;
1622            File.Col := 1;
1623         end if;
1624
1625         --  Loop reading characters till we get one at the required Col value
1626
1627         loop
1628            --  Read next character. The reason we have to read ahead is to
1629            --  skip formatting characters, the effect of Set_Col is to set
1630            --  us to a real character with the right Col value, and format
1631            --  characters don't count.
1632
1633            ch := Getc (File);
1634
1635            --  Error if we hit an end of file
1636
1637            if ch = EOF then
1638               raise End_Error;
1639
1640            --  If line mark, eat it and adjust file position
1641
1642            elsif ch = LM then
1643               File.Line := File.Line + 1;
1644               File.Col := 1;
1645
1646            --  If recognized page mark, eat it, and adjust file position
1647
1648            elsif ch = PM and then File.Is_Regular_File then
1649               File.Page := File.Page + 1;
1650               File.Line := 1;
1651               File.Col := 1;
1652
1653            --  Otherwise this is the character we are looking for, so put it
1654            --  back in the input stream (we have not adjusted the file
1655            --  position yet, so everything is set right after this ungetc).
1656
1657            elsif To = File.Col then
1658               Ungetc (ch, File);
1659               return;
1660
1661            --  Keep skipping characters if we are not there yet, updating the
1662            --  file position past the skipped character.
1663
1664            else
1665               File.Col := File.Col + 1;
1666            end if;
1667         end loop;
1668      end if;
1669   end Set_Col;
1670
1671   procedure Set_Col (To : Positive_Count) is
1672   begin
1673      Set_Col (Current_Out, To);
1674   end Set_Col;
1675
1676   ---------------
1677   -- Set_Error --
1678   ---------------
1679
1680   procedure Set_Error (File : File_Type) is
1681   begin
1682      FIO.Check_Write_Status (AP (File));
1683      Current_Err := File;
1684   end Set_Error;
1685
1686   ---------------
1687   -- Set_Input --
1688   ---------------
1689
1690   procedure Set_Input (File : File_Type) is
1691   begin
1692      FIO.Check_Read_Status (AP (File));
1693      Current_In := File;
1694   end Set_Input;
1695
1696   --------------
1697   -- Set_Line --
1698   --------------
1699
1700   procedure Set_Line
1701     (File : File_Type;
1702      To   : Positive_Count)
1703   is
1704   begin
1705      --  Raise Constraint_Error if out of range value. The reason for this
1706      --  explicit test is that we don't want junk values around, even if
1707      --  checks are off in the caller.
1708
1709      if not To'Valid then
1710         raise Constraint_Error;
1711      end if;
1712
1713      FIO.Check_File_Open (AP (File));
1714
1715      if To = File.Line then
1716         return;
1717      end if;
1718
1719      if Mode (File) >= Out_File then
1720         if File.Page_Length /= 0 and then To > File.Page_Length then
1721            raise Layout_Error;
1722         end if;
1723
1724         if To < File.Line then
1725            New_Page (File);
1726         end if;
1727
1728         while File.Line < To loop
1729            New_Line (File);
1730         end loop;
1731
1732      else
1733         while To /= File.Line loop
1734            Skip_Line (File);
1735         end loop;
1736      end if;
1737   end Set_Line;
1738
1739   procedure Set_Line (To : Positive_Count) is
1740   begin
1741      Set_Line (Current_Out, To);
1742   end Set_Line;
1743
1744   ---------------------
1745   -- Set_Line_Length --
1746   ---------------------
1747
1748   procedure Set_Line_Length (File : File_Type; To : Count) is
1749   begin
1750      --  Raise Constraint_Error if out of range value. The reason for this
1751      --  explicit test is that we don't want junk values around, even if
1752      --  checks are off in the caller.
1753
1754      if not To'Valid then
1755         raise Constraint_Error;
1756      end if;
1757
1758      FIO.Check_Write_Status (AP (File));
1759      File.Line_Length := To;
1760   end Set_Line_Length;
1761
1762   procedure Set_Line_Length (To : Count) is
1763   begin
1764      Set_Line_Length (Current_Out, To);
1765   end Set_Line_Length;
1766
1767   ----------------
1768   -- Set_Output --
1769   ----------------
1770
1771   procedure Set_Output (File : File_Type) is
1772   begin
1773      FIO.Check_Write_Status (AP (File));
1774      Current_Out := File;
1775   end Set_Output;
1776
1777   ---------------------
1778   -- Set_Page_Length --
1779   ---------------------
1780
1781   procedure Set_Page_Length (File : File_Type; To : Count) is
1782   begin
1783      --  Raise Constraint_Error if out of range value. The reason for this
1784      --  explicit test is that we don't want junk values around, even if
1785      --  checks are off in the caller.
1786
1787      if not To'Valid then
1788         raise Constraint_Error;
1789      end if;
1790
1791      FIO.Check_Write_Status (AP (File));
1792      File.Page_Length := To;
1793   end Set_Page_Length;
1794
1795   procedure Set_Page_Length (To : Count) is
1796   begin
1797      Set_Page_Length (Current_Out, To);
1798   end Set_Page_Length;
1799
1800   --------------
1801   -- Set_WCEM --
1802   --------------
1803
1804   procedure Set_WCEM (File : in out File_Type) is
1805      Start : Natural;
1806      Stop  : Natural;
1807
1808   begin
1809      File.WC_Method := WCEM_Brackets;
1810      FIO.Form_Parameter (File.Form.all, "wcem", Start, Stop);
1811
1812      if Start = 0 then
1813         File.WC_Method := WCEM_Brackets;
1814
1815      else
1816         if Stop = Start then
1817            for J in WC_Encoding_Letters'Range loop
1818               if File.Form (Start) = WC_Encoding_Letters (J) then
1819                  File.WC_Method := J;
1820                  return;
1821               end if;
1822            end loop;
1823         end if;
1824
1825         Close (File);
1826         raise Use_Error with "invalid WCEM form parameter";
1827      end if;
1828   end Set_WCEM;
1829
1830   ---------------
1831   -- Skip_Line --
1832   ---------------
1833
1834   procedure Skip_Line
1835     (File    : File_Type;
1836      Spacing : Positive_Count := 1)
1837   is
1838      ch : int;
1839
1840   begin
1841      --  Raise Constraint_Error if out of range value. The reason for this
1842      --  explicit test is that we don't want junk values around, even if
1843      --  checks are off in the caller.
1844
1845      if not Spacing'Valid then
1846         raise Constraint_Error;
1847      end if;
1848
1849      FIO.Check_Read_Status (AP (File));
1850
1851      for L in 1 .. Spacing loop
1852         if File.Before_LM then
1853            File.Before_LM := False;
1854
1855            --  Note that if File.Before_LM_PM is currently set, we also have
1856            --  to reset it (because it makes sense for Before_LM_PM to be set
1857            --  only when Before_LM is also set). This is done later on in this
1858            --  subprogram, as soon as Before_LM_PM has been taken into account
1859            --  for the purpose of page and line counts.
1860
1861         else
1862            ch := Getc (File);
1863
1864            --  If at end of file now, then immediately raise End_Error. Note
1865            --  that we can never be positioned between a line mark and a page
1866            --  mark, so if we are at the end of file, we cannot logically be
1867            --  before the implicit page mark that is at the end of the file.
1868
1869            --  For the same reason, we do not need an explicit check for a
1870            --  page mark. If there is a FF in the middle of a line, the file
1871            --  is not in canonical format and we do not care about the page
1872            --  numbers for files other than ones in canonical format.
1873
1874            if ch = EOF then
1875               raise End_Error;
1876            end if;
1877
1878            --  If not at end of file, then loop till we get to an LM or EOF.
1879            --  The latter case happens only in non-canonical files where the
1880            --  last line is not terminated by LM, but we don't want to blow
1881            --  up for such files, so we assume an implicit LM in this case.
1882
1883            loop
1884               exit when ch = LM or else ch = EOF;
1885               ch := Getc (File);
1886            end loop;
1887         end if;
1888
1889         --  We have got past a line mark, now, for a regular file only,
1890         --  see if a page mark immediately follows this line mark and
1891         --  if so, skip past the page mark as well. We do not do this
1892         --  for non-regular files, since it would cause an undesirable
1893         --  wait for an additional character.
1894
1895         File.Col := 1;
1896         File.Line := File.Line + 1;
1897
1898         if File.Before_LM_PM then
1899            File.Page := File.Page + 1;
1900            File.Line := 1;
1901            File.Before_LM_PM := False;
1902
1903         elsif File.Is_Regular_File then
1904            ch := Getc (File);
1905
1906            --  Page mark can be explicit, or implied at the end of the file
1907
1908            if (ch = PM or else ch = EOF)
1909              and then File.Is_Regular_File
1910            then
1911               File.Page := File.Page + 1;
1912               File.Line := 1;
1913            else
1914               Ungetc (ch, File);
1915            end if;
1916         end if;
1917      end loop;
1918
1919      File.Before_Upper_Half_Character := False;
1920   end Skip_Line;
1921
1922   procedure Skip_Line (Spacing : Positive_Count := 1) is
1923   begin
1924      Skip_Line (Current_In, Spacing);
1925   end Skip_Line;
1926
1927   ---------------
1928   -- Skip_Page --
1929   ---------------
1930
1931   procedure Skip_Page (File : File_Type) is
1932      ch : int;
1933
1934   begin
1935      FIO.Check_Read_Status (AP (File));
1936
1937      --  If at page mark already, just skip it
1938
1939      if File.Before_LM_PM then
1940         File.Before_LM := False;
1941         File.Before_LM_PM := False;
1942         File.Page := File.Page + 1;
1943         File.Line := 1;
1944         File.Col  := 1;
1945         return;
1946      end if;
1947
1948      --  This is a bit tricky, if we are logically before an LM then
1949      --  it is not an error if we are at an end of file now, since we
1950      --  are not really at it.
1951
1952      if File.Before_LM then
1953         File.Before_LM := False;
1954         File.Before_LM_PM := False;
1955         ch := Getc (File);
1956
1957      --  Otherwise we do raise End_Error if we are at the end of file now
1958
1959      else
1960         ch := Getc (File);
1961
1962         if ch = EOF then
1963            raise End_Error;
1964         end if;
1965      end if;
1966
1967      --  Now we can just rumble along to the next page mark, or to the
1968      --  end of file, if that comes first. The latter case happens when
1969      --  the page mark is implied at the end of file.
1970
1971      loop
1972         exit when ch = EOF
1973           or else (ch = PM and then File.Is_Regular_File);
1974         ch := Getc (File);
1975      end loop;
1976
1977      File.Page := File.Page + 1;
1978      File.Line := 1;
1979      File.Col  := 1;
1980      File.Before_Upper_Half_Character := False;
1981   end Skip_Page;
1982
1983   procedure Skip_Page is
1984   begin
1985      Skip_Page (Current_In);
1986   end Skip_Page;
1987
1988   --------------------
1989   -- Standard_Error --
1990   --------------------
1991
1992   function Standard_Error return File_Type is
1993   begin
1994      return Standard_Err;
1995   end Standard_Error;
1996
1997   function Standard_Error return File_Access is
1998   begin
1999      return Standard_Err'Access;
2000   end Standard_Error;
2001
2002   --------------------
2003   -- Standard_Input --
2004   --------------------
2005
2006   function Standard_Input return File_Type is
2007   begin
2008      return Standard_In;
2009   end Standard_Input;
2010
2011   function Standard_Input return File_Access is
2012   begin
2013      return Standard_In'Access;
2014   end Standard_Input;
2015
2016   ---------------------
2017   -- Standard_Output --
2018   ---------------------
2019
2020   function Standard_Output return File_Type is
2021   begin
2022      return Standard_Out;
2023   end Standard_Output;
2024
2025   function Standard_Output return File_Access is
2026   begin
2027      return Standard_Out'Access;
2028   end Standard_Output;
2029
2030   --------------------
2031   -- Terminate_Line --
2032   --------------------
2033
2034   procedure Terminate_Line (File : File_Type) is
2035   begin
2036      FIO.Check_File_Open (AP (File));
2037
2038      --  For file other than In_File, test for needing to terminate last line
2039
2040      if Mode (File) /= In_File then
2041
2042         --  If not at start of line definition need new line
2043
2044         if File.Col /= 1 then
2045            New_Line (File);
2046
2047         --  For files other than standard error and standard output, we
2048         --  make sure that an empty file has a single line feed, so that
2049         --  it is properly formatted. We avoid this for the standard files
2050         --  because it is too much of a nuisance to have these odd line
2051         --  feeds when nothing has been written to the file.
2052
2053         --  We also avoid this for files opened in append mode, in
2054         --  accordance with (RM A.8.2(10))
2055
2056         elsif (File /= Standard_Err and then File /= Standard_Out)
2057           and then (File.Line = 1 and then File.Page = 1)
2058           and then Mode (File) = Out_File
2059         then
2060            New_Line (File);
2061         end if;
2062      end if;
2063   end Terminate_Line;
2064
2065   ------------
2066   -- Ungetc --
2067   ------------
2068
2069   procedure Ungetc (ch : int; File : File_Type) is
2070   begin
2071      if ch /= EOF then
2072         if ungetc (ch, File.Stream) = EOF then
2073            raise Device_Error;
2074         end if;
2075      end if;
2076   end Ungetc;
2077
2078   -----------
2079   -- Write --
2080   -----------
2081
2082   --  This is the primitive Stream Write routine, used when a Text_IO file
2083   --  is treated directly as a stream using Text_IO.Streams.Stream.
2084
2085   procedure Write
2086     (File : in out Text_AFCB;
2087      Item : Stream_Element_Array)
2088   is
2089      pragma Warnings (Off, File);
2090      --  Because in this implementation we don't need IN OUT, we only read
2091
2092      function Has_Translated_Characters return Boolean;
2093      --  return True if Item array contains a character which will be
2094      --  translated under the text file mode. There is only one such
2095      --  character under DOS based systems which is character 10.
2096
2097      text_translation_required : Boolean;
2098      for text_translation_required'Size use Character'Size;
2099      pragma Import (C, text_translation_required,
2100                     "__gnat_text_translation_required");
2101
2102      Siz : constant size_t := Item'Length;
2103
2104      -------------------------------
2105      -- Has_Translated_Characters --
2106      -------------------------------
2107
2108      function Has_Translated_Characters return Boolean is
2109      begin
2110         for K in Item'Range loop
2111            if Item (K) = 10 then
2112               return True;
2113            end if;
2114         end loop;
2115         return False;
2116      end Has_Translated_Characters;
2117
2118      Needs_Binary_Write : constant Boolean :=
2119        text_translation_required and then Has_Translated_Characters;
2120
2121   --  Start of processing for Write
2122
2123   begin
2124      if File.Mode = FCB.In_File then
2125         raise Mode_Error;
2126      end if;
2127
2128      --  Now we do the write. Since this is a text file, it is normally in
2129      --  text mode, but stream data must be written in binary mode, so we
2130      --  temporarily set binary mode for the write, resetting it after. This
2131      --  is done only if needed (i.e. there is some characters in Item which
2132      --  needs to be written using the binary mode).
2133      --  These calls have no effect in a system (like Unix) where there is
2134      --  no distinction between text and binary files.
2135
2136      --  Since the character translation is done at the time the buffer is
2137      --  written (this is true under Windows) we first flush current buffer
2138      --  with text mode if needed.
2139
2140      if Needs_Binary_Write then
2141         if fflush (File.Stream) = -1 then
2142            raise Device_Error;
2143         end if;
2144
2145         set_binary_mode (fileno (File.Stream));
2146      end if;
2147
2148      if fwrite (Item'Address, 1, Siz, File.Stream) /= Siz then
2149         raise Device_Error;
2150      end if;
2151
2152      --  At this point we need to flush the buffer using the binary mode then
2153      --  we reset to text mode.
2154
2155      if Needs_Binary_Write then
2156         if fflush (File.Stream) = -1 then
2157            raise Device_Error;
2158         end if;
2159
2160         set_text_mode (fileno (File.Stream));
2161      end if;
2162   end Write;
2163
2164begin
2165   --  Initialize Standard Files
2166
2167   for J in WC_Encoding_Method loop
2168      if WC_Encoding = WC_Encoding_Letters (J) then
2169         Default_WCEM := J;
2170      end if;
2171   end loop;
2172
2173   Initialize_Standard_Files;
2174
2175   FIO.Chain_File (AP (Standard_In));
2176   FIO.Chain_File (AP (Standard_Out));
2177   FIO.Chain_File (AP (Standard_Err));
2178
2179end Ada.Text_IO;
2180