summaryrefslogtreecommitdiffstats
path: root/javatoscachecker/kwalify/src/main/java/kwalify/PlainYamlParser.java
blob: f23146bfeac8c96c2a381b70c52835965c13386c (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
/*
 * The original version of this file was provided under the MIT license,
 * as follows:
 *
 * @(#)PlainYamlParser.java	$Rev: 4 $ $Release: 0.5.1 $
 *
 * Copyright (c) <2005> <kuwata lab>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * Modifications to this file are provided under the Apache 2.0 license,
 * as follows:

 * Copyright (c) 2017 <AT&T>.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations 
 * under the License.
 */

package kwalify;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * plain yaml parser class which is a parent of YamlParser class.
 *
 * ex.
 * <pre>
 *  String str = kwalify.Util.readFile("document.yaml");
 *  kwalify.Parser parser = new kwalify.PlainYamlParser(str);
 *  Object doc = parser.parse();
 * </pre>
 *
 * @revision    $Rev: 4 $
 * @release     $Release: 0.5.1 $
 */
public class PlainYamlParser implements Parser {

    public static class Alias {
        private String _label;
        private int    _linenum;

        public Alias(String label, int linenum) {
            _label   = label;
            _linenum = linenum;
        }

        public String getLabel() { return _label; }
        public void setLabel(String label) { _label = label; }

        public int getLineNumber() { return _linenum; }
        public void setLineNumber(int linenum) { _linenum = linenum; }
    }


    private String[] _lines;
    private String _line = null;
    private int _linenum = 0;
    private Map _anchors = new HashMap();
    private Map _aliases = new HashMap();   // key: label, value: Integer
    private Object _end_flag = null;
    private String _sbuf = null;
    private int _index = 0;

    public PlainYamlParser(String yaml_str) {
        // split yaml_str into _lines
        List list = Util.toListOfLines(yaml_str);
        int len = list.size();
        _lines = new String[len + 1];
        for (int i = 0; i < len; i++) {
            _lines[i + 1] = (String)list.get(i);
        }
    }

    public Object parse() throws SyntaxException {
        Object data = parseChild(0);
        if (data == null && _end_flag == ENDFLAG_DOC_BEGIN) {
            data = parseChild(0);
        }
        if (_aliases.size() > 0) {
            resolveAliases(data);
        }
        //System.err.println("*** debug: data = " + Util.inspect(data));
        //System.err.println("*** debug: data = " + data.toString());
        return data;
    }

    public boolean hasNext() {
        return _end_flag != ENDFLAG_EOF;
    }

    public Object[] parseAll() throws SyntaxException {
        List docs = new ArrayList();
        while (hasNext()) {
            Object doc = parse();
            docs.add(doc);
        }
        return docs.toArray();
    }


    protected List createSequence(int linenum) {
        return new ArrayList();
    }

    //private List createSequence() {
    //    return createSequence(_linenum);
    //}

    protected void addSequenceValue(List seq, Object value, int linenum) {
        seq.add(value);
    }

    protected void setSequenceValueAt(List seq, int index, Object value, int linenum) {
        seq.set(index, value);
    }

    protected Map createMapping(int linenum) {
        return new DefaultableHashMap();
    }

    //private Map createMapping() {
    //    return createMapping(_linenum);
    //}

    protected void setMappingValueWith(Map map, Object key, Object value, int linenum) {
        map.put(key, value);
    }

    protected void setMappingDefault(Map map, Object value, int linenum) {
        if (map instanceof Defaultable) {
            ((Defaultable)map).setDefault(value);
        }
    }

    protected void mergeMapping(Map map, Map map2, int linenum) {
        for (Iterator it = map2.keySet().iterator(); it.hasNext(); ) {
            Object key = it.next();
            if (! map.containsKey(key)) {
                Object value = map2.get(key);
                map.put(key, value);
            }
        }
    }

    protected void mergeList(Map map, List maplist, int linenum) throws SyntaxException {
        for (Iterator it = maplist.iterator(); it.hasNext(); ) {
            Object elem = it.next();
            mergeCollection(map, elem, linenum);
        }
    }

    protected void mergeCollection(Map map, Object collection, int linenum) throws SyntaxException {
        if (collection instanceof Map) {
            mergeMapping(map, (Map)collection, linenum);
        } else if (collection instanceof List) {
            mergeList(map, (List)collection, linenum);
        } else {
            throw syntaxError("'<<' requires collection (mapping, or sequence of mapping).");
        }
    }

    protected Object createScalar(Object value, int linenum) {
        return value;
    }

    private Object createScalar(Object value) {
        return createScalar(value, _linenum);
    }

    protected String currentLine() {
        return _line;
    }

    protected int currentLineNumber() {
        return _linenum;
    }

    protected String getLine() {
        String line;
        do {
            line = _getLine_();
        } while (line != null && Util.matches(line, "^\\s*($|#)"));
        return line;
    }

    protected String _getLine_() {
        if (++_linenum < _lines.length) {
            _line = _lines[_linenum];
            if (Util.matches(_line, "^\\.\\.\\.$")) {
                _line = null;
                _end_flag = ENDFLAG_DOC_END;
            } else if (Util.matches(_line, "^---( [!%].*)?$")) {
                _line = null;
                _end_flag = ENDFLAG_DOC_BEGIN;
            }
        } else {
            _line = null;
            _end_flag = ENDFLAG_EOF;
        }
        return _line;
    }

    protected static final String ENDFLAG_EOF       = "<EOF>";
    protected static final String ENDFLAG_DOC_BEGIN = "---";
    protected static final String ENDFLAG_DOC_END   = "...";

    private void resetBuffer(String str) {
        _sbuf = str.charAt(str.length() - 1) == '\n' ? str : str + "\n";
        _index = -1;
    }


    private int _getChar_() {
        if (_index + 1 < _sbuf.length()) {
            _index++;
        } else {
            String line = getLine();
            if (line == null) return -1;
            resetBuffer(line);
            _index++;
        }
        int ch = _sbuf.charAt(_index);
        return ch;
    }

    private int getChar() {
        int ch;
        do {
            ch = _getChar_();
        } while (ch >= 0 && isWhite(ch));
        return ch;
    }

    private int getCharOrNewline() {
        int ch;
        do {
            ch = _getChar_();
        } while (ch >= 0 && isWhite(ch) && ch != '\n');
        return ch;
    }

    private int currentChar() {
        return _sbuf.charAt(_index);
    }

    private SyntaxException syntaxError(String message, int linenum) {
        return new YamlSyntaxException(message, linenum);
    }

    private SyntaxException syntaxError(String message) {
        return new SyntaxException(message, _linenum);
    }

    private Object parseChild(int column) throws SyntaxException {
        String line = getLine();
        if (line == null) {
            return createScalar(null);
        }
        Matcher m = Util.matcher(line, "^( *)(.*)");
        if (! m.find()) {
            assert false;
            return null;
        }
        int indent = m.group(1).length();
        if (indent < column) {
            return createScalar(null);
        }
        String value = m.group(2);
        return parseValue(column, value, indent);
    }

    private Object parseValue(int column, String value, int value_start_column) throws SyntaxException {
        Object data;
        if        (Util.matches(value, "^-( |$)")) {
            data = parseSequence(value_start_column, value);
        } else if (Util.matches(value, "^((?::?[-.\\w]+|'.*?'|\".*?\"|=|<<) *):(( +)(.*))?$")) {
            data = parseMapping(value_start_column, value);
        } else if (Util.matches(value, "^[\\[\\{]")) {
            data = parseFlowStyle(column, value);
        } else if (Util.matches(value, "^\\&[-\\w]+( |$)")) {
            data = parseAnchor(column, value);
        } else if (Util.matches(value, "^\\*[-\\w]+( |$)")) {
            data = parseAlias(column, value);
        } else if (Util.matches(value, "^[|>]")) {
            data = parseBlockText(column, value);
        } else if (Util.matches(value, "^!")) {
            data = parseTag(column, value);
        } else if (Util.matches(value, "^\\#")) {
            data = parseChild(column);
        } else {
            data = parseScalar(column, value);
        }
        return data;
    }

    private static boolean isWhite(int ch) {
        return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
    }


    private Object parseFlowStyle(int column, String value) throws SyntaxException {
        resetBuffer(value);
        getChar();
        Object data = parseFlow(0);
        int ch = currentChar();
        assert ch == ']' || ch == '}';
        ch = getCharOrNewline();
        if (ch != '\n' && ch != '#' && ch >= 0) {
            throw syntaxError("flow style sequence is closed buf got '" + ((char)ch) + "'.");
        }
        if (ch >= 0) getLine();
        return data;
    }

    private Object parseFlow(int depth) throws SyntaxException {
        int ch = currentChar();
        //ch = getChar();
        if (ch < 0) {
            throw syntaxError("found EOF when parsing flow style.");
        }
        Object data;
        if (ch == '[') {
            data = parseFlowSequence(depth);
        } else if (ch == '{') {
            data = parseFlowMapping(depth);
        } else {
            data = parseFlowScalar(depth);
        }
        return data;
    }

    private List parseFlowSequence(int depth) throws SyntaxException {
        assert currentChar() == '[';
        List seq = createSequence(_linenum);
        int ch = getChar();
        if (ch != '}') {
            int linenum = currentLineNumber();
            //seq.add(parseFlowSequenceItem(depth+1);
            addSequenceValue(seq, parseFlowSequenceItem(depth + 1), linenum);
            while ((ch = currentChar()) == ',') {
                ch = getChar();
                if (ch == '}') {
                    throw syntaxError("sequence item required (or last comma is extra).");
                }
                //if (ch == '?') break;
                linenum = currentLineNumber();
                //seq.add(parseFlowSequenceItem(depth+1);
                addSequenceValue(seq, parseFlowSequenceItem(depth + 1), linenum);
            }
        }
        if (currentChar() != ']') {
            throw syntaxError("flow style sequence requires ']'.");
        }
        if (depth > 0) getChar();
        return seq;
    }

    private Object parseFlowSequenceItem(int depth) throws SyntaxException {
        return parseFlow(depth);
    }

    private Map parseFlowMapping(int depth) throws SyntaxException {
        assert currentChar() == '{';
        Map map = createMapping(_linenum);
        int ch = getChar();
        if (ch != '}') {
            int linenum = currentLineNumber();
            Object[] pair = parseFlowMappingItem(depth + 1);
            Object key   = pair[0];
            Object value = pair[1];
            //map[ke] = value
            setMappingValueWith(map, key, value, linenum);
            while ((ch = currentChar()) == ',') {
                ch = getChar();
                if (ch == '}') {
                    throw syntaxError("mapping item required (or last comman is extra.");
                }
                //if (ch == '}') break;
                linenum = currentLineNumber();
                pair = parseFlowMappingItem(depth + 1);
                key   = pair[0];
                value = pair[1];
                //map.put(key) = value;
                setMappingValueWith(map, key, value, linenum);
            }
        }
        if (currentChar() != '}') {
            throw syntaxError("flow style mapping requires '}'.");
        }
        if (depth > 0) getChar();
        return map;
    }

    private Object[] parseFlowMappingItem(int depth) throws SyntaxException {
        Object key = parseFlow(depth);
        int ch = currentChar();
        if (ch != ':') {
            String s = ch >= 0 ? "'" + ((char)ch) + "'" : "EOF";
            throw syntaxError("':' expected but got " + s);
        }
        getChar();
        Object value = parseFlow(depth);
        return new Object[] { key, value };
    }

    private Object parseFlowScalar(int depth) throws SyntaxException {
        int ch = currentChar();
        Object scalar = null;
        StringBuffer sb = new StringBuffer();
        if (ch == '"' || ch == '\'') {
            int endch = ch;
            while ((ch = _getChar_()) >= 0 && ch != endch) {
                sb.append((char)ch);
            }
            getChar();
            scalar = sb.toString();
        } else {
            sb.append((char)ch);
            while ((ch = _getChar_()) >= 0 && ch != ':' && ch != ',' && ch != ']' && ch != '}') {
                sb.append((char)ch);
            }
            scalar = toScalar(sb.toString().trim());
        }
        return createScalar(scalar);
    }

    private Object parseTag(int column, String value) throws SyntaxException {
        assert Util.matches(value, "^!\\S+");
        Matcher m = Util.matcher(value, "^!(\\S+)((\\s+)(.*))?$");
        if (! m.find()) {
            assert false;
            return null;
        }
        String tag = m.group(1);
        String space = m.group(3);
        String value2 = m.group(4);
        Object data;
        if (value2 != null && value2.length() > 0) {
            int value_start_column = column + 1 + tag.length() + space.length();
            data = parseValue(column, value2, value_start_column);
        } else {
            data = parseChild(column);
        }
        return data;
    }

    private Object parseAnchor(int column, String value) throws SyntaxException {
        assert Util.matches(value, "^\\&([-\\w]+)(( *)(.*))?$");
        Matcher m = Util.matcher(value, "^\\&([-\\w]+)(( *)(.*))?$");
        if (! m.find()) {
            assert false;
            return null;
        }
        String label  = m.group(1);
        String space  = m.group(3);
        String value2 = m.group(4);
        Object data;
        if (value2 != null && value2.length() > 0) {
            int value_start_column = column + 1 + label.length() + space.length();
            data = parseValue(column, value2, value_start_column);
        } else {
            data = parseChild(column);
        }
        registerAnchor(label, data);
        return data;
    }

    private void registerAnchor(String label, Object data) throws SyntaxException {
        if (_anchors.containsKey(label)) {
            throw syntaxError("anchor '" + label + "' is already used.");
        }
        _anchors.put(label, data);
    }

    private Object parseAlias(int column, String value) throws SyntaxException {
        assert value.matches("^\\*([-\\w]+)(( *)(.*))?$");
        Matcher m = Util.matcher(value, "^\\*([-\\w]+)(( *)(.*))?$");
        if (! m.find()) {
            assert false;
            return null;
        }
        String label  = m.group(1);
        //String space  = m.group(3);
        String value2 = m.group(4);
        if (value2 != null && value2.length() > 0 && value2.charAt(0) != '#') {
            throw syntaxError("alias cannot take any data.");
        }
        Object data = _anchors.get(label);
        if (data == null) {
            //throw syntaxError("anchor '" + label "' not found (cannot refer to backward or child anchor).");
            data = registerAlias(label);
        }
        getLine();
        return data;
    }

    private Alias registerAlias(String label) throws SyntaxException {
        Integer count = (Integer)_aliases.get(label);
        if (count == null) {
            _aliases.put(label, new Integer(1));
        } else {
            _aliases.put(label, new Integer(count.intValue() + 1));
        }
        return new Alias(label, _linenum);
    }


    private void resolveAliases(Object data) throws SyntaxException {  // List or Map
        Map resolved = new IdentityHashMap();
        resolveAliases(data, resolved);
    }


    private void resolveAliases(Object data, Map resolved) throws SyntaxException {
        if (resolved.containsKey(data)) {
            return;
        }
        resolved.put(data, data);
        if (data instanceof List) {
            resolveAliases((List)data, resolved);
        } else if (data instanceof Map) {
            resolveAliases((Map)data, resolved);
        } else {
            assert !(data instanceof Alias);
        }
        if (data instanceof Defaultable) {
            Object default_value = ((Defaultable)data).getDefault();
            if (default_value != null) {
                resolveAliases(default_value, resolved);
            }
        }
    }

    private void resolveAliases(List seq, Map resolved) throws SyntaxException {
        int len = seq.size();
        for (int i = 0; i < len; i++) {  // don't use itrator not to raise java.util.ConcurrentModificationException
            Object val = seq.get(i);
            if (val instanceof Alias) {
                Alias alias = (Alias)val;
                String label = alias.getLabel();
                if (_anchors.containsKey(label)) {
                    //seq.set(i, _anchors.get(label);
                    setSequenceValueAt(seq, i, _anchors.get(label), alias.getLineNumber());
                } else {
                    throw syntaxError("anchor '" + alias.getLabel() + "' not found.");
                }
            } else if (val instanceof List || val instanceof Map) {
                resolveAliases(val, resolved);
            }
        }
    }

    private void resolveAliases(Map map, Map resolved) throws SyntaxException {
        for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
            Object key = it.next();
            Object val = map.get(key);
            if (val instanceof Alias) {
                Alias alias = (Alias)val;
                String label = alias.getLabel();
                if (_anchors.containsKey(label)) {
                    //map.put(key, _anchors.get(label));
                    setMappingValueWith(map, key, _anchors.get(label), alias.getLineNumber());
                } else {
                    throw syntaxError("anchor '" + alias.getLabel() + "' not found.", alias.getLineNumber());
                }
            } else if (val instanceof List || val instanceof Map) {
                resolveAliases(val, resolved);
            }
        }
    }



/*
    private Object parseBlockText(int column, String value) throws SyntaxException {
        assert Util.matches(value, "^[>|\\|]");
        Matcher m = Util.matcher(value, "^([>|\\|])([-+]?)\\s*(.*)$");
        if (! m.find()) {
            assert false;
            return null;
        }
        String blockchar = m.group(1);
        String indicator = m.group(2);
        String sep = blockchar.equals("|") ? "\n" : " ";
        //String text = m.group(3).length() > 0 ? "" : m.group(3) + sep;
        String text = m.group(3);
        StringBuffer sb = new StringBuffer();
        StringBuffer empty = new StringBuffer();
        int min_indent = -1;
        String line;
        Pattern pat2 = Pattern.compile("^( *)(.*)");
        while ((line = _getLine_()) != null) {
            (m = pat2.matcher(line)).find();
            int indent = m.group(1).length();
            if (m.group(2).length() == 0) {
                empty.append("\n");
            } else if (indent < column) {
                break;
            } else {
                if (min_indent < 0 || min_indent > indent) {
                    min_indent = indent;
                }
                sb.append(empty.toString());
                sb.append(line);
                empty.delete(0, empty.length());
            }
        }
        if (indicator.equals("+")) {
            sb.append(empty);
        } else if (indicator.equals("-")) {
            sb.deleteCharAt(sb.length() - 1);
        }
        String s;
        if (min_indent <= 0) {
            s = sb.toString();
        } else {
            StringBuffer regex = new StringBuffer("(?m)^");
            for (int i = 0; i < min_indent; i++) regex.append(" ");
            s = sb.toString().replaceAll(regex.toString(), "");
        }
        if (blockchar.equals(">")) {
            StringBuffer sb2 = new StringBuffer();
            int len = s.length();
            int n = 0;
            for (int i = 0; i < len; i++) {
                char ch = s.charAt(i);
                if (ch == '\n') {
                    n++;
                } else {
                    if (n == 1) {
                        sb2.append(' ');   n = 0;
                    } else if (n > 1) {
                        sb2.append('\n');  n = 0;
                    }
                    sb2.append(ch);
                }
            }
            s = sb2.toString();
        }
        if (currentLine() != null && Util.matches(currentLine(), "^\\s*#")) getLine();
        return createScalar(text + s);
    }
*/

    private Object parseBlockText(int column, String value) throws SyntaxException {
        assert Util.matches(value, "^[>|]");
        Matcher m = Util.matcher(value, "^([>|])([-+]?)(\\d*)\\s*(.*)$");
        if (! m.find()) {
            assert false;
            return null;
        }
        char blockchar = m.group(1).length() > 0 ? m.group(1).charAt(0) : '\0';
        char indicator = m.group(2).length() > 0 ? m.group(2).charAt(0) : '\0';
        int indent     = m.group(3).length() > 0 ? Integer.parseInt(m.group(3)) : -1;
        String text    = m.group(4);
        char sep = blockchar == '|' ? '\n' : ' ';
        String line;
        StringBuffer sb = new StringBuffer();
        int n = 0;
        while ((line = _getLine_()) != null) {
            m = Util.matcher(line, "^( *)(.*)$");
            m.find();
            String space = m.group(1);
            String str   = m.group(2);
            if (indent < 0) indent = space.length();
            if (str.length() == 0) {   // empty line
                n++;
            } else {
                int slen = space.length();
                if (slen < column) {
                    break;
                } else if (slen < indent) {
                    throw syntaxError("invalid indent in block text.");
                } else {
                    if (n > 0) {
                        if (blockchar == '>' && sb.length() > 0) {
                            sb.deleteCharAt(sb.length() - 1);
                        }
                        for (int i = 0; i < n; i++) {
                            sb.append('\n');
                        }
                        n = 0;
                    }
                    str = line.substring(indent);
                }
            }
            sb.append(str);
            if (blockchar == '>') {
                if (sb.charAt(sb.length() - 1) == '\n') {
                    sb.setCharAt(sb.length() - 1, ' ');
                }
            }
        }
        if (line != null && Util.matches(line, "^ *#")) {
            getLine();
        }
        switch (indicator) {
        case '+':
            if (n > 0) {
                if (blockchar == '>') {
                    sb.setCharAt(sb.length() - 1, '\n');
                }
                for (int i = 0; i < n; i++) {
                    sb.append('\n');
                }
            }
            break;
        case '-':
            if (sb.charAt(sb.length() - 1) == sep) {
                sb.deleteCharAt(sb.length() - 1);
            }
            break;
        default:
            if (blockchar == '>') {
                sb.setCharAt(sb.length() - 1, '\n');
            }
        }
        return createScalar(text + sb.toString());
    }


    private List parseSequence(int column, String value) throws SyntaxException {
        assert Util.matches(value, "^-(( +)(.*))?$");
        List seq = createSequence(_linenum);
        while (true) {
            Matcher m = Util.matcher(value, "^-(( +)(.*))?$");
            if (! m.find()) {
                throw syntaxError("sequence item is expected.");
            }
            String space  = m.group(2);
            String value2 = m.group(3);
            int column2   = column + 1;
            int linenum   = currentLineNumber();
            //
            Object elem;
            if (value2 == null || value2.length() == 0) {
                elem = parseChild(column2);
            } else {
                int value_start_column = column2 + space.length();
                elem = parseValue(column2, value2, value_start_column);
            }
            addSequenceValue(seq, elem, linenum);
            //
            String line = currentLine();
            if (line == null) break;
            Matcher m2 = Util.matcher(line, "^( *)(.*)");
            m2.find();
            int indent = m2.group(1).length();
            if (indent < column) {
                break;
            } else if (indent > column) {
                throw syntaxError("invalid indent of sequence.");
            }
            value = m2.group(2);
        }
        return seq;
    }


    private Map parseMapping(int column, String value) throws SyntaxException {
        assert Util.matches(value, "^((?::?[-.\\w]+|'.*?'|\".*?\"|=|<<) *):(( +)(.*))?$");
        Map map = createMapping(_linenum);
        while (true) {
            Matcher m = Util.matcher(value, "^((?::?[-.\\w]+|'.*?'|\".*?\"|=|<<) *):(( +)(.*))?$");
            if (! m.find()) {
                throw syntaxError("mapping item is expected.");
            }
            String v = m.group(1).trim();
            Object key = toScalar(v);
            String value2 = m.group(4);
            int column2 = column + 1;
            int linenum = currentLineNumber();
            //
            Object elem;
            if (value2 == null || value2.length() == 0) {
                elem = parseChild(column2);
            } else {
                int value_start_column = column2 + m.group(1).length() + m.group(3).length();
                elem = parseValue(column2, value2, value_start_column);
            }
            if (v.equals("=")) {
                setMappingDefault(map, elem, linenum);
            } else if (v.equals("<<")) {
                mergeCollection(map, elem, linenum);
            } else {
                setMappingValueWith(map, key, elem, linenum);
            }
            //
            String line = currentLine();
            if (line == null) {
                break;
            }
            Matcher m2 = Util.matcher(line, "^( *)(.*)");
            m2.find();
            int indent = m2.group(1).length();
            if (indent < column) {
                break;
            } else if (indent > column) {
                throw syntaxError("invalid indent of mapping.");
            }
            value = m2.group(2);
        }
        return map;
    }


    private Object parseScalar(int indent, String value) throws SyntaxException {
        Object data = createScalar(toScalar(value));
        getLine();
        return data;
    }


    private Object toScalar(String value) {
        Matcher m;
        m = Util.matcher(value, "^\"(.*)\"([ \t]*#.*$)?");
        if(m.find()) {
            return m.group(1);
        }

        m = Util.matcher(value, "^'(.*)'([ \t]*#.*$)?");
        if (m.find()) {
            return m.group(1);
        }

        m = Util.matcher(value, "^(.*\\S)[ \t]*#");
        if (m.find()) {
            value = m.group(1);
        }

        if (Util.matches(value, "^-?0x\\d+$"))
            return Integer.valueOf(value, 16);
        else if (Util.matches(value, "^-?0\\d+$"))
            return Integer.valueOf(value, 8);
        else if (Util.matches(value, "^-?\\d+$"))
            return Integer.valueOf(value, 10);
        else if (Util.matches(value, "^-?\\d+\\.\\d+$"))
            return Double.valueOf(value);
        else if (Util.matches(value, "^(true|yes|on)$"))
            return Boolean.TRUE;
        else if (Util.matches(value, "^(false|no|off)$"))
            return Boolean.FALSE;
        else if (Util.matches(value, "^(null|~)$"))
            return null;
        else if (Util.matches(value, "^:(\\w+)$"))
            return value;

        m = Util.matcher(value, "^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$");
        if (m.find()) {
            int year = Integer.parseInt(m.group(1));
            int month = Integer.parseInt(m.group(2));
            int day = Integer.parseInt(m.group(3));
            Calendar cal = Calendar.getInstance();
            cal.set(year, month, day, 0, 0, 0);
            return cal.getTime();
        }

        m = Util.matcher(value, "^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)(?:[Tt]|[ \t]+)(\\d\\d?):(\\d\\d):(\\d\\d)(\\.\\d*)?(?:Z|[ \t]*([-+]\\d\\d?)(?::(\\d\\d))?)?$");
        if (m.find()) {
            int year = Integer.parseInt(m.group(1));
            int month = Integer.parseInt(m.group(2));
            int day = Integer.parseInt(m.group(3));
            int hour = Integer.parseInt(m.group(4));
            int min = Integer.parseInt(m.group(5));
            int sec = Integer.parseInt(m.group(6));
            // int usec = Integer.parseInt(m.group(7));
            // int tzone_h = Integer.parseInt(m.group(8));
            // int tzone_m = Integer.parseInt(m.group(9));
            String timezone = "GMT" + m.group(8) + ":" + m.group(9);
            Calendar cal = Calendar.getInstance();
            cal.set(year, month, day, hour, min, sec);
            cal.setTimeZone(TimeZone.getTimeZone(timezone));
            return cal.getTime();
        }
        return value;
    }

/*
    public static void main(String[] args) throws Exception {
        String filename = args.length > 0 ? args[0] : "test.yaml";
        String s = Util.readFile(filename);
        PlainYamlParser parser = new PlainYamlParser(s);
        while (parser.hasNext()) {
            Object doc = parser.parse();
            System.out.println(Util.inspect(doc));
        }
    }
*/

}