aboutsummaryrefslogtreecommitdiff
path: root/libjava/classpath/java/text/DateFormat.java
blob: 73aa62d9805301678df41627108ab512843d2413 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/* DateFormat.java -- Class for formatting/parsing date/times
   Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005
   Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
 
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.text;

import java.io.InvalidObjectException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.TimeZone;

/**
 * @author Per Bothner (bothner@cygnus.com)
 * @date October 25, 1998.
 */
/* Written using "Java Class Libraries", 2nd edition, plus online
 * API docs for JDK 1.2 beta from http://www.javasoft.com.
 * Status:  Mostly complete; search for FIXME to see omissions.
 */

public abstract class DateFormat extends Format implements Cloneable
{
  private static final long serialVersionUID = 7218322306649953788L;

  // Names fixed by serialization spec.
  protected Calendar calendar;
  protected NumberFormat numberFormat;

  // (Values determined using a test program.)
  public static final int FULL = 0;
  public static final int LONG = 1;
  public static final int MEDIUM = 2;
  public static final int SHORT = 3;
  public static final int DEFAULT = MEDIUM;

  /* These constants need to have these exact values.  They
   * correspond to index positions within the localPatternChars
   * string for a given locale.  Each locale may specify its
   * own character for a particular field, but the position
   * of these characters must correspond to an appropriate field
   * number (as listed below), in order for their meaning to
   * be determined.  For example, the US locale uses
   * the string "GyMdkHmsSEDFwWahKzYeugAZ", where 'G' is the character
   * for era, 'y' for year, and so on down to 'Z' for time zone.
   */
  /**
   * Represents the position of the era
   * pattern character in the array of
   * localized pattern characters. 
   * For example, 'AD' is an era used
   * in the Gregorian calendar system.
   * In the U.S. locale, this is 'G'.
   */  
  public static final int ERA_FIELD = 0;
  /**
   * Represents the position of the year
   * pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'y'.
   */
  public static final int YEAR_FIELD = 1;
  /**
   * Represents the position of the month
   * pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'M'.
   */
  public static final int MONTH_FIELD = 2;
  /**
   * Represents the position of the date
   * or day of the month pattern character
   * in the array of localized pattern
   * characters.  In the U.S. locale,
   * this is 'd'.
   */
  public static final int DATE_FIELD = 3;
  /**
   * Represents the position of the 24
   * hour pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'k'.
   * This field numbers hours from 1 to 24.
   */
  public static final int HOUR_OF_DAY1_FIELD = 4;
  /**
   * Represents the position of the 24
   * hour pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'H'.
   * This field numbers hours from 0 to 23.
   */
  public static final int HOUR_OF_DAY0_FIELD = 5;
  /**
   * Represents the position of the minute
   * pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'm'.
   */
  public static final int MINUTE_FIELD = 6;
  /**
   * Represents the position of the second
   * pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 's'.
   */
  public static final int SECOND_FIELD = 7;
  /**
   * Represents the position of the millisecond
   * pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'S'.
   */
  public static final int MILLISECOND_FIELD = 8;
  /**
   * Represents the position of the day of the
   * week pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'E'.
   */
  public static final int DAY_OF_WEEK_FIELD = 9;
  /**
   * Represents the position of the day of the
   * year pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'D'.
   */
  public static final int DAY_OF_YEAR_FIELD = 10;
  /**
   * Represents the position of the day of the
   * week in the month pattern character in the
   * array of localized pattern characters.
   * In the U.S. locale, this is 'F'.
   */
  public static final int DAY_OF_WEEK_IN_MONTH_FIELD = 11;
  /**
   * Represents the position of the week of the
   * year pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'w'.
   */
  public static final int WEEK_OF_YEAR_FIELD = 12;
  /**
   * Represents the position of the week of the
   * month pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'W'.
   */
  public static final int WEEK_OF_MONTH_FIELD = 13;
  /**
   * Represents the position of the am/pm
   * pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'a'.
   */
  public static final int AM_PM_FIELD = 14;
  /**
   * Represents the position of the 12 
   * hour pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'h'.
   * This field numbers hours from 1 to 12.
   */
  public static final int HOUR1_FIELD = 15;
  /**
   * Represents the position of the 12 
   * hour pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'K'.
   * This field numbers hours from 0 to 11.
   */
  public static final int HOUR0_FIELD = 16;
  /**
   * Represents the position of the generic
   * timezone pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'z'.
   */
  public static final int TIMEZONE_FIELD = 17;
  /**
   * Represents the position of the ISO year
   * pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'Y'.
   * This is a GNU extension in accordance with
   * the CLDR data used.  This value may
   * differ from the normal year value.
   */
  public static final int ISO_YEAR_FIELD = 18;
  /**
   * Represents the position of the localized
   * day of the week pattern character in the
   * array of localized pattern characters.
   * In the U.S. locale, this is 'e'.
   * This is a GNU extension in accordance with
   * the CLDR data used.  This value only
   * differs from the day of the week with
   * numeric formatting, in which case the
   * locale's first day of the week is used.
   */
  public static final int LOCALIZED_DAY_OF_WEEK_FIELD = 19;
  /**
   * Represents the position of the extended year
   * pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'u'.
   * This is a GNU extension in accordance with
   * the CLDR data used.  This value modifies
   * the year value, so as to incorporate the era.
   * For example, in the Gregorian calendar system,
   * the extended year is negative instead of being
   * marked as BC.
   */
  public static final int EXTENDED_YEAR_FIELD = 20;
  /**
   * Represents the position of the modified Julian
   * day pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'g'.
   * This is a GNU extension in accordance with
   * the CLDR data used.  This value differs
   * from the standard Julian day in that days
   * are marked from midnight onwards rather than
   * noon, and the local time zone affects the value.
   * In simple terms, it can be thought of as all
   * the date fields represented as a single number.
   */
  public static final int MODIFIED_JULIAN_DAY_FIELD = 21;
  /**
   * Represents the position of the millisecond
   * in the day pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'A'.
   * This is a GNU extension in accordance with
   * the CLDR data used.  This value represents
   * all the time fields (excluding the time zone)
   * numerically, giving the number of milliseconds
   * into the day (e.g. 10 in the morning would
   * be 10 * 60 * 60 * 1000).  Any daylight savings
   * offset also affects this value.
   */
  public static final int MILLISECOND_IN_DAY_FIELD = 22;
  /**
   * Represents the position of the RFC822
   * timezone pattern character in the array of
   * localized pattern characters.
   * In the U.S. locale, this is 'Z'.
   * This is a GNU extension in accordance with
   * the CLDR data used.  The value is the offset
   * of the current time from GMT e.g. -0500 would
   * be five hours prior to GMT.
   */
  public static final int RFC822_TIMEZONE_FIELD = 23;

  public static class Field extends Format.Field
  {
    static final long serialVersionUID = 7441350119349544720L;
    
    private int calendarField;

    public static final DateFormat.Field ERA
	= new Field("era", Calendar.ERA);
    public static final DateFormat.Field YEAR
	= new Field("year", Calendar.YEAR);
    public static final DateFormat.Field MONTH
	= new Field("month", Calendar.MONTH);
    public static final DateFormat.Field DAY_OF_MONTH
	= new Field("day of month", Calendar.DAY_OF_MONTH);
    public static final DateFormat.Field HOUR_OF_DAY1
	= new Field("hour of day 1", Calendar.HOUR_OF_DAY);
    public static final DateFormat.Field HOUR_OF_DAY0
	= new Field("hour of day 0", Calendar.HOUR_OF_DAY);
    public static final DateFormat.Field MINUTE
	= new Field("minute", Calendar.MINUTE);
    public static final DateFormat.Field SECOND
	= new Field("second", Calendar.SECOND);
    public static final DateFormat.Field MILLISECOND
	= new Field("millisecond", Calendar.MILLISECOND);
    public static final DateFormat.Field DAY_OF_WEEK
	= new Field("day of week", Calendar.DAY_OF_WEEK);
    public static final DateFormat.Field DAY_OF_YEAR
	= new Field("day of year", Calendar.DAY_OF_YEAR);
    public static final DateFormat.Field DAY_OF_WEEK_IN_MONTH
	= new Field("day of week in month", Calendar.DAY_OF_WEEK_IN_MONTH);
    public static final DateFormat.Field WEEK_OF_YEAR
	= new Field("week of year", Calendar.WEEK_OF_YEAR);
    public static final DateFormat.Field WEEK_OF_MONTH
	= new Field("week of month", Calendar.WEEK_OF_MONTH);
    public static final DateFormat.Field AM_PM
	= new Field("am/pm", Calendar.AM_PM);
    public static final DateFormat.Field HOUR1
	= new Field("hour1", Calendar.HOUR);
    public static final DateFormat.Field HOUR0
	= new Field("hour0", Calendar.HOUR);
    public static final DateFormat.Field TIME_ZONE
	= new Field("timezone", Calendar.ZONE_OFFSET);
    public static final DateFormat.Field ISO_YEAR
	= new Field("iso year", Calendar.YEAR);
    public static final DateFormat.Field LOCALIZED_DAY_OF_WEEK
	= new Field("localized day of week", Calendar.DAY_OF_WEEK);
    public static final DateFormat.Field EXTENDED_YEAR
      = new Field("extended year", Calendar.YEAR);
    public static final DateFormat.Field MODIFIED_JULIAN_DAY
	= new Field("julian day", -1);
    public static final DateFormat.Field MILLISECOND_IN_DAY
	= new Field("millisecond in day", -1);
    public static final DateFormat.Field RFC822_TIME_ZONE
	= new Field("rfc822 timezone", Calendar.ZONE_OFFSET);

    static final DateFormat.Field[] allFields =
    {
      ERA, YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY1,
      HOUR_OF_DAY0, MINUTE, SECOND, MILLISECOND,
      DAY_OF_WEEK, DAY_OF_YEAR, DAY_OF_WEEK_IN_MONTH,
      WEEK_OF_YEAR, WEEK_OF_MONTH, AM_PM, HOUR1, HOUR0,
      TIME_ZONE, ISO_YEAR, LOCALIZED_DAY_OF_WEEK,
      EXTENDED_YEAR, MODIFIED_JULIAN_DAY, MILLISECOND_IN_DAY,
      RFC822_TIME_ZONE
    };

    // For deserialization
    private Field()
    {
      super("");
    }

    protected Field(String name, int calendarField)
    {
      super(name);
      this.calendarField = calendarField;
    }
    
    public int getCalendarField()
    {
      return calendarField;
    }

    public static Field ofCalendarField(int calendarField)
    {
      if (calendarField >= allFields.length || calendarField < 0)
	throw new IllegalArgumentException("no such calendar field ("
					   + calendarField + ")");
      
      return allFields[calendarField];
    }
    
    protected Object readResolve() throws InvalidObjectException
    {
      String s = getName();

      for (int i=0;i<allFields.length;i++)
	if (s.equals(allFields[i].getName()))
	  return allFields[i];
      
      throw new InvalidObjectException("no such DateFormat field called " + s);
    }
  }

  /**
   * This method initializes a new instance of <code>DateFormat</code>.
   */
  protected DateFormat ()
  {
  }

  /**
   * This method tests this object for equality against the specified object.
   * The two objects will be considered equal if an only if the specified
   * object:
   * <P>
   * <ul>
   * <li>Is not <code>null</code>.</li>
   * <li>Is an instance of <code>DateFormat</code>.</li>
   * <li>Has equal numberFormat field as this object.</li>
   * <li>Has equal (Calendar) TimeZone rules as this object.</li>
   * <li>Has equal (Calendar) isLenient results.</li> 
   * <li>Has equal Calendar first day of week and minimal days in week
   * values.</li>
   * </ul>
   * Note that not all properties of the Calendar are relevant for a
   * DateFormat. For formatting only the fact whether or not the
   * TimeZone has the same rules and whether the calendar is lenient
   * and has the same week rules is compared for this implementation
   * of equals. Other properties of the Calendar (such as the time)
   * are not taken into account.
   *
   * @param obj The object to test for equality against.
   * 
   * @return <code>true</code> if the specified object is equal to this object,
   * <code>false</code> otherwise.
   */
  public boolean equals (Object obj)
  {
    if (!(obj instanceof DateFormat))
      return false;

    DateFormat d = (DateFormat) obj;
    TimeZone tz = getTimeZone();
    TimeZone tzd = d.getTimeZone();
    if (tz.hasSameRules(tzd))
      if (isLenient() == d.isLenient())
	{
	  Calendar c = getCalendar();
	  Calendar cd = d.getCalendar();
	  if ((c == null && cd == null)
	      ||
	      (c.getFirstDayOfWeek() == cd.getFirstDayOfWeek()
	       &&
	       c.getMinimalDaysInFirstWeek()
	       == cd.getMinimalDaysInFirstWeek()))
	    return ((numberFormat == null && d.numberFormat == null)
		    || numberFormat.equals(d.numberFormat));
	}

    return false;
  }

  /**
   * This method returns a copy of this object.
   *
   * @return A copy of this object.
   */
  public Object clone ()
  {
    // We know the superclass just call's Object's generic cloner.
    return super.clone ();
  }

  /**
   * This method formats the specified <code>Object</code> into a date string
   * and appends it to the specified <code>StringBuffer</code>.
   * The specified object must be an instance of <code>Number</code> or
   * <code>Date</code> or an <code>IllegalArgumentException</code> will be
   * thrown.
   *
   * @param obj The <code>Object</code> to format.
   * @param buf The <code>StringBuffer</code> to append the resultant
   * <code>String</code> to.
   * @param pos Is updated to the start and end index of the
   * specified field.
   *
   * @return The <code>StringBuffer</code> supplied on input, with the
   * formatted date/time appended.
   */
  public final StringBuffer format (Object obj,
				    StringBuffer buf, FieldPosition pos)
  {
    if (obj instanceof Number)
      obj = new Date(((Number) obj).longValue());
    else if (! (obj instanceof Date))
      throw new IllegalArgumentException
	("Cannot format given Object as a Date");

    return format ((Date) obj, buf, pos);
  }

  /**  
    * Formats the date argument according to the pattern specified. 
    *
    * @param date The formatted date.
    */
  public final String format (Date date)
  {
    StringBuffer sb = new StringBuffer ();
    format (date, sb, new FieldPosition (MONTH_FIELD));
    return sb.toString();
  }

  /**
   * This method formats a <code>Date</code> into a string and appends it
   * to the specified <code>StringBuffer</code>.
   *
   * @param date The <code>Date</code> value to format.
   * @param buf The <code>StringBuffer</code> to append the resultant
   * <code>String</code> to.
   * @param pos Is updated to the start and end index of the
   * specified field.
   *
   * @return The <code>StringBuffer</code> supplied on input, with the
   * formatted date/time appended.
   */
  public abstract StringBuffer format (Date date,
				       StringBuffer buf, FieldPosition pos);

  /**
   * This method returns a list of available locales supported by this
   * class.
   */
  public static Locale[] getAvailableLocales()
  {
    return Locale.getAvailableLocales();
  }

  /**
    * This method returns the <code>Calendar</code> object being used by
    * this object to parse/format datetimes.
    *
    * @return The <code>Calendar</code> being used by this object.
    *
    * @see java.util.Calendar
    */
  public Calendar getCalendar ()
  {
    return calendar;
  }

  private static DateFormat computeInstance (int style, Locale loc,
                                             boolean use_date, boolean use_time)
  {
    return computeInstance (style, style, loc, use_date, use_time);
  }

  private static DateFormat computeInstance (int dateStyle, int timeStyle,
                                             Locale loc, boolean use_date,
                                             boolean use_time)
  {
    ResourceBundle res;
    try
      {
	res = ResourceBundle.getBundle("gnu.java.locale.LocaleInformation",
				       loc, ClassLoader.getSystemClassLoader());
      }
    catch (MissingResourceException x)
      {
	res = null;
      }

    String pattern = null;
    if (use_date)
      {
	String name, def;
	switch (dateStyle)
	  {
	  case FULL:
	    name = "fullDateFormat";
	    def = "EEEE MMMM d, yyyy G";
	    break;
	  case LONG:
	    name = "longDateFormat";
	    def = "MMMM d, yyyy";
	    break;
	  case MEDIUM:
	    name = "mediumDateFormat";
	    def = "d-MMM-yy";
	    break;
	  case SHORT:
	    name = "shortDateFormat";
	    def = "M/d/yy";
	    break;
	  default:
	    throw new IllegalArgumentException ();
	  }
	try
	  {
	    pattern = res == null ? def : res.getString(name);
	  }
	catch (MissingResourceException x)
	  {
	    pattern = def;
	  }
      }

    if (use_time)
      {
	if (pattern == null)
	  pattern = "";
	else
	  pattern += " ";

	String name, def;
	switch (timeStyle)
	  {
	  case FULL:
	    name = "fullTimeFormat";
	    def = "h:mm:ss;S 'o''clock' a z";
	    break;
	  case LONG:
	    name = "longTimeFormat";
	    def = "h:mm:ss a z";
	    break;
	  case MEDIUM:
	    name = "mediumTimeFormat";
	    def = "h:mm:ss a";
	    break;
	  case SHORT:
	    name = "shortTimeFormat";
	    def = "h:mm a";
	    break;
	  default:
	    throw new IllegalArgumentException ();
	  }

	String s;
	try
	  {
	    s = res == null ? def : res.getString(name);
	  }
	catch (MissingResourceException x)
	  {
	    s = def;
	  }
	pattern += s;
      }

    return new SimpleDateFormat (pattern, loc);
  }

 /**
   * This method returns an instance of <code>DateFormat</code> that will
   * format using the default formatting style for dates.
   *
   * @return A new <code>DateFormat</code> instance.
   */
  public static final DateFormat getDateInstance ()
  {
    return getDateInstance (DEFAULT, Locale.getDefault());
  }

  /**
   * This method returns an instance of <code>DateFormat</code> that will
   * format using the specified formatting style for dates.
   *
   * @param style The type of formatting to perform. 
   * 
   * @return A new <code>DateFormat</code> instance.
   */
  public static final DateFormat getDateInstance (int style)
  {
    return getDateInstance (style, Locale.getDefault());
  }

  /**
   * This method returns an instance of <code>DateFormat</code> that will
   * format using the specified formatting style for dates.  The specified
   * localed will be used in place of the default.
   *
   * @param style The type of formatting to perform. 
   * @param loc The desired locale.
   * 
   * @return A new <code>DateFormat</code> instance.
   */
  public static final DateFormat getDateInstance (int style, Locale loc)
  {
    return computeInstance (style, loc, true, false);
  }

  /**
   * This method returns a new instance of <code>DateFormat</code> that
   * formats both dates and times using the <code>SHORT</code> style.
   *
   * @return A new <code>DateFormat</code>instance.
   */
  public static final DateFormat getDateTimeInstance ()
  {
    return getDateTimeInstance (DEFAULT, DEFAULT, Locale.getDefault());
  }

  /**
   * This method returns a new instance of <code>DateFormat</code> that
   * formats both dates and times using the <code>DEFAULT</code> style.
   *
   * @return A new <code>DateFormat</code>instance.
   */
  public static final DateFormat getDateTimeInstance (int dateStyle, 
						      int timeStyle)
  {
    return getDateTimeInstance (dateStyle, timeStyle, Locale.getDefault());
  }

  /**
   * This method returns a new instance of <code>DateFormat</code> that
   * formats both dates and times using the specified styles.
   * 
   * @param dateStyle The desired style for date formatting.
   * @param timeStyle The desired style for time formatting
   *
   * @return A new <code>DateFormat</code>instance.
   */
  public static final DateFormat getDateTimeInstance (int dateStyle, 
						      int timeStyle, 
						      Locale loc)
  {
    return computeInstance (dateStyle, timeStyle, loc, true, true);
  }

  /**
   * This method returns a new instance of <code>DateFormat</code> that
   * formats both dates and times using the <code>SHORT</code> style.
   *
   * @return A new <code>DateFormat</code>instance.
   */
  public static final DateFormat getInstance ()
  {
    // JCL book says SHORT.
    return getDateTimeInstance (SHORT, SHORT, Locale.getDefault());
  }

  /**
   * This method returns the <code>NumberFormat</code> object being used
   * by this object to parse/format time values.
   *
   * @return The <code>NumberFormat</code> in use by this object.
   */
  public NumberFormat getNumberFormat ()
  {
    return numberFormat;
  }

 /**
   * This method returns an instance of <code>DateFormat</code> that will
   * format using the default formatting style for times.
   *
   * @return A new <code>DateFormat</code> instance.
   */
  public static final DateFormat getTimeInstance ()
  {
    return getTimeInstance (DEFAULT, Locale.getDefault());
  }

  /**
   * This method returns an instance of <code>DateFormat</code> that will
   * format using the specified formatting style for times.
   *
   * @param style The type of formatting to perform. 
   * 
   * @return A new <code>DateFormat</code> instance.
   */
  public static final DateFormat getTimeInstance (int style)
  {
    return getTimeInstance (style, Locale.getDefault());
  }

  /**
   * This method returns an instance of <code>DateFormat</code> that will
   * format using the specified formatting style for times.  The specified
   * localed will be used in place of the default.
   *
   * @param style The type of formatting to perform. 
   * @param loc The desired locale.
   * 
   * @return A new <code>DateFormat</code> instance.
   */
  public static final DateFormat getTimeInstance (int style, Locale loc)
  {
    return computeInstance (style, loc, false, true);
  }

  /**
   * This method returns the <code>TimeZone</code> object being used by
   * this instance.
   *
   * @return The time zone in use.
   */
  public TimeZone getTimeZone ()
  {
    return calendar.getTimeZone();
  }

  /**
   * This method returns a hash value for this object.
   * 
   * @return A hash value for this object.
   */
  public int hashCode ()
  {
    if (numberFormat != null)
      return numberFormat.hashCode();
    else
      return 0;
  }

  /**
   * This method indicates whether or not the parsing of date and time
   * values should be done in a lenient value.
   *
   * @return <code>true</code> if date/time parsing is lenient,
   * <code>false</code> otherwise.
   */
  public boolean isLenient ()
  {
    return calendar.isLenient();
  }

  /**
   * This method parses the specified date/time string.
   *
   * @param source The string to parse.
   * @return The resultant date.
   *
   * @exception ParseException If the specified string cannot be parsed.
   */
  public Date parse (String source) throws ParseException
  {
    ParsePosition pos = new ParsePosition(0);
    Date result = parse (source, pos);
    if (result == null)
      {
	int index = pos.getErrorIndex();
	if (index < 0)
	  index = pos.getIndex();
	throw new ParseException("invalid Date syntax in \""
				 + source + '\"', index);
      }
    return result;
  }

  /** 
   * This method parses the specified <code>String</code> into a 
   * <code>Date</code>.  The <code>pos</code> argument contains the
   * starting parse position on method entry and the ending parse
   * position on method exit.
   *
   * @param source The string to parse.
   * @param pos The starting parse position in entry, the ending parse
   * position on exit.
   *
   * @return The parsed date, or <code>null</code> if the string cannot
   * be parsed.
   */
  public abstract Date parse (String source, ParsePosition pos);

  /**
   * This method is identical to <code>parse(String, ParsePosition)</code>,
   * but returns its result as an <code>Object</code> instead of a
   * <code>Date</code>.
   * 
   * @param source The string to parse.
   * @param pos The starting parse position in entry, the ending parse
   * position on exit.
   *
   * @return The parsed date, or <code>null</code> if the string cannot
   * be parsed.
   */
  public Object parseObject (String source, ParsePosition pos)
  {
    return parse(source, pos);
  }

  /**
   * This method specified the <code>Calendar</code> that should be used 
   * by this object to parse/format datetimes.
   *
   * @param calendar The new <code>Calendar</code> for this object.
   *
   * @see java.util.Calendar
   */
  public void setCalendar (Calendar calendar)
  {
    this.calendar = calendar;
  }

  /**
   * This method specifies whether or not this object should be lenient in 
   * the syntax it accepts while parsing date/time values.
   *
   * @param lenient <code>true</code> if parsing should be lenient,
   * <code>false</code> otherwise.
   */
  public void setLenient (boolean lenient)
  {
    calendar.setLenient(lenient);
  }

  /**
   * This method specifies the <code>NumberFormat</code> object that should
   * be used by this object to parse/format times.
   *
   * @param numberFormat The <code>NumberFormat</code> in use by this object.
   */
  public void setNumberFormat (NumberFormat numberFormat)
  {
    this.numberFormat = numberFormat;
  }

  /**
   * This method sets the time zone that should be used by this object.
   *
   * @param timeZone The new time zone.
   */
  public void setTimeZone (TimeZone timeZone)
  {
    calendar.setTimeZone(timeZone);
  }
}
t-mul-patterns'>users/gysit/remove-arith-ext-mul-patterns Unnamed repository; edit this file 'description' to name the repository.root
aboutsummaryrefslogtreecommitdiff
path: root/flang/lib/Parser/unparse.cpp
blob: 4a66d528f407c6467a1bfd3e11218acc43e2e31f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
//===-- lib/Parser/unparse.cpp --------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// Generates Fortran from the content of a parse tree, using the
// traversal templates in parse-tree-visitor.h.

#include "flang/Parser/unparse.h"
#include "flang/Common/Fortran.h"
#include "flang/Common/idioms.h"
#include "flang/Common/indirection.h"
#include "flang/Parser/characters.h"
#include "flang/Parser/parse-tree-visitor.h"
#include "flang/Parser/parse-tree.h"
#include "flang/Parser/tools.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cinttypes>
#include <cstddef>
#include <set>

namespace Fortran::parser {

class UnparseVisitor {
public:
  UnparseVisitor(llvm::raw_ostream &out, int indentationAmount,
      Encoding encoding, bool capitalize, bool backslashEscapes,
      preStatementType *preStatement, AnalyzedObjectsAsFortran *asFortran)
      : out_{out}, indentationAmount_{indentationAmount}, encoding_{encoding},
        capitalizeKeywords_{capitalize}, backslashEscapes_{backslashEscapes},
        preStatement_{preStatement}, asFortran_{asFortran} {}

  // In nearly all cases, this code avoids defining Boolean-valued Pre()
  // callbacks for the parse tree walking framework in favor of two void
  // functions, Before() and Unparse(), which imply true and false return
  // values for Pre() respectively.
  template <typename T> void Before(const T &) {}
  template <typename T> double Unparse(const T &); // not void, never used

  template <typename T> bool Pre(const T &x) {
    if constexpr (std::is_void_v<decltype(Unparse(x))>) {
      // There is a local definition of Unparse() for this type.  It
      // overrides the parse tree walker's default Walk() over the descendents.
      Before(x);
      Unparse(x);
      Post(x);
      return false; // Walk() does not visit descendents
    } else if constexpr (HasTypedExpr<T>::value) {
      // Format the expression representation from semantics
      if (asFortran_ && x.typedExpr) {
        asFortran_->expr(out_, *x.typedExpr);
        return false;
      } else {
        return true;
      }
    } else {
      Before(x);
      return true; // there's no Unparse() defined here, Walk() the descendents
    }
  }
  template <typename T> void Post(const T &) {}

  // Emit simple types as-is.
  void Unparse(const std::string &x) { Put(x); }
  void Unparse(int x) { Put(std::to_string(x)); }
  void Unparse(unsigned int x) { Put(std::to_string(x)); }
  void Unparse(long x) { Put(std::to_string(x)); }
  void Unparse(unsigned long x) { Put(std::to_string(x)); }
  void Unparse(long long x) { Put(std::to_string(x)); }
  void Unparse(unsigned long long x) { Put(std::to_string(x)); }
  void Unparse(char x) { Put(x); }

  // Statement labels and ends of lines
  template <typename T> void Before(const Statement<T> &x) {
    if (preStatement_) {
      (*preStatement_)(x.source, out_, indent_);
    }
    Walk(x.label, " ");
  }
  template <typename T> void Post(const Statement<T> &) { Put('\n'); }

  // The special-case formatting functions for these productions are
  // ordered to correspond roughly to their order of appearance in
  // the Fortran 2018 standard (and parse-tree.h).

  void Unparse(const Program &x) { // R501
    Walk("", x.v, "\n"); // put blank lines between ProgramUnits
  }

  void Unparse(const Name &x) { // R603
    Put(x.ToString());
  }
  void Unparse(const DefinedOperator::IntrinsicOperator &x) { // R608
    switch (x) {
    case DefinedOperator::IntrinsicOperator::Power:
      Put("**");
      break;
    case DefinedOperator::IntrinsicOperator::Multiply:
      Put('*');
      break;
    case DefinedOperator::IntrinsicOperator::Divide:
      Put('/');
      break;
    case DefinedOperator::IntrinsicOperator::Add:
      Put('+');
      break;
    case DefinedOperator::IntrinsicOperator::Subtract:
      Put('-');
      break;
    case DefinedOperator::IntrinsicOperator::Concat:
      Put("//");
      break;
    case DefinedOperator::IntrinsicOperator::LT:
      Put('<');
      break;
    case DefinedOperator::IntrinsicOperator::LE:
      Put("<=");
      break;
    case DefinedOperator::IntrinsicOperator::EQ:
      Put("==");
      break;
    case DefinedOperator::IntrinsicOperator::NE:
      Put("/=");
      break;
    case DefinedOperator::IntrinsicOperator::GE:
      Put(">=");
      break;
    case DefinedOperator::IntrinsicOperator::GT:
      Put('>');
      break;
    default:
      Put('.'), Word(DefinedOperator::EnumToString(x)), Put('.');
    }
  }
  void Post(const Star &) { Put('*'); } // R701 &c.
  void Post(const TypeParamValue::Deferred &) { Put(':'); } // R701
  void Unparse(const DeclarationTypeSpec::Type &x) { // R703
    Word("TYPE("), Walk(x.derived), Put(')');
  }
  void Unparse(const DeclarationTypeSpec::Class &x) {
    Word("CLASS("), Walk(x.derived), Put(')');
  }
  void Post(const DeclarationTypeSpec::ClassStar &) { Word("CLASS(*)"); }
  void Post(const DeclarationTypeSpec::TypeStar &) { Word("TYPE(*)"); }
  void Unparse(const DeclarationTypeSpec::Record &x) {
    Word("RECORD/"), Walk(x.v), Put('/');
  }
  void Before(const IntrinsicTypeSpec::Real &) { // R704
    Word("REAL");
  }
  void Before(const IntrinsicTypeSpec::Complex &) { Word("COMPLEX"); }
  void Post(const IntrinsicTypeSpec::DoublePrecision &) {
    Word("DOUBLE PRECISION");
  }
  void Before(const IntrinsicTypeSpec::Character &) { Word("CHARACTER"); }
  void Before(const IntrinsicTypeSpec::Logical &) { Word("LOGICAL"); }
  void Post(const IntrinsicTypeSpec::DoubleComplex &) {
    Word("DOUBLE COMPLEX");
  }
  void Before(const IntegerTypeSpec &) { // R705
    Word("INTEGER");
  }
  void Unparse(const KindSelector &x) { // R706
    std::visit(
        common::visitors{
            [&](const ScalarIntConstantExpr &y) {
              Put('('), Word("KIND="), Walk(y), Put(')');
            },
            [&](const KindSelector::StarSize &y) { Put('*'), Walk(y.v); },
        },
        x.u);
  }
  void Unparse(const SignedIntLiteralConstant &x) { // R707
    Put(std::get<CharBlock>(x.t).ToString());
    Walk("_", std::get<std::optional<KindParam>>(x.t));
  }
  void Unparse(const IntLiteralConstant &x) { // R708
    Put(std::get<CharBlock>(x.t).ToString());
    Walk("_", std::get<std::optional<KindParam>>(x.t));
  }
  void Unparse(const Sign &x) { // R712
    Put(x == Sign::Negative ? '-' : '+');
  }
  void Unparse(const RealLiteralConstant &x) { // R714, R715
    Put(x.real.source.ToString()), Walk("_", x.kind);
  }
  void Unparse(const ComplexLiteralConstant &x) { // R718 - R720
    Put('('), Walk(x.t, ","), Put(')');
  }
  void Unparse(const CharSelector::LengthAndKind &x) { // R721
    Put('('), Word("KIND="), Walk(x.kind);
    Walk(", LEN=", x.length), Put(')');
  }
  void Unparse(const LengthSelector &x) { // R722
    std::visit(common::visitors{
                   [&](const TypeParamValue &y) {
                     Put('('), Word("LEN="), Walk(y), Put(')');
                   },
                   [&](const CharLength &y) { Put('*'), Walk(y); },
               },
        x.u);
  }
  void Unparse(const CharLength &x) { // R723
    std::visit(
        common::visitors{
            [&](const TypeParamValue &y) { Put('('), Walk(y), Put(')'); },
            [&](const std::int64_t &y) { Walk(y); },
        },
        x.u);
  }
  void Unparse(const CharLiteralConstant &x) { // R724
    const auto &str{std::get<std::string>(x.t)};
    if (const auto &k{std::get<std::optional<KindParam>>(x.t)}) {
      Walk(*k), Put('_');
    }
    PutNormalized(str);
  }
  void Unparse(const HollerithLiteralConstant &x) {
    auto ucs{DecodeString<std::u32string, Encoding::UTF_8>(x.v, false)};
    Unparse(ucs.size());
    Put('H');
    for (char32_t ch : ucs) {
      EncodedCharacter encoded{EncodeCharacter(encoding_, ch)};
      for (int j{0}; j < encoded.bytes; ++j) {
        Put(encoded.buffer[j]);
      }
    }
  }
  void Unparse(const LogicalLiteralConstant &x) { // R725
    Put(std::get<bool>(x.t) ? ".TRUE." : ".FALSE.");
    Walk("_", std::get<std::optional<KindParam>>(x.t));
  }
  void Unparse(const DerivedTypeStmt &x) { // R727
    Word("TYPE"), Walk(", ", std::get<std::list<TypeAttrSpec>>(x.t), ", ");
    Put(" :: "), Walk(std::get<Name>(x.t));
    Walk("(", std::get<std::list<Name>>(x.t), ", ", ")");
    Indent();
  }
  void Unparse(const Abstract &) { // R728, &c.
    Word("ABSTRACT");
  }
  void Post(const TypeAttrSpec::BindC &) { Word("BIND(C)"); }
  void Unparse(const TypeAttrSpec::Extends &x) {
    Word("EXTENDS("), Walk(x.v), Put(')');
  }
  void Unparse(const EndTypeStmt &x) { // R730
    Outdent(), Word("END TYPE"), Walk(" ", x.v);
  }
  void Unparse(const SequenceStmt &) { // R731
    Word("SEQUENCE");
  }
  void Unparse(const TypeParamDefStmt &x) { // R732
    Walk(std::get<IntegerTypeSpec>(x.t));
    Put(", "), Walk(std::get<common::TypeParamAttr>(x.t));
    Put(" :: "), Walk(std::get<std::list<TypeParamDecl>>(x.t), ", ");
  }
  void Unparse(const TypeParamDecl &x) { // R733
    Walk(std::get<Name>(x.t));
    Walk("=", std::get<std::optional<ScalarIntConstantExpr>>(x.t));
  }
  void Unparse(const DataComponentDefStmt &x) { // R737
    const auto &dts{std::get<DeclarationTypeSpec>(x.t)};
    const auto &attrs{std::get<std::list<ComponentAttrSpec>>(x.t)};
    const auto &decls{std::get<std::list<ComponentOrFill>>(x.t)};
    Walk(dts), Walk(", ", attrs, ", ");
    if (!attrs.empty() ||
        (!std::holds_alternative<DeclarationTypeSpec::Record>(dts.u) &&
            std::none_of(
                decls.begin(), decls.end(), [](const ComponentOrFill &c) {
                  return std::visit(
                      common::visitors{
                          [](const ComponentDecl &d) {
                            const auto &init{
                                std::get<std::optional<Initialization>>(d.t)};
                            return init &&
                                std::holds_alternative<std::list<
                                    common::Indirection<DataStmtValue>>>(
                                    init->u);
                          },
                          [](const FillDecl &) { return false; },
                      },
                      c.u);
                }))) {
      Put(" ::");
    }
    Put(' '), Walk(decls, ", ");
  }
  void Unparse(const Allocatable &) { // R738
    Word("ALLOCATABLE");
  }
  void Unparse(const Pointer &) { Word("POINTER"); }
  void Unparse(const Contiguous &) { Word("CONTIGUOUS"); }
  void Before(const ComponentAttrSpec &x) {
    std::visit(common::visitors{
                   [&](const CoarraySpec &) { Word("CODIMENSION["); },
                   [&](const ComponentArraySpec &) { Word("DIMENSION("); },
                   [](const auto &) {},
               },
        x.u);
  }
  void Post(const ComponentAttrSpec &x) {
    std::visit(common::visitors{
                   [&](const CoarraySpec &) { Put(']'); },
                   [&](const ComponentArraySpec &) { Put(')'); },
                   [](const auto &) {},
               },
        x.u);
  }
  void Unparse(const ComponentDecl &x) { // R739
    Walk(std::get<ObjectName>(x.t));
    Walk("(", std::get<std::optional<ComponentArraySpec>>(x.t), ")");
    Walk("[", std::get<std::optional<CoarraySpec>>(x.t), "]");
    Walk("*", std::get<std::optional<CharLength>>(x.t));
    Walk(std::get<std::optional<Initialization>>(x.t));
  }
  void Unparse(const FillDecl &x) { // DEC extension
    Put("%FILL");
    Walk("(", std::get<std::optional<ComponentArraySpec>>(x.t), ")");
    Walk("*", std::get<std::optional<CharLength>>(x.t));
  }
  void Unparse(const ComponentArraySpec &x) { // R740
    std::visit(common::visitors{
                   [&](const std::list<ExplicitShapeSpec> &y) { Walk(y, ","); },
                   [&](const DeferredShapeSpecList &y) { Walk(y); },
               },
        x.u);
  }
  void Unparse(const ProcComponentDefStmt &x) { // R741
    Word("PROCEDURE(");
    Walk(std::get<std::optional<ProcInterface>>(x.t)), Put(')');
    Walk(", ", std::get<std::list<ProcComponentAttrSpec>>(x.t), ", ");
    Put(" :: "), Walk(std::get<std::list<ProcDecl>>(x.t), ", ");
  }
  void Unparse(const NoPass &) { // R742
    Word("NOPASS");
  }
  void Unparse(const Pass &x) { Word("PASS"), Walk("(", x.v, ")"); }
  void Unparse(const Initialization &x) { // R743 & R805
    std::visit(common::visitors{
                   [&](const ConstantExpr &y) { Put(" = "), Walk(y); },
                   [&](const NullInit &y) { Put(" => "), Walk(y); },
                   [&](const InitialDataTarget &y) { Put(" => "), Walk(y); },
                   [&](const std::list<common::Indirection<DataStmtValue>> &y) {
                     Walk("/", y, ", ", "/");
                   },
               },
        x.u);
  }
  void Unparse(const PrivateStmt &) { // R745
    Word("PRIVATE");
  }
  void Unparse(const TypeBoundProcedureStmt::WithoutInterface &x) { // R749
    Word("PROCEDURE"), Walk(", ", x.attributes, ", ");
    Put(" :: "), Walk(x.declarations, ", ");
  }
  void Unparse(const TypeBoundProcedureStmt::WithInterface &x) {
    Word("PROCEDURE("), Walk(x.interfaceName), Put("), ");
    Walk(x.attributes);
    Put(" :: "), Walk(x.bindingNames, ", ");
  }
  void Unparse(const TypeBoundProcDecl &x) { // R750
    Walk(std::get<Name>(x.t));
    Walk(" => ", std::get<std::optional<Name>>(x.t));
  }
  void Unparse(const TypeBoundGenericStmt &x) { // R751
    Word("GENERIC"), Walk(", ", std::get<std::optional<AccessSpec>>(x.t));
    Put(" :: "), Walk(std::get<common::Indirection<GenericSpec>>(x.t));
    Put(" => "), Walk(std::get<std::list<Name>>(x.t), ", ");
  }
  void Post(const BindAttr::Deferred &) { Word("DEFERRED"); } // R752
  void Post(const BindAttr::Non_Overridable &) { Word("NON_OVERRIDABLE"); }
  void Unparse(const FinalProcedureStmt &x) { // R753
    Word("FINAL :: "), Walk(x.v, ", ");
  }
  void Unparse(const DerivedTypeSpec &x) { // R754
    Walk(std::get<Name>(x.t));
    Walk("(", std::get<std::list<TypeParamSpec>>(x.t), ",", ")");
  }
  void Unparse(const TypeParamSpec &x) { // R755
    Walk(std::get<std::optional<Keyword>>(x.t), "=");
    Walk(std::get<TypeParamValue>(x.t));
  }
  void Unparse(const StructureConstructor &x) { // R756
    Walk(std::get<DerivedTypeSpec>(x.t));
    Put('('), Walk(std::get<std::list<ComponentSpec>>(x.t), ", "), Put(')');
  }
  void Unparse(const ComponentSpec &x) { // R757
    Walk(std::get<std::optional<Keyword>>(x.t), "=");
    Walk(std::get<ComponentDataSource>(x.t));
  }
  void Unparse(const EnumDefStmt &) { // R760
    Word("ENUM, BIND(C)"), Indent();
  }
  void Unparse(const EnumeratorDefStmt &x) { // R761
    Word("ENUMERATOR :: "), Walk(x.v, ", ");
  }
  void Unparse(const Enumerator &x) { // R762
    Walk(std::get<NamedConstant>(x.t));
    Walk(" = ", std::get<std::optional<ScalarIntConstantExpr>>(x.t));
  }
  void Post(const EndEnumStmt &) { // R763
    Outdent(), Word("END ENUM");
  }
  void Unparse(const BOZLiteralConstant &x) { // R764 - R767
    Put(x.v);
  }
  void Unparse(const AcValue::Triplet &x) { // R773
    Walk(std::get<0>(x.t)), Put(':'), Walk(std::get<1>(x.t));
    Walk(":", std::get<std::optional<ScalarIntExpr>>(x.t));
  }
  void Unparse(const ArrayConstructor &x) { // R769
    Put('['), Walk(x.v), Put(']');
  }
  void Unparse(const AcSpec &x) { // R770
    Walk(x.type, "::"), Walk(x.values, ", ");
  }
  template <typename A, typename B> void Unparse(const LoopBounds<A, B> &x) {
    Walk(x.name), Put('='), Walk(x.lower), Put(','), Walk(x.upper);
    Walk(",", x.step);
  }
  void Unparse(const AcImpliedDo &x) { // R774
    Put('('), Walk(std::get<std::list<AcValue>>(x.t), ", ");
    Put(", "), Walk(std::get<AcImpliedDoControl>(x.t)), Put(')');
  }
  void Unparse(const AcImpliedDoControl &x) { // R775
    Walk(std::get<std::optional<IntegerTypeSpec>>(x.t), "::");
    Walk(std::get<AcImpliedDoControl::Bounds>(x.t));
  }

  void Unparse(const TypeDeclarationStmt &x) { // R801
    const auto &dts{std::get<DeclarationTypeSpec>(x.t)};
    const auto &attrs{std::get<std::list<AttrSpec>>(x.t)};
    const auto &decls{std::get<std::list<EntityDecl>>(x.t)};
    Walk(dts), Walk(", ", attrs, ", ");

    static const auto isInitializerOldStyle{[](const Initialization &i) {
      return std::holds_alternative<
          std::list<common::Indirection<DataStmtValue>>>(i.u);
    }};
    static const auto hasAssignmentInitializer{[](const EntityDecl &d) {
      // Does a declaration have a new-style =x initializer?
      const auto &init{std::get<std::optional<Initialization>>(d.t)};
      return init && !isInitializerOldStyle(*init);
    }};
    static const auto hasSlashDelimitedInitializer{[](const EntityDecl &d) {
      // Does a declaration have an old-style /x/ initializer?
      const auto &init{std::get<std::optional<Initialization>>(d.t)};
      return init && isInitializerOldStyle(*init);
    }};
    const auto useDoubledColons{[&]() {
      bool isRecord{std::holds_alternative<DeclarationTypeSpec::Record>(dts.u)};
      if (!attrs.empty()) {
        // Attributes after the type require :: before the entities.
        CHECK(!isRecord);
        return true;
      }
      if (std::any_of(decls.begin(), decls.end(), hasAssignmentInitializer)) {
        // Always use :: with new style standard initializers (=x),
        // since the standard requires them to appear (even in free form,
        // where mandatory spaces already disambiguate INTEGER J=666).
        CHECK(!isRecord);
        return true;
      }
      if (isRecord) {
        // Never put :: in a legacy extension RECORD// statement.
        return false;
      }
      // The :: is optional for this declaration.  Avoid usage that can
      // crash the pgf90 compiler.
      if (std::any_of(
              decls.begin(), decls.end(), hasSlashDelimitedInitializer)) {
        // Don't use :: when a declaration uses legacy DATA-statement-like
        // /x/ initialization.
        return false;
      }
      // Don't use :: with intrinsic types.  Otherwise, use it.
      return !std::holds_alternative<IntrinsicTypeSpec>(dts.u);
    }};

    if (useDoubledColons()) {
      Put(" ::");
    }
    Put(' '), Walk(std::get<std::list<EntityDecl>>(x.t), ", ");
  }
  void Before(const AttrSpec &x) { // R802
    std::visit(common::visitors{
                   [&](const CoarraySpec &) { Word("CODIMENSION["); },
                   [&](const ArraySpec &) { Word("DIMENSION("); },
                   [](const auto &) {},
               },
        x.u);
  }
  void Post(const AttrSpec &x) {
    std::visit(common::visitors{
                   [&](const CoarraySpec &) { Put(']'); },
                   [&](const ArraySpec &) { Put(')'); },
                   [](const auto &) {},
               },
        x.u);
  }
  void Unparse(const EntityDecl &x) { // R803
    Walk(std::get<ObjectName>(x.t));
    Walk("(", std::get<std::optional<ArraySpec>>(x.t), ")");
    Walk("[", std::get<std::optional<CoarraySpec>>(x.t), "]");
    Walk("*", std::get<std::optional<CharLength>>(x.t));
    Walk(std::get<std::optional<Initialization>>(x.t));
  }
  void Unparse(const NullInit &) { // R806
    Word("NULL()");
  }
  void Unparse(const LanguageBindingSpec &x) { // R808 & R1528
    Word("BIND(C"), Walk(", NAME=", x.v), Put(')');
  }
  void Unparse(const CoarraySpec &x) { // R809
    std::visit(common::visitors{
                   [&](const DeferredCoshapeSpecList &y) { Walk(y); },
                   [&](const ExplicitCoshapeSpec &y) { Walk(y); },
               },
        x.u);
  }
  void Unparse(const DeferredCoshapeSpecList &x) { // R810
    for (auto j{x.v}; j > 0; --j) {
      Put(':');
      if (j > 1) {
        Put(',');
      }
    }
  }
  void Unparse(const ExplicitCoshapeSpec &x) { // R811
    Walk(std::get<std::list<ExplicitShapeSpec>>(x.t), ",", ",");
    Walk(std::get<std::optional<SpecificationExpr>>(x.t), ":"), Put('*');
  }
  void Unparse(const ExplicitShapeSpec &x) { // R812 - R813 & R816 - R818
    Walk(std::get<std::optional<SpecificationExpr>>(x.t), ":");
    Walk(std::get<SpecificationExpr>(x.t));
  }
  void Unparse(const ArraySpec &x) { // R815
    std::visit(common::visitors{
                   [&](const std::list<ExplicitShapeSpec> &y) { Walk(y, ","); },
                   [&](const std::list<AssumedShapeSpec> &y) { Walk(y, ","); },
                   [&](const DeferredShapeSpecList &y) { Walk(y); },
                   [&](const AssumedSizeSpec &y) { Walk(y); },
                   [&](const ImpliedShapeSpec &y) { Walk(y); },
                   [&](const AssumedRankSpec &y) { Walk(y); },
               },
        x.u);
  }
  void Post(const AssumedShapeSpec &) { Put(':'); } // R819
  void Unparse(const DeferredShapeSpecList &x) { // R820
    for (auto j{x.v}; j > 0; --j) {
      Put(':');
      if (j > 1) {
        Put(',');
      }
    }
  }
  void Unparse(const AssumedImpliedSpec &x) { // R821
    Walk(x.v, ":");
    Put('*');
  }
  void Unparse(const AssumedSizeSpec &x) { // R822
    Walk(std::get<std::list<ExplicitShapeSpec>>(x.t), ",", ",");
    Walk(std::get<AssumedImpliedSpec>(x.t));
  }
  void Unparse(const ImpliedShapeSpec &x) { // R823
    Walk(x.v, ",");
  }
  void Post(const AssumedRankSpec &) { Put(".."); } // R825
  void Post(const Asynchronous &) { Word("ASYNCHRONOUS"); }
  void Post(const External &) { Word("EXTERNAL"); }
  void Post(const Intrinsic &) { Word("INTRINSIC"); }
  void Post(const Optional &) { Word("OPTIONAL"); }
  void Post(const Parameter &) { Word("PARAMETER"); }
  void Post(const Protected &) { Word("PROTECTED"); }
  void Post(const Save &) { Word("SAVE"); }
  void Post(const Target &) { Word("TARGET"); }
  void Post(const Value &) { Word("VALUE"); }
  void Post(const Volatile &) { Word("VOLATILE"); }
  void Unparse(const IntentSpec &x) { // R826
    Word("INTENT("), Walk(x.v), Put(")");
  }
  void Unparse(const AccessStmt &x) { // R827
    Walk(std::get<AccessSpec>(x.t));
    Walk(" :: ", std::get<std::list<AccessId>>(x.t), ", ");
  }
  void Unparse(const AllocatableStmt &x) { // R829
    Word("ALLOCATABLE :: "), Walk(x.v, ", ");
  }
  void Unparse(const ObjectDecl &x) { // R830 & R860
    Walk(std::get<ObjectName>(x.t));
    Walk("(", std::get<std::optional<ArraySpec>>(x.t), ")");
    Walk("[", std::get<std::optional<CoarraySpec>>(x.t), "]");
  }
  void Unparse(const AsynchronousStmt &x) { // R831
    Word("ASYNCHRONOUS :: "), Walk(x.v, ", ");
  }
  void Unparse(const BindStmt &x) { // R832
    Walk(x.t, " :: ");
  }
  void Unparse(const BindEntity &x) { // R833
    bool isCommon{std::get<BindEntity::Kind>(x.t) == BindEntity::Kind::Common};
    const char *slash{isCommon ? "/" : ""};
    Put(slash), Walk(std::get<Name>(x.t)), Put(slash);
  }
  void Unparse(const CodimensionStmt &x) { // R834
    Word("CODIMENSION :: "), Walk(x.v, ", ");
  }
  void Unparse(const CodimensionDecl &x) { // R835
    Walk(std::get<Name>(x.t));
    Put('['), Walk(std::get<CoarraySpec>(x.t)), Put(']');
  }
  void Unparse(const ContiguousStmt &x) { // R836
    Word("CONTIGUOUS :: "), Walk(x.v, ", ");
  }
  void Unparse(const DataStmt &x) { // R837
    Word("DATA "), Walk(x.v, ", ");
  }
  void Unparse(const DataStmtSet &x) { // R838
    Walk(std::get<std::list<DataStmtObject>>(x.t), ", ");
    Put('/'), Walk(std::get<std::list<DataStmtValue>>(x.t), ", "), Put('/');
  }
  void Unparse(const DataImpliedDo &x) { // R840, R842
    Put('('), Walk(std::get<std::list<DataIDoObject>>(x.t), ", "), Put(',');
    Walk(std::get<std::optional<IntegerTypeSpec>>(x.t), "::");
    Walk(std::get<DataImpliedDo::Bounds>(x.t)), Put(')');
  }
  void Unparse(const DataStmtValue &x) { // R843
    Walk(std::get<std::optional<DataStmtRepeat>>(x.t), "*");
    Walk(std::get<DataStmtConstant>(x.t));
  }
  void Unparse(const DimensionStmt &x) { // R848
    Word("DIMENSION :: "), Walk(x.v, ", ");
  }
  void Unparse(const DimensionStmt::Declaration &x) {
    Walk(std::get<Name>(x.t));
    Put('('), Walk(std::get<ArraySpec>(x.t)), Put(')');
  }
  void Unparse(const IntentStmt &x) { // R849
    Walk(x.t, " :: ");
  }
  void Unparse(const OptionalStmt &x) { // R850
    Word("OPTIONAL :: "), Walk(x.v, ", ");
  }
  void Unparse(const ParameterStmt &x) { // R851
    Word("PARAMETER("), Walk(x.v, ", "), Put(')');
  }
  void Unparse(const NamedConstantDef &x) { // R852
    Walk(x.t, "=");
  }
  void Unparse(const PointerStmt &x) { // R853
    Word("POINTER :: "), Walk(x.v, ", ");
  }
  void Unparse(const PointerDecl &x) { // R854
    Walk(std::get<Name>(x.t));
    Walk("(", std::get<std::optional<DeferredShapeSpecList>>(x.t), ")");
  }
  void Unparse(const ProtectedStmt &x) { // R855
    Word("PROTECTED :: "), Walk(x.v, ", ");
  }
  void Unparse(const SaveStmt &x) { // R856
    Word("SAVE"), Walk(" :: ", x.v, ", ");
  }
  void Unparse(const SavedEntity &x) { // R857, R858
    bool isCommon{
        std::get<SavedEntity::Kind>(x.t) == SavedEntity::Kind::Common};
    const char *slash{isCommon ? "/" : ""};
    Put(slash), Walk(std::get<Name>(x.t)), Put(slash);
  }
  void Unparse(const TargetStmt &x) { // R859
    Word("TARGET :: "), Walk(x.v, ", ");
  }
  void Unparse(const ValueStmt &x) { // R861
    Word("VALUE :: "), Walk(x.v, ", ");
  }
  void Unparse(const VolatileStmt &x) { // R862
    Word("VOLATILE :: "), Walk(x.v, ", ");
  }
  void Unparse(const ImplicitStmt &x) { // R863
    Word("IMPLICIT ");
    std::visit(common::visitors{
                   [&](const std::list<ImplicitSpec> &y) { Walk(y, ", "); },
                   [&](const std::list<ImplicitStmt::ImplicitNoneNameSpec> &y) {
                     Word("NONE"), Walk(" (", y, ", ", ")");
                   },
               },
        x.u);
  }
  void Unparse(const ImplicitSpec &x) { // R864
    Walk(std::get<DeclarationTypeSpec>(x.t));
    Put('('), Walk(std::get<std::list<LetterSpec>>(x.t), ", "), Put(')');
  }
  void Unparse(const LetterSpec &x) { // R865
    Put(*std::get<const char *>(x.t));
    auto second{std::get<std::optional<const char *>>(x.t)};
    if (second) {
      Put('-'), Put(**second);
    }
  }
  void Unparse(const ImportStmt &x) { // R867
    Word("IMPORT");
    switch (x.kind) {
    case common::ImportKind::Default:
      Walk(" :: ", x.names, ", ");
      break;
    case common::ImportKind::Only:
      Put(", "), Word("ONLY: ");
      Walk(x.names, ", ");
      break;
    case common::ImportKind::None:
      Word(", NONE");
      break;
    case common::ImportKind::All:
      Word(", ALL");
      break;
    }
  }
  void Unparse(const NamelistStmt &x) { // R868
    Word("NAMELIST"), Walk(x.v, ", ");
  }
  void Unparse(const NamelistStmt::Group &x) {
    Put('/'), Walk(std::get<Name>(x.t)), Put('/');
    Walk(std::get<std::list<Name>>(x.t), ", ");
  }
  void Unparse(const EquivalenceStmt &x) { // R870, R871
    Word("EQUIVALENCE");
    const char *separator{" "};
    for (const std::list<EquivalenceObject> &y : x.v) {
      Put(separator), Put('('), Walk(y), Put(')');
      separator = ", ";
    }
  }
  void Unparse(const CommonStmt &x) { // R873
    Word("COMMON ");
    Walk(x.blocks);
  }
  void Unparse(const CommonBlockObject &x) { // R874
    Walk(std::get<Name>(x.t));
    Walk("(", std::get<std::optional<ArraySpec>>(x.t), ")");
  }
  void Unparse(const CommonStmt::Block &x) {
    Word("/"), Walk(std::get<std::optional<Name>>(x.t)), Word("/");
    Walk(std::get<std::list<CommonBlockObject>>(x.t));
  }

  void Unparse(const Substring &x) { // R908, R909
    Walk(std::get<DataRef>(x.t));
    Put('('), Walk(std::get<SubstringRange>(x.t)), Put(')');
  }
  void Unparse(const CharLiteralConstantSubstring &x) {
    Walk(std::get<CharLiteralConstant>(x.t));
    Put('('), Walk(std::get<SubstringRange>(x.t)), Put(')');
  }
  void Unparse(const SubstringRange &x) { // R910
    Walk(x.t, ":");
  }
  void Unparse(const PartRef &x) { // R912
    Walk(x.name);
    Walk("(", x.subscripts, ",", ")");
    Walk(x.imageSelector);
  }
  void Unparse(const StructureComponent &x) { // R913
    Walk(x.base);
    if (structureComponents_.find(x.component.source) !=
        structureComponents_.end()) {
      Put('.');
    } else {
      Put('%');
    }
    Walk(x.component);
  }
  void Unparse(const ArrayElement &x) { // R917
    Walk(x.base);
    Put('('), Walk(x.subscripts, ","), Put(')');
  }
  void Unparse(const SubscriptTriplet &x) { // R921
    Walk(std::get<0>(x.t)), Put(':'), Walk(std::get<1>(x.t));
    Walk(":", std::get<2>(x.t));
  }
  void Unparse(const ImageSelector &x) { // R924
    Put('['), Walk(std::get<std::list<Cosubscript>>(x.t), ",");
    Walk(",", std::get<std::list<ImageSelectorSpec>>(x.t), ","), Put(']');
  }
  void Before(const ImageSelectorSpec::Stat &) { // R926
    Word("STAT=");
  }
  void Before(const ImageSelectorSpec::Team_Number &) { Word("TEAM_NUMBER="); }
  void Before(const ImageSelectorSpec &x) {
    if (std::holds_alternative<TeamValue>(x.u)) {
      Word("TEAM=");
    }
  }
  void Unparse(const AllocateStmt &x) { // R927
    Word("ALLOCATE(");
    Walk(std::get<std::optional<TypeSpec>>(x.t), "::");
    Walk(std::get<std::list<Allocation>>(x.t), ", ");
    Walk(", ", std::get<std::list<AllocOpt>>(x.t), ", "), Put(')');
  }
  void Before(const AllocOpt &x) { // R928, R931
    std::visit(common::visitors{
                   [&](const AllocOpt::Mold &) { Word("MOLD="); },
                   [&](const AllocOpt::Source &) { Word("SOURCE="); },
                   [](const StatOrErrmsg &) {},
               },
        x.u);
  }
  void Unparse(const Allocation &x) { // R932
    Walk(std::get<AllocateObject>(x.t));
    Walk("(", std::get<std::list<AllocateShapeSpec>>(x.t), ",", ")");
    Walk("[", std::get<std::optional<AllocateCoarraySpec>>(x.t), "]");
  }
  void Unparse(const AllocateShapeSpec &x) { // R934 & R938
    Walk(std::get<std::optional<BoundExpr>>(x.t), ":");
    Walk(std::get<BoundExpr>(x.t));
  }
  void Unparse(const AllocateCoarraySpec &x) { // R937
    Walk(std::get<std::list<AllocateCoshapeSpec>>(x.t), ",", ",");
    Walk(std::get<std::optional<BoundExpr>>(x.t), ":"), Put('*');
  }
  void Unparse(const NullifyStmt &x) { // R939
    Word("NULLIFY("), Walk(x.v, ", "), Put(')');
  }
  void Unparse(const DeallocateStmt &x) { // R941
    Word("DEALLOCATE(");
    Walk(std::get<std::list<AllocateObject>>(x.t), ", ");
    Walk(", ", std::get<std::list<StatOrErrmsg>>(x.t), ", "), Put(')');
  }
  void Before(const StatOrErrmsg &x) { // R942 & R1165
    std::visit(common::visitors{
                   [&](const StatVariable &) { Word("STAT="); },
                   [&](const MsgVariable &) { Word("ERRMSG="); },
               },
        x.u);
  }

  // R1001 - R1022
  void Unparse(const Expr::Parentheses &x) { Put('('), Walk(x.v), Put(')'); }
  void Before(const Expr::UnaryPlus &) { Put("+"); }
  void Before(const Expr::Negate &) { Put("-"); }
  void Before(const Expr::NOT &) { Word(".NOT."); }
  void Unparse(const Expr::PercentLoc &x) {
    Word("%LOC("), Walk(x.v), Put(')');
  }
  void Unparse(const Expr::Power &x) { Walk(x.t, "**"); }
  void Unparse(const Expr::Multiply &x) { Walk(x.t, "*"); }
  void Unparse(const Expr::Divide &x) { Walk(x.t, "/"); }
  void Unparse(const Expr::Add &x) { Walk(x.t, "+"); }
  void Unparse(const Expr::Subtract &x) { Walk(x.t, "-"); }
  void Unparse(const Expr::Concat &x) { Walk(x.t, "//"); }
  void Unparse(const Expr::LT &x) { Walk(x.t, "<"); }
  void Unparse(const Expr::LE &x) { Walk(x.t, "<="); }
  void Unparse(const Expr::EQ &x) { Walk(x.t, "=="); }
  void Unparse(const Expr::NE &x) { Walk(x.t, "/="); }
  void Unparse(const Expr::GE &x) { Walk(x.t, ">="); }
  void Unparse(const Expr::GT &x) { Walk(x.t, ">"); }
  void Unparse(const Expr::AND &x) { Walk(x.t, ".AND."); }
  void Unparse(const Expr::OR &x) { Walk(x.t, ".OR."); }
  void Unparse(const Expr::EQV &x) { Walk(x.t, ".EQV."); }
  void Unparse(const Expr::NEQV &x) { Walk(x.t, ".NEQV."); }
  void Unparse(const Expr::ComplexConstructor &x) {
    Put('('), Walk(x.t, ","), Put(')');
  }
  void Unparse(const Expr::DefinedBinary &x) {
    Walk(std::get<1>(x.t)); // left
    Walk(std::get<DefinedOpName>(x.t));
    Walk(std::get<2>(x.t)); // right
  }
  void Unparse(const DefinedOpName &x) { // R1003, R1023, R1414, & R1415
    Walk(x.v);
  }
  void Unparse(const AssignmentStmt &x) { // R1032
    if (asFortran_ && x.typedAssignment.get()) {
      Put(' ');
      asFortran_->assignment(out_, *x.typedAssignment);
      Put('\n');
    } else {
      Walk(x.t, " = ");
    }
  }
  void Unparse(const PointerAssignmentStmt &x) { // R1033, R1034, R1038
    if (asFortran_ && x.typedAssignment.get()) {
      Put(' ');
      asFortran_->assignment(out_, *x.typedAssignment);
      Put('\n');
    } else {
      Walk(std::get<DataRef>(x.t));
      std::visit(
          common::visitors{
              [&](const std::list<BoundsRemapping> &y) {
                Put('('), Walk(y), Put(')');
              },
              [&](const std::list<BoundsSpec> &y) { Walk("(", y, ", ", ")"); },
          },
          std::get<PointerAssignmentStmt::Bounds>(x.t).u);
      Put(" => "), Walk(std::get<Expr>(x.t));
    }
  }
  void Post(const BoundsSpec &) { // R1035
    Put(':');
  }
  void Unparse(const BoundsRemapping &x) { // R1036
    Walk(x.t, ":");
  }
  void Unparse(const WhereStmt &x) { // R1041, R1045, R1046
    Word("WHERE ("), Walk(x.t, ") ");
  }
  void Unparse(const WhereConstructStmt &x) { // R1043
    Walk(std::get<std::optional<Name>>(x.t), ": ");
    Word("WHERE ("), Walk(std::get<LogicalExpr>(x.t)), Put(')');
    Indent();
  }
  void Unparse(const MaskedElsewhereStmt &x) { // R1047
    Outdent();
    Word("ELSEWHERE ("), Walk(std::get<LogicalExpr>(x.t)), Put(')');
    Walk(" ", std::get<std::optional<Name>>(x.t));
    Indent();
  }
  void Unparse(const ElsewhereStmt &x) { // R1048
    Outdent(), Word("ELSEWHERE"), Walk(" ", x.v), Indent();
  }
  void Unparse(const EndWhereStmt &x) { // R1049
    Outdent(), Word("END WHERE"), Walk(" ", x.v);
  }
  void Unparse(const ForallConstructStmt &x) { // R1051
    Walk(std::get<std::optional<Name>>(x.t), ": ");
    Word("FORALL"), Walk(std::get<common::Indirection<ConcurrentHeader>>(x.t));
    Indent();
  }
  void Unparse(const EndForallStmt &x) { // R1054
    Outdent(), Word("END FORALL"), Walk(" ", x.v);
  }
  void Before(const ForallStmt &) { // R1055
    Word("FORALL");
  }

  void Unparse(const AssociateStmt &x) { // R1103
    Walk(std::get<std::optional<Name>>(x.t), ": ");
    Word("ASSOCIATE (");
    Walk(std::get<std::list<Association>>(x.t), ", "), Put(')'), Indent();
  }
  void Unparse(const Association &x) { // R1104
    Walk(x.t, " => ");
  }
  void Unparse(const EndAssociateStmt &x) { // R1106
    Outdent(), Word("END ASSOCIATE"), Walk(" ", x.v);
  }
  void Unparse(const BlockStmt &x) { // R1108
    Walk(x.v, ": "), Word("BLOCK"), Indent();
  }
  void Unparse(const EndBlockStmt &x) { // R1110
    Outdent(), Word("END BLOCK"), Walk(" ", x.v);
  }
  void Unparse(const ChangeTeamStmt &x) { // R1112
    Walk(std::get<std::optional<Name>>(x.t), ": ");
    Word("CHANGE TEAM ("), Walk(std::get<TeamValue>(x.t));
    Walk(", ", std::get<std::list<CoarrayAssociation>>(x.t), ", ");
    Walk(", ", std::get<std::list<StatOrErrmsg>>(x.t), ", "), Put(')');
    Indent();
  }
  void Unparse(const CoarrayAssociation &x) { // R1113
    Walk(x.t, " => ");
  }
  void Unparse(const EndChangeTeamStmt &x) { // R1114
    Outdent(), Word("END TEAM (");
    Walk(std::get<std::list<StatOrErrmsg>>(x.t), ", ");
    Put(')'), Walk(" ", std::get<std::optional<Name>>(x.t));
  }
  void Unparse(const CriticalStmt &x) { // R1117
    Walk(std::get<std::optional<Name>>(x.t), ": ");
    Word("CRITICAL ("), Walk(std::get<std::list<StatOrErrmsg>>(x.t), ", ");
    Put(')'), Indent();
  }
  void Unparse(const EndCriticalStmt &x) { // R1118
    Outdent(), Word("END CRITICAL"), Walk(" ", x.v);
  }
  void Unparse(const DoConstruct &x) { // R1119, R1120
    Walk(std::get<Statement<NonLabelDoStmt>>(x.t));
    Indent(), Walk(std::get<Block>(x.t), ""), Outdent();
    Walk(std::get<Statement<EndDoStmt>>(x.t));
  }
  void Unparse(const LabelDoStmt &x) { // R1121
    Walk(std::get<std::optional<Name>>(x.t), ": ");
    Word("DO "), Walk(std::get<Label>(x.t));
    Walk(" ", std::get<std::optional<LoopControl>>(x.t));
  }
  void Unparse(const NonLabelDoStmt &x) { // R1122
    Walk(std::get<std::optional<Name>>(x.t), ": ");
    Word("DO "), Walk(std::get<std::optional<LoopControl>>(x.t));
  }
  void Unparse(const LoopControl &x) { // R1123
    std::visit(common::visitors{
                   [&](const ScalarLogicalExpr &y) {
                     Word("WHILE ("), Walk(y), Put(')');
                   },
                   [&](const auto &y) { Walk(y); },
               },
        x.u);
  }
  void Unparse(const ConcurrentHeader &x) { // R1125
    Put('('), Walk(std::get<std::optional<IntegerTypeSpec>>(x.t), "::");
    Walk(std::get<std::list<ConcurrentControl>>(x.t), ", ");
    Walk(", ", std::get<std::optional<ScalarLogicalExpr>>(x.t)), Put(')');
  }
  void Unparse(const ConcurrentControl &x) { // R1126 - R1128
    Walk(std::get<Name>(x.t)), Put('='), Walk(std::get<1>(x.t));
    Put(':'), Walk(std::get<2>(x.t));
    Walk(":", std::get<std::optional<ScalarIntExpr>>(x.t));
  }
  void Before(const LoopControl::Concurrent &) { // R1129
    Word("CONCURRENT");
  }
  void Unparse(const LocalitySpec::Local &x) {
    Word("LOCAL("), Walk(x.v, ", "), Put(')');
  }
  void Unparse(const LocalitySpec::LocalInit &x) {
    Word("LOCAL_INIT("), Walk(x.v, ", "), Put(')');
  }
  void Unparse(const LocalitySpec::Shared &x) {
    Word("SHARED("), Walk(x.v, ", "), Put(')');
  }
  void Post(const LocalitySpec::DefaultNone &) { Word("DEFAULT(NONE)"); }
  void Unparse(const EndDoStmt &x) { // R1132
    Word("END DO"), Walk(" ", x.v);
  }
  void Unparse(const CycleStmt &x) { // R1133
    Word("CYCLE"), Walk(" ", x.v);
  }
  void Unparse(const IfThenStmt &x) { // R1135
    Walk(std::get<std::optional<Name>>(x.t), ": ");
    Word("IF ("), Walk(std::get<ScalarLogicalExpr>(x.t));
    Put(") "), Word("THEN"), Indent();
  }
  void Unparse(const ElseIfStmt &x) { // R1136
    Outdent(), Word("ELSE IF (");
    Walk(std::get<ScalarLogicalExpr>(x.t)), Put(") "), Word("THEN");
    Walk(" ", std::get<std::optional<Name>>(x.t)), Indent();
  }
  void Unparse(const ElseStmt &x) { // R1137
    Outdent(), Word("ELSE"), Walk(" ", x.v), Indent();
  }
  void Unparse(const EndIfStmt &x) { // R1138
    Outdent(), Word("END IF"), Walk(" ", x.v);
  }
  void Unparse(const IfStmt &x) { // R1139
    Word("IF ("), Walk(x.t, ") ");
  }
  void Unparse(const SelectCaseStmt &x) { // R1141, R1144
    Walk(std::get<std::optional<Name>>(x.t), ": ");
    Word("SELECT CASE (");
    Walk(std::get<Scalar<Expr>>(x.t)), Put(')'), Indent();
  }
  void Unparse(const CaseStmt &x) { // R1142
    Outdent(), Word("CASE "), Walk(std::get<CaseSelector>(x.t));
    Walk(" ", std::get<std::optional<Name>>(x.t)), Indent();
  }
  void Unparse(const EndSelectStmt &x) { // R1143 & R1151 & R1155
    Outdent(), Word("END SELECT"), Walk(" ", x.v);
  }
  void Unparse(const CaseSelector &x) { // R1145
    std::visit(common::visitors{
                   [&](const std::list<CaseValueRange> &y) {
                     Put('('), Walk(y), Put(')');
                   },
                   [&](const Default &) { Word("DEFAULT"); },
               },
        x.u);
  }
  void Unparse(const CaseValueRange::Range &x) { // R1146
    Walk(x.lower), Put(':'), Walk(x.upper);
  }
  void Unparse(const SelectRankStmt &x) { // R1149
    Walk(std::get<0>(x.t), ": ");
    Word("SELECT RANK ("), Walk(std::get<1>(x.t), " => ");
    Walk(std::get<Selector>(x.t)), Put(')'), Indent();
  }
  void Unparse(const SelectRankCaseStmt &x) { // R1150
    Outdent(), Word("RANK ");
    std::visit(common::visitors{
                   [&](const ScalarIntConstantExpr &y) {
                     Put('('), Walk(y), Put(')');
                   },
                   [&](const Star &) { Put("(*)"); },
                   [&](const Default &) { Word("DEFAULT"); },
               },
        std::get<SelectRankCaseStmt::Rank>(x.t).u);
    Walk(" ", std::get<std::optional<Name>>(x.t)), Indent();
  }
  void Unparse(const SelectTypeStmt &x) { // R1153
    Walk(std::get<0>(x.t), ": ");
    Word("SELECT TYPE ("), Walk(std::get<1>(x.t), " => ");
    Walk(std::get<Selector>(x.t)), Put(')'), Indent();
  }
  void Unparse(const TypeGuardStmt &x) { // R1154
    Outdent(), Walk(std::get<TypeGuardStmt::Guard>(x.t));
    Walk(" ", std::get<std::optional<Name>>(x.t)), Indent();
  }
  void Unparse(const TypeGuardStmt::Guard &x) {
    std::visit(
        common::visitors{
            [&](const TypeSpec &y) { Word("TYPE IS ("), Walk(y), Put(')'); },
            [&](const DerivedTypeSpec &y) {
              Word("CLASS IS ("), Walk(y), Put(')');
            },
            [&](const Default &) { Word("CLASS DEFAULT"); },
        },
        x.u);
  }
  void Unparse(const ExitStmt &x) { // R1156
    Word("EXIT"), Walk(" ", x.v);
  }
  void Before(const GotoStmt &) { // R1157
    Word("GO TO ");
  }
  void Unparse(const ComputedGotoStmt &x) { // R1158
    Word("GO TO ("), Walk(x.t, "), ");
  }
  void Unparse(const ContinueStmt &) { // R1159
    Word("CONTINUE");
  }
  void Unparse(const StopStmt &x) { // R1160, R1161
    if (std::get<StopStmt::Kind>(x.t) == StopStmt::Kind::ErrorStop) {
      Word("ERROR ");
    }
    Word("STOP"), Walk(" ", std::get<std::optional<StopCode>>(x.t));
    Walk(", QUIET=", std::get<std::optional<ScalarLogicalExpr>>(x.t));
  }
  void Unparse(const FailImageStmt &) { // R1163
    Word("FAIL IMAGE");
  }
  void Unparse(const SyncAllStmt &x) { // R1164
    Word("SYNC ALL ("), Walk(x.v, ", "), Put(')');
  }
  void Unparse(const SyncImagesStmt &x) { // R1166
    Word("SYNC IMAGES (");
    Walk(std::get<SyncImagesStmt::ImageSet>(x.t));
    Walk(", ", std::get<std::list<StatOrErrmsg>>(x.t), ", "), Put(')');
  }
  void Unparse(const SyncMemoryStmt &x) { // R1168
    Word("SYNC MEMORY ("), Walk(x.v, ", "), Put(')');
  }
  void Unparse(const SyncTeamStmt &x) { // R1169
    Word("SYNC TEAM ("), Walk(std::get<TeamValue>(x.t));
    Walk(", ", std::get<std::list<StatOrErrmsg>>(x.t), ", "), Put(')');
  }
  void Unparse(const EventPostStmt &x) { // R1170
    Word("EVENT POST ("), Walk(std::get<EventVariable>(x.t));
    Walk(", ", std::get<std::list<StatOrErrmsg>>(x.t), ", "), Put(')');
  }
  void Before(const EventWaitStmt::EventWaitSpec &x) { // R1173, R1174
    std::visit(common::visitors{
                   [&](const ScalarIntExpr &) { Word("UNTIL_COUNT="); },
                   [](const StatOrErrmsg &) {},
               },
        x.u);
  }
  void Unparse(const EventWaitStmt &x) { // R1170
    Word("EVENT WAIT ("), Walk(std::get<EventVariable>(x.t));
    Walk(", ", std::get<std::list<EventWaitStmt::EventWaitSpec>>(x.t), ", ");
    Put(')');
  }
  void Unparse(const FormTeamStmt &x) { // R1175, R1177
    Word("FORM TEAM ("), Walk(std::get<ScalarIntExpr>(x.t));
    Put(','), Walk(std::get<TeamVariable>(x.t));
    Walk(", ", std::get<std::list<FormTeamStmt::FormTeamSpec>>(x.t), ", ");
    Put(')');
  }
  void Before(const FormTeamStmt::FormTeamSpec &x) { // R1176, R1178
    std::visit(common::visitors{
                   [&](const ScalarIntExpr &) { Word("NEW_INDEX="); },
                   [](const StatOrErrmsg &) {},
               },
        x.u);
  }
  void Unparse(const LockStmt &x) { // R1179
    Word("LOCK ("), Walk(std::get<LockVariable>(x.t));
    Walk(", ", std::get<std::list<LockStmt::LockStat>>(x.t), ", ");
    Put(')');
  }
  void Before(const LockStmt::LockStat &x) { // R1180
    std::visit(
        common::visitors{
            [&](const ScalarLogicalVariable &) { Word("ACQUIRED_LOCK="); },
            [](const StatOrErrmsg &) {},
        },
        x.u);
  }
  void Unparse(const UnlockStmt &x) { // R1181
    Word("UNLOCK ("), Walk(std::get<LockVariable>(x.t));
    Walk(", ", std::get<std::list<StatOrErrmsg>>(x.t), ", ");
    Put(')');
  }

  void Unparse(const OpenStmt &x) { // R1204
    Word("OPEN ("), Walk(x.v, ", "), Put(')');
  }
  bool Pre(const ConnectSpec &x) { // R1205
    return std::visit(common::visitors{
                          [&](const FileUnitNumber &) {
                            Word("UNIT=");
                            return true;
                          },
                          [&](const FileNameExpr &) {
                            Word("FILE=");
                            return true;
                          },
                          [&](const ConnectSpec::CharExpr &y) {
                            Walk(y.t, "=");
                            return false;
                          },
                          [&](const MsgVariable &) {
                            Word("IOMSG=");
                            return true;
                          },
                          [&](const StatVariable &) {
                            Word("IOSTAT=");
                            return true;
                          },
                          [&](const ConnectSpec::Recl &) {
                            Word("RECL=");
                            return true;
                          },
                          [&](const ConnectSpec::Newunit &) {
                            Word("NEWUNIT=");
                            return true;
                          },
                          [&](const ErrLabel &) {
                            Word("ERR=");
                            return true;
                          },
                          [&](const StatusExpr &) {
                            Word("STATUS=");
                            return true;
                          },
                      },
        x.u);
  }
  void Unparse(const CloseStmt &x) { // R1208
    Word("CLOSE ("), Walk(x.v, ", "), Put(')');
  }
  void Before(const CloseStmt::CloseSpec &x) { // R1209
    std::visit(common::visitors{
                   [&](const FileUnitNumber &) { Word("UNIT="); },
                   [&](const StatVariable &) { Word("IOSTAT="); },
                   [&](const MsgVariable &) { Word("IOMSG="); },
                   [&](const ErrLabel &) { Word("ERR="); },
                   [&](const StatusExpr &) { Word("STATUS="); },
               },
        x.u);
  }
  void Unparse(const ReadStmt &x) { // R1210
    Word("READ ");
    if (x.iounit) {
      Put('('), Walk(x.iounit);
      if (x.format) {
        Put(", "), Walk(x.format);
      }
      Walk(", ", x.controls, ", ");
      Put(')');
    } else if (x.format) {
      Walk(x.format);
      if (!x.items.empty()) {
        Put(", ");
      }
    } else {
      Put('('), Walk(x.controls, ", "), Put(')');
    }
    Walk(" ", x.items, ", ");
  }
  void Unparse(const WriteStmt &x) { // R1211
    Word("WRITE (");
    if (x.iounit) {
      Walk(x.iounit);
      if (x.format) {
        Put(", "), Walk(x.format);
      }
      Walk(", ", x.controls, ", ");
    } else {
      Walk(x.controls, ", ");
    }
    Put(')'), Walk(" ", x.items, ", ");
  }
  void Unparse(const PrintStmt &x) { // R1212
    Word("PRINT "), Walk(std::get<Format>(x.t));
    Walk(", ", std::get<std::list<OutputItem>>(x.t), ", ");
  }
  bool Pre(const IoControlSpec &x) { // R1213
    return std::visit(common::visitors{
                          [&](const IoUnit &) {
                            Word("UNIT=");
                            return true;
                          },
                          [&](const Format &) {
                            Word("FMT=");
                            return true;
                          },
                          [&](const Name &) {
                            Word("NML=");
                            return true;
                          },
                          [&](const IoControlSpec::CharExpr &y) {
                            Walk(y.t, "=");
                            return false;
                          },
                          [&](const IoControlSpec::Asynchronous &) {
                            Word("ASYNCHRONOUS=");
                            return true;
                          },
                          [&](const EndLabel &) {
                            Word("END=");
                            return true;
                          },
                          [&](const EorLabel &) {
                            Word("EOR=");
                            return true;
                          },
                          [&](const ErrLabel &) {
                            Word("ERR=");
                            return true;
                          },
                          [&](const IdVariable &) {
                            Word("ID=");
                            return true;
                          },
                          [&](const MsgVariable &) {
                            Word("IOMSG=");
                            return true;
                          },
                          [&](const StatVariable &) {
                            Word("IOSTAT=");
                            return true;
                          },
                          [&](const IoControlSpec::Pos &) {
                            Word("POS=");
                            return true;
                          },
                          [&](const IoControlSpec::Rec &) {
                            Word("REC=");
                            return true;
                          },
                          [&](const IoControlSpec::Size &) {
                            Word("SIZE=");
                            return true;
                          },
                      },
        x.u);
  }
  void Unparse(const InputImpliedDo &x) { // R1218
    Put('('), Walk(std::get<std::list<InputItem>>(x.t), ", "), Put(", ");
    Walk(std::get<IoImpliedDoControl>(x.t)), Put(')');
  }
  void Unparse(const OutputImpliedDo &x) { // R1219
    Put('('), Walk(std::get<std::list<OutputItem>>(x.t), ", "), Put(", ");
    Walk(std::get<IoImpliedDoControl>(x.t)), Put(')');
  }
  void Unparse(const WaitStmt &x) { // R1222
    Word("WAIT ("), Walk(x.v, ", "), Put(')');
  }
  void Before(const WaitSpec &x) { // R1223
    std::visit(common::visitors{
                   [&](const FileUnitNumber &) { Word("UNIT="); },
                   [&](const EndLabel &) { Word("END="); },
                   [&](const EorLabel &) { Word("EOR="); },
                   [&](const ErrLabel &) { Word("ERR="); },
                   [&](const IdExpr &) { Word("ID="); },
                   [&](const MsgVariable &) { Word("IOMSG="); },
                   [&](const StatVariable &) { Word("IOSTAT="); },
               },
        x.u);
  }
  void Unparse(const BackspaceStmt &x) { // R1224
    Word("BACKSPACE ("), Walk(x.v, ", "), Put(')');
  }
  void Unparse(const EndfileStmt &x) { // R1225
    Word("ENDFILE ("), Walk(x.v, ", "), Put(')');
  }
  void Unparse(const RewindStmt &x) { // R1226
    Word("REWIND ("), Walk(x.v, ", "), Put(')');
  }
  void Before(const PositionOrFlushSpec &x) { // R1227 & R1229
    std::visit(common::visitors{
                   [&](const FileUnitNumber &) { Word("UNIT="); },
                   [&](const MsgVariable &) { Word("IOMSG="); },
                   [&](const StatVariable &) { Word("IOSTAT="); },
                   [&](const ErrLabel &) { Word("ERR="); },
               },
        x.u);
  }
  void Unparse(const FlushStmt &x) { // R1228
    Word("FLUSH ("), Walk(x.v, ", "), Put(')');
  }
  void Unparse(const InquireStmt &x) { // R1230
    Word("INQUIRE (");
    std::visit(
        common::visitors{
            [&](const InquireStmt::Iolength &y) {
              Word("IOLENGTH="), Walk(y.t, ") ");
            },
            [&](const std::list<InquireSpec> &y) { Walk(y, ", "), Put(')'); },
        },
        x.u);
  }
  bool Pre(const InquireSpec &x) { // R1231
    return std::visit(common::visitors{
                          [&](const FileUnitNumber &) {
                            Word("UNIT=");
                            return true;
                          },
                          [&](const FileNameExpr &) {
                            Word("FILE=");
                            return true;
                          },
                          [&](const InquireSpec::CharVar &y) {
                            Walk(y.t, "=");
                            return false;
                          },
                          [&](const InquireSpec::IntVar &y) {
                            Walk(y.t, "=");
                            return false;
                          },
                          [&](const InquireSpec::LogVar &y) {
                            Walk(y.t, "=");
                            return false;
                          },
                          [&](const IdExpr &) {
                            Word("ID=");
                            return true;
                          },
                          [&](const ErrLabel &) {
                            Word("ERR=");
                            return true;
                          },
                      },
        x.u);
  }

  void Before(const FormatStmt &) { // R1301
    Word("FORMAT");
  }
  void Unparse(const format::FormatSpecification &x) { // R1302, R1303, R1305
    Put('('), Walk("", x.items, ",", x.unlimitedItems.empty() ? "" : ",");
    Walk("*(", x.unlimitedItems, ",", ")"), Put(')');
  }
  void Unparse(const format::FormatItem &x) { // R1304, R1306, R1321
    if (x.repeatCount) {
      Walk(*x.repeatCount);
    }
    std::visit(common::visitors{
                   [&](const std::string &y) { PutNormalized(y); },
                   [&](const std::list<format::FormatItem> &y) {
                     Walk("(", y, ",", ")");
                   },
                   [&](const auto &y) { Walk(y); },
               },
        x.u);
  }
  void Unparse(
      const format::IntrinsicTypeDataEditDesc &x) { // R1307(1/2) - R1311
    switch (x.kind) {
#define FMT(x) \
  case format::IntrinsicTypeDataEditDesc::Kind::x: \
    Put(#x); \
    break
      FMT(I);
      FMT(B);
      FMT(O);
      FMT(Z);
      FMT(F);
      FMT(E);
      FMT(EN);
      FMT(ES);
      FMT(EX);
      FMT(G);
      FMT(L);
      FMT(A);
      FMT(D);
#undef FMT
    }
    Walk(x.width), Walk(".", x.digits), Walk("E", x.exponentWidth);
  }
  void Unparse(const format::DerivedTypeDataEditDesc &x) { // R1307(2/2), R1312
    Word("DT");
    if (!x.type.empty()) {
      Put('"'), Put(x.type), Put('"');
    }
    Walk("(", x.parameters, ",", ")");
  }
  void Unparse(const format::ControlEditDesc &x) { // R1313, R1315-R1320
    switch (x.kind) {
    case format::ControlEditDesc::Kind::T:
      Word("T");
      Walk(x.count);
      break;
    case format::ControlEditDesc::Kind::TL:
      Word("TL");
      Walk(x.count);
      break;
    case format::ControlEditDesc::Kind::TR:
      Word("TR");
      Walk(x.count);
      break;
    case format::ControlEditDesc::Kind::X:
      if (x.count != 1) {
        Walk(x.count);
      }
      Word("X");
      break;
    case format::ControlEditDesc::Kind::Slash:
      if (x.count != 1) {
        Walk(x.count);
      }
      Put('/');
      break;
    case format::ControlEditDesc::Kind::Colon:
      Put(':');
      break;
    case format::ControlEditDesc::Kind::P:
      Walk(x.count);
      Word("P");
      break;
#define FMT(x) \
  case format::ControlEditDesc::Kind::x: \
    Put(#x); \
    break
      FMT(SS);
      FMT(SP);
      FMT(S);
      FMT(BN);
      FMT(BZ);
      FMT(RU);
      FMT(RD);
      FMT(RZ);
      FMT(RN);
      FMT(RC);
      FMT(RP);
      FMT(DC);
      FMT(DP);
#undef FMT
    case format::ControlEditDesc::Kind::Dollar:
      Put('$');
      break;
    case format::ControlEditDesc::Kind::Backslash:
      Put('\\');
      break;
    }
  }

  void Before(const MainProgram &x) { // R1401
    if (!std::get<std::optional<Statement<ProgramStmt>>>(x.t)) {
      Indent();
    }
  }
  void Before(const ProgramStmt &) { // R1402
    Word("PROGRAM "), Indent();
  }
  void Unparse(const EndProgramStmt &x) { // R1403
    EndSubprogram("PROGRAM", x.v);
  }
  void Before(const ModuleStmt &) { // R1405
    Word("MODULE "), Indent();
  }