001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.marshall.yaml;
018
019import static org.apache.juneau.commons.lang.StateEnum.*;
020import static org.apache.juneau.commons.utils.CollectionUtils.*;
021import static org.apache.juneau.commons.utils.Shorts.*;
022import static org.apache.juneau.commons.utils.StringUtils.*;
023
024import java.io.*;
025import java.lang.reflect.*;
026import java.util.*;
027
028import org.apache.juneau.commons.bean.*;
029import org.apache.juneau.commons.reflect.*;
030import org.apache.juneau.commons.utils.*;
031import org.apache.juneau.marshall.*;
032import org.apache.juneau.marshall.collections.*;
033import org.apache.juneau.marshall.parser.*;
034import org.apache.juneau.marshall.stream.*;
035import org.apache.juneau.marshall.swap.spi.*;
036
037/**
038 * Session object that lives for the duration of a single use of {@link YamlParser}.
039 *
040 * <h2 class='section'>Notes:</h2><ul>
041 *    <li class='warn'>This class is not thread safe and is typically discarded after one use.
042 * </ul>
043 */
044@SuppressWarnings({
045   "java:S107", // 8 parameters required for YAML scalar handling dispatch
046   "java:S125", // State-machine and parse-path comments are documentation, not commented-out code
047   "java:S135", // Multiple break/continue acceptable for YAML parsing state machines
048   "java:S1168", // handlePlainScalar(), readFlowMapping(), readFlowSequence() and readBlockMappingKey() return null for an empty scalar, null key or the unreachable fall-through, which callers treat as "no value"
049   "java:S1172", // eType, pMeta kept for API consistency with callers
050   "java:S2583", // Conditions look constant to static analysis but depend on parser state mutated by called helpers.
051   "java:S2589", // State checks in error path - analyzer FP on state machine flow
052   "java:S2677", // r.read() return value intentionally ignored when consuming/skipping chars
053   "java:S3626", // Redundant jump acceptable for state machine clarity
054   "java:S3776", // readAnything(), readBlockScalar(), readFlowMapping() and readIntoBeanMapFlow() are branch-heavy dispatches over YAML syntax forms; splitting them would obscure the grammar
055   "java:S6541", // readAnything() and readBlockScalar() are long single-pass dispatches over the YAML scalar/flow/block forms
056   "rawtypes", // Raw Map/Collection/ArrayList are used in readAnything(), handleQuotedScalar() and handlePlainScalar() when instantiating the reflectively resolved target type
057   "resource", // Closeable resources are owned by the caller's parser session; Eclipse JDT @Owning warning is by design.
058   "unchecked", // Casts to T/E and Class<? extends Number> in readAnything(), readFlowSequence(), readBlockSequence() and convertToType() are guarded by the ClassMeta checks on the requested type
059   "unused" // eType/pMeta/keyIndent on the private handleQuotedScalar(), handlePlainScalar() and convertToType() helpers are kept so they share readAnything()'s dispatch signature
060})
061public class YamlParserSession extends ReaderParserSession implements RecordReadable, ArrayRecordReadable {
062
063   /**
064    * Builder class.
065    */
066   public static class Builder extends ReaderParserSession.Builder<Builder> {
067
068      private final YamlParser ctx;
069
070      /**
071       * Constructor
072       *
073       * @param ctx The context creating this session.
074       */
075      protected Builder(YamlParser ctx) {
076         super(ctx);
077         this.ctx = ctx;
078      }
079
080      @Override
081      public YamlParserSession build() {
082         return new YamlParserSession(this);
083      }
084
085   }
086
087   /**
088    * Creates a new builder for this object.
089    *
090    * @param ctx The context creating this session.
091    *    <br>Cannot be <jk>null</jk>.
092    * @return A new builder.
093    */
094   public static Builder create(YamlParser ctx) {
095      return new Builder(ctx);
096   }
097
098   private final YamlParser ctx;
099
100   /**
101    * Constructor.
102    *
103    * @param builder The builder for this object.
104    */
105   protected YamlParserSession(Builder builder) {
106      super(builder);
107      ctx = builder.ctx;
108   }
109
110   @Override /* Overridden from ParserSession */
111   protected <T> T doRead(ParserPipe pipe, ClassMeta<T> type) throws IOException, ParseException, ExecutableException {
112      try (var r = pipe.getParserReader()) {
113         if (r == null)
114            return null;
115         return readAnything(type, r, getOuter(), null);
116      }
117   }
118
119   /**
120    * Opens a whole-value pull-parser cursor over a YAML document, bound to this live session.
121    * {@link RecordReader#read(Class) read(...)} delegates to the polymorphic
122    * {@link ParserSession#read(Object, Class)} entry point.
123    *
124    * @param input The input.
125    * @return A new {@link RecordReader} cursor.
126    * @throws IOException If a problem occurred opening the underlying input.
127    */
128   @Override /* RecordReadable */
129   public RecordReader readRecords(Object input) throws IOException {
130      return RecordAdapter.reader(this, input);
131   }
132
133   /**
134    * Buffered array-element {@link RecordReader} for YAML, bound to this live session.  Calls
135    * {@code parse(input, List.class, Object.class)} once and iterates the result.
136    *
137    * <h4 class='section'>Streaming status:</h4>
138    * <p>
139    * A top-level YAML block sequence ({@code - elem} per line) <i>is</i> forward-readable in
140    * principle, so true element-at-a-time streaming is <b>feasible</b> here (unlike Parquet/BSON).
141    * It is left buffered for now: Juneau's YAML reader is a single hand-written indentation state
142    * machine ({@code readBlockSequence}/{@code readFlowSequence}) whose per-element advance and
143    * dedent bookkeeping are not currently exposed as a pull cursor, and extracting that safely is a
144    * non-trivial parser refactor with real regression surface.  This
145    * is demand-driven &mdash; convert when a large-YAML-array use case justifies the refactor.
146    *
147    * @param input The input.
148    * @return A buffered {@link RecordReader}.
149    * @throws IOException If a problem occurred reading the input.
150    */
151   @Override /* ArrayRecordReadable */
152   public RecordReader readArrayRecords(Object input) throws IOException {
153      return RecordAdapter.arrayReader(this, input);
154   }
155
156   /**
157    * The YAML record cursor is buffered/{@link RecordAdapter}-backed, not O(1) streaming.
158    *
159    * @return Always <jk>false</jk>.
160    */
161   @Override /* RecordReadable */
162   public boolean isRecordStreaming() { return false; }
163
164   /**
165    * The YAML array-record cursor is buffered/{@link RecordAdapter}-backed, not O(1) streaming.
166    *
167    * <p>
168    * Genuine streaming is feasible for YAML block sequences but deferred (demand-driven) pending a
169    * pull-cursor refactor of the indentation state machine; see {@link #readArrayRecords(Object)}.
170    *
171    * @return Always <jk>false</jk>.
172    */
173   @Override /* ArrayRecordReadable */
174   public boolean isArrayRecordStreaming() { return false; }
175
176   @Override /* Overridden from ReaderParserSession */
177   protected <E> Collection<E> doReadIntoCollection(ParserPipe pipe, Collection<E> c, Type elementType) throws IOException, ParseException, ExecutableException {
178      try (var r = pipe.getParserReader()) {
179         skipWhitespaceAndComments(r);
180         int ch = r.peek();
181         if (ch == '[') {
182            readFlowSequence(r, c, getClassMeta(elementType), null);
183         } else {
184            readBlockSequence(r, c, getClassMeta(elementType), null, 0);
185         }
186         return c;
187      }
188   }
189
190   @Override /* Overridden from ReaderParserSession */
191   protected <K,V> Map<K,V> doReadIntoMap(ParserPipe pipe, Map<K,V> m, Type keyType, Type valueType) throws IOException, ParseException, ExecutableException {
192      try (var r = pipe.getParserReader()) {
193         skipWhitespaceAndComments(r);
194         int ch = r.peek();
195         if (ch == '{') {
196            readFlowMapping(r, m, (ClassMeta<K>)getClassMeta(keyType), (ClassMeta<V>)getClassMeta(valueType), null);
197         } else {
198            readBlockMapping(r, m, (ClassMeta<K>)getClassMeta(keyType), (ClassMeta<V>)getClassMeta(valueType), null, 0);
199         }
200         return m;
201      }
202   }
203
204   private <T> T readAnything(ClassMeta<?> eType, ParserReader r, Object outer, BeanPropertyMeta pMeta) throws IOException, ParseException, ExecutableException {
205      enterParseDepth();
206      try {
207         return readAnything0(eType, r, outer, pMeta);
208      } finally {
209         exitParseDepth();
210      }
211   }
212
213   // Workhorse method, wrapped by readAnything() with the recursion-depth guard.
214   private <T> T readAnything0(ClassMeta<?> eType, ParserReader r, Object outer, BeanPropertyMeta pMeta) throws IOException, ParseException, ExecutableException {
215
216      if (eType == null)
217         eType = object();
218      var swap = (ObjectSwap<T,Object>)eType.getSwap(this);
219      var builder = (BuilderSwap<T,Object>)eType.getBuilderSwap(this);
220      ClassMeta<?> sType = null;
221      if (nn(builder))
222         sType = builder.getBuilderClassMeta(this);
223      else if (nn(swap))
224         sType = swap.getSwapClassMeta(this);
225      else
226         sType = eType;
227
228      if (sType.isOptional())
229         return (T)o(readAnything(eType.getElementType(), r, outer, pMeta));
230
231      setCurrentClass(sType);
232
233      Object o = null;
234
235      skipWhitespaceAndComments(r);
236      skipDocumentMarker(r);
237      skipWhitespaceAndComments(r);
238
239      int contentColumn = r.getPosition().getColumn();
240      int c = r.peek();
241      if (c == -1) {
242         // Let o be null.
243      } else if (c == '{') {
244         if (sType.isObject()) {
245            var m2 = newGenericMap();
246            readFlowMapping(r, m2, string(), object(), pMeta);
247            o = cast(m2, pMeta, eType);
248         } else if (nn(builder)) {
249            var m = toBeanMap(builder.create(this, eType));
250            o = builder.build(this, checkRequired(readIntoBeanMap(r, m)).getBean(), eType);
251         } else if (sType.canCreateNewBean(outer)) {
252            var m = newBeanMap(outer, sType.inner());
253            o = checkRequired(readIntoBeanMap(r, m)).getBean();
254         } else if (sType.isMap()) {
255            Map m = (sType.canCreateNewInstance(outer) ? (Map)sType.newInstance(outer) : newGenericMap(sType));
256            o = readFlowMapping(r, m, sType.getKeyType(), sType.getValueType(), pMeta);
257         } else if (sType.isCollection()) {
258            var m = newGenericMap();
259            readFlowMapping(r, m, string(), object(), pMeta);
260            o = cast(m, pMeta, eType);
261         } else if (sType.isArray() || sType.isArgs()) {
262            // Unlike the isCollection() arm above, cast(m, pMeta, eType) has no way to turn a plain Map
263            // into an array -- it only resolves a "_type" bean discriminator key, which a flow mapping
264            // read this way will essentially never carry -- so it used to just hand the caller back the
265            // raw Map unchanged, silently returning the wrong runtime type for the requested array target.
266            // A flow mapping has no sequence shape to convert from, so reject it outright instead.
267            throw new ParseException(this, "Cannot read a YAML flow mapping into array type '%s'.", sType);
268         } else {
269            Map m = newGenericMap();
270            readFlowMapping(r, m, sType.getKeyType(), sType.getValueType(), pMeta);
271            if (m.containsKey(getBeanTypePropertyName(eType)))
272               o = cast((MarshalledMap)m, pMeta, eType);
273            else if (nn(sType.getProxyInvocationHandler()))
274               o = checkRequired(newBeanMap(outer, sType.inner()).load(m)).getBean();
275            else
276               throw new ParseException(this, "Class '%s' could not be instantiated.  Reason: '%s'", cn(sType), sType.getNotABeanReason());
277         }
278      } else if (c == '[') {
279         if (sType.isObject()) {
280            o = readFlowSequence(r, newGenericList(), object(), pMeta);
281         } else if (sType.isCollection()) {
282            Collection l = (sType.canCreateNewInstance(outer) ? (Collection)sType.newInstance() : newGenericList());
283            o = readFlowSequence(r, l, sType, pMeta);
284         } else if (sType.isArray() || sType.isArgs()) {
285            var l = (ArrayList)readFlowSequence(r, list(), sType, pMeta);
286            o = toArray(sType, l);
287         } else {
288            throw new ParseException(this, "Unrecognized syntax for class type '%s', starting character '%s'", sType, (char)c);
289         }
290      } else if (c == '\'') {
291         String s = readSingleQuotedString(r);
292         o = handleQuotedScalar(s, r, sType, eType, builder, outer, pMeta, contentColumn > 0 ? contentColumn - 1 : 0);
293      } else if (c == '"') {
294         String s = readDoubleQuotedString(r);
295         o = handleQuotedScalar(s, r, sType, eType, builder, outer, pMeta, contentColumn > 0 ? contentColumn - 1 : 0);
296      } else if (c == '-') {
297         int c2 = peekSecondChar(r);
298         if (c2 == ' ' || c2 == '\n' || c2 == '\r') {
299            if (sType.isObject()) {
300               o = readBlockSequence(r, newGenericList(), object(), pMeta, 0);
301            } else if (sType.isCollection()) {
302               Collection l = (sType.canCreateNewInstance(outer) ? (Collection)sType.newInstance() : newGenericList());
303               o = readBlockSequence(r, l, sType, pMeta, 0);
304            } else if (sType.isArray() || sType.isArgs()) {
305               var l = (ArrayList)readBlockSequence(r, list(), sType, pMeta, 0);
306               o = toArray(sType, l);
307            } else {
308               throw new ParseException(this, "Unrecognized syntax for class type '%s', starting character '%s'", sType, (char)c);
309            }
310         } else {
311            String s = readPlainScalar(r, 0);
312            o = convertToType(s, sType, eType, outer, pMeta);
313         }
314      } else if (c == '|' || c == '>') {
315         String s = readBlockScalar(r, (char)c);
316         o = convertToType(s, sType, eType, outer, pMeta);
317      } else if (c == '~') {
318         r.read(); // consume '~'
319         // o remains null (initialized at line 255)
320      } else {
321         String s = readPlainScalar(r, 0);
322         o = handlePlainScalar(s, r, sType, eType, builder, outer, pMeta, contentColumn > 0 ? contentColumn - 1 : 0);
323      }
324
325      if (nn(swap) && nn(o))
326         o = unswap(swap, o, eType);
327
328      if (nn(parentBean()))
329         setParent(eType, o, parentBean());
330
331      return (T)o;
332   }
333
334   private <T> Object handleQuotedScalar(String s, ParserReader r, ClassMeta<?> sType, ClassMeta<?> eType, BuilderSwap<T,Object> builder, Object outer, BeanPropertyMeta pMeta, int keyIndent) throws IOException, ParseException, ExecutableException {
335      if (looksLikeMappingKey(r)) {
336         r.read(); // consume ':'
337         int cp = r.peek();
338         if (cp == ' ')
339            r.read();
340
341         if (sType.isObject()) {
342            var m2 = newGenericMap();
343            Object value = readAnything(object(), r, m2, pMeta);
344            String ts = trim(s);
345            setName(object(), value, ts);
346            m2.put(ts, value);
347            readBlockMappingRemainder(r, m2, string(), object(), pMeta, keyIndent);
348            return cast(m2, pMeta, eType);
349         } else if (nn(builder)) {
350            var m = toBeanMap(builder.create(this, eType));
351            readBeanProperty(r, m, s);
352            readIntoBeanMapBlockRemainder(r, m, keyIndent);
353            return builder.build(this, checkRequired(m).getBean(), eType);
354         } else if (sType.canCreateNewBean(outer)) {
355            var m = newBeanMap(outer, sType.inner());
356            readBeanProperty(r, m, s);
357            readIntoBeanMapBlockRemainder(r, m, keyIndent);
358            return checkRequired(m).getBean();
359         } else if (sType.isMap()) {
360            Map m = (sType.canCreateNewInstance(outer) ? (Map)sType.newInstance(outer) : newGenericMap(sType));
361            Object value = readAnything(sType.getValueType(), r, m, pMeta);
362            Object key = convertAttrToType(m, trim(s), sType.getKeyType());
363            setName(sType.getValueType(), value, key);
364            m.put(key, value);
365            readBlockMappingRemainder(r, m, sType.getKeyType(), sType.getValueType(), pMeta, keyIndent);
366            return m;
367         } else {
368            var m2 = newGenericMap();
369            Object value = readAnything(object(), r, m2, pMeta);
370            m2.put(s, value);
371            readBlockMappingRemainder(r, m2, string(), object(), pMeta, keyIndent);
372            if (m2.containsKey(getBeanTypePropertyName(eType)))
373               return cast(m2, pMeta, eType);
374            if (nn(sType.getProxyInvocationHandler()))
375               return checkRequired(newBeanMap(outer, sType.inner()).load(m2)).getBean();
376            throw new ParseException(this, "Class '%s' could not be instantiated.  Reason: '%s'", cn(sType), sType.getNotABeanReason());
377         }
378      }
379      if (sType.isObject())
380         return trim(s);
381      return convertToType(s, sType, eType, outer, pMeta);
382   }
383
384   private <T> Object handlePlainScalar(String s, ParserReader r, ClassMeta<?> sType, ClassMeta<?> eType, BuilderSwap<T,Object> builder, Object outer, BeanPropertyMeta pMeta, int keyIndent) throws IOException, ParseException, ExecutableException {
385      if (s.isEmpty())
386         return null;
387
388      if (looksLikeMappingKey(r)) {
389         r.read(); // consume ':'
390         int cp = r.peek();
391         if (cp == ' ')
392            r.read(); // consume space after ':'
393
394         String keyStr = isYamlNull(s) ? null : trim(s);
395         if (sType.isObject()) {
396            var m2 = newGenericMap();
397            Object value = readAnything(object(), r, m2, pMeta);
398            setName(object(), value, keyStr);
399            m2.put(keyStr, value);
400            readBlockMappingRemainder(r, m2, string(), object(), pMeta, keyIndent);
401            return cast(m2, pMeta, eType);
402         } else if (nn(builder)) {
403            var m = toBeanMap(builder.create(this, eType));
404            readBeanProperty(r, m, s);
405            readIntoBeanMapBlockRemainder(r, m, keyIndent);
406            return builder.build(this, checkRequired(m).getBean(), eType);
407         } else if (sType.canCreateNewBean(outer)) {
408            var m = newBeanMap(outer, sType.inner());
409            readBeanProperty(r, m, s);
410            readIntoBeanMapBlockRemainder(r, m, keyIndent);
411            return checkRequired(m).getBean();
412         } else if (sType.isMap()) {
413            Map m = (sType.canCreateNewInstance(outer) ? (Map)sType.newInstance(outer) : newGenericMap(sType));
414            Object value = readAnything(sType.getValueType(), r, m, pMeta);
415            Object key = convertAttrToType(m, keyStr, sType.getKeyType());
416            setName(sType.getValueType(), value, key);
417            m.put(key, value);
418            readBlockMappingRemainder(r, m, sType.getKeyType(), sType.getValueType(), pMeta, keyIndent);
419            return m;
420         } else {
421            var m2 = newGenericMap();
422            Object value = readAnything(object(), r, m2, pMeta);
423            m2.put(s, value);
424            readBlockMappingRemainder(r, m2, string(), object(), pMeta, keyIndent);
425            if (m2.containsKey(getBeanTypePropertyName(eType)))
426               return cast(m2, pMeta, eType);
427            if (nn(sType.getProxyInvocationHandler()))
428               return checkRequired(newBeanMap(outer, sType.inner()).load(m2)).getBean();
429            throw new ParseException(this, "Class '%s' could not be instantiated.  Reason: '%s'", cn(sType), sType.getNotABeanReason());
430         }
431      }
432
433      if (isYamlNull(s))
434         return null;
435
436      if ("true".equals(s) || "false".equals(s)) {
437         if (sType.isObject() || sType.isBoolean())
438            return Boolean.valueOf(s);
439         return convertToType(s, sType, eType, outer, pMeta);
440      }
441
442      return convertToType(s, sType, eType, outer, pMeta);
443   }
444
445   private Object convertToType(String s, ClassMeta<?> sType, ClassMeta<?> eType, Object outer, BeanPropertyMeta pMeta) throws ParseException {
446      if (sType.isObject()) {
447         return resolveScalarType(trim(s));
448      } else if (sType.isCharSequence()) {
449         return trim(s);
450      } else if (sType.isChar()) {
451         return parseCharacter(s);
452      } else if (sType.isNumber()) {
453         return StringUtils.parseNumber(s, (Class<? extends Number>)sType.inner());
454      } else if (sType.isBoolean()) {
455         return b(s);
456      } else if (sType.isDate()) {
457         return readDate(s, sType);
458      } else if (sType.isCalendar()) {
459         return readCalendar(s, sType);
460      } else if (sType.isTemporal()) {
461         return readTemporal(s, sType);
462      } else if (sType.isDuration()) {
463         return readDuration(s);
464      } else if (sType.isPeriod()) {
465         return readPeriod(s);
466      } else if (sType.canCreateNewInstanceFromString(outer)) {
467         return sType.newInstanceFromString(outer, s);
468      } else {
469         throw new ParseException(this, "Unrecognized syntax for class type '%s', value '%s'", sType, s);
470      }
471   }
472
473   private static boolean looksLikeMappingKey(ParserReader r) throws IOException {
474      return r.peek() == ':';
475   }
476
477   private static boolean isYamlNull(String s) {
478      return "null".equals(s) || "Null".equals(s) || "NULL".equals(s) || "~".equals(s);
479   }
480
481   private <K,V> void readBlockMappingRemainder(ParserReader r, Map<K,V> m, ClassMeta<K> keyType, ClassMeta<V> valueType, BeanPropertyMeta pMeta, int parentIndent) throws IOException, ParseException, ExecutableException {
482      readBlockMapping(r, m, keyType, valueType, pMeta, parentIndent);
483   }
484
485   private <T> void readIntoBeanMapBlockRemainder(ParserReader r, BeanMap<T> m, int parentIndent) throws IOException, ParseException, ExecutableException {
486      readIntoBeanMapBlock(r, m, parentIndent);
487   }
488
489   private <T> void readBeanProperty(ParserReader r, BeanMap<T> m, String currAttr) throws IOException, ParseException, ExecutableException {
490      var pb = swapParentBean(m.getBean(false));
491      try {
492      var pm = m.getPropertyMeta(currAttr);
493      setCurrentProperty(pm);
494      if (pm == null) {
495         onUnknownProperty(currAttr, m, readAnything(object(), r, m.getBean(false), null));
496      } else {
497         var cm = (ClassMeta<?>) pm.getBeanInfo();
498         Object value = readAnything(cm, r, m.getBean(false), pm);
499         setName(cm, value, currAttr);
500         try {
501            pm.set(m, currAttr, value);
502         } catch (BeanRuntimeException e) {
503            onBeanSetterException(pm, e);
504            throw e;
505         }
506      }
507      } finally {
508         swapParentBean(pb);
509      }
510      setCurrentProperty(null);
511   }
512
513   private static boolean isNullBlockValue(ParserReader r, int blockIndent) throws IOException {
514      int c = r.peek();
515      if (c == -1)
516         return true;
517      if (c != '\n' && c != '\r')
518         return false;
519      int charsRead = 0;
520      while (true) {
521         c = r.read();
522         if (c == -1) {
523            for (int j = 0; j < charsRead; j++) r.unread();
524            return true;
525         }
526         charsRead++;
527         if (c != '\n' && c != '\r' && c != ' ' && c != '\t')
528            break;
529      }
530      int nextColumn = r.getPosition().getColumn() - 1;
531      for (int j = 0; j < charsRead; j++) r.unread();
532      return nextColumn <= blockIndent;
533   }
534
535   private static int peekSecondChar(ParserReader r) throws IOException {
536      r.read();
537      int c2 = r.peek();
538      r.unread();
539      return c2;
540   }
541
542   // ==========================================
543   // Flow mapping: { key: value, ... }
544   // ==========================================
545   private <K,V> Map<K,V> readFlowMapping(ParserReader r, Map<K,V> m, ClassMeta<K> keyType, ClassMeta<V> valueType, BeanPropertyMeta pMeta) throws IOException, ParseException, ExecutableException {
546
547      if (keyType == null)
548         keyType = (ClassMeta<K>)string();
549
550      // S1: Looking for outer {
551      // S2: Looking for key start or }
552      // S3: Found key, looking for :
553      // S4: Found :, looking for value
554      // S5: Looking for , or }
555      // S6: Found , looking for key start
556
557      var state = S1;
558      String currKey = null;
559      int c = 0;
560      while (c != -1) {
561         c = r.read();
562         if (state == S1) {
563            if (c == '{')
564               state = S2;
565            else if (isWhitespace(c))
566               continue;
567            else
568               break;
569         } else if (state == S2) {
570            if (c == '}') {
571               return m;
572            } else if (isWhitespace(c)) {
573               continue;
574            } else {
575               r.unread();
576               currKey = readFlowMappingKey(r);
577               state = S3;
578            }
579         } else if (state == S3) {
580            if (c == ':')
581               state = S4;
582            else if (isWhitespace(c))
583               continue;
584         } else if (state == S4) {
585            if (isWhitespace(c))
586               continue;
587            r.unread();
588            K key = convertAttrToType(m, currKey, keyType);
589            V value = readAnything(valueType, r, m, pMeta);
590            setName(valueType, value, key);
591            m.put(key, value);
592            state = S5;
593         } else if (state == S5) {
594            if (c == ',') {
595               state = S6;
596            } else if (isWhitespace(c)) {
597               continue;
598            } else if (c == '}') {
599               return m;
600            } else {
601               break;
602            }
603         } else if (state == S6) {
604            if (c == '}') {
605               break;
606            } else if (isWhitespace(c)) {
607               continue;
608            } else {
609               r.unread();
610               currKey = readFlowMappingKey(r);
611               state = S3;
612            }
613         }
614      }
615      if (state == S1)
616         throw new ParseException(this, "Expected '{' at beginning of YAML flow mapping.");
617      if (state == S2)
618         throw new ParseException(this, "Could not find key in YAML flow mapping.");
619      if (state == S3)
620         throw new ParseException(this, "Could not find ':' following key in YAML flow mapping.");
621      if (state == S4)
622         throw new ParseException(this, "Expected value in YAML flow mapping.");
623      if (state == S5)
624         throw new ParseException(this, "Could not find '}' marking end of YAML flow mapping.");
625      if (state == S6)
626         throw new ParseException(this, "Unexpected '}' found in YAML flow mapping.");
627
628      return null; // Unreachable.
629   }
630
631   private String readFlowMappingKey(ParserReader r) throws IOException, ParseException {
632      int c = r.peek();
633      if (c == '\'' )
634         return readSingleQuotedString(r);
635      if (c == '"')
636         return readDoubleQuotedString(r);
637      var key = readPlainFlowKey(r);
638      if (isYamlNull(key))
639         return null;
640      return key;
641   }
642
643   private static String readPlainFlowKey(ParserReader r) throws IOException {
644      var sb = new StringBuilder();
645      int c;
646      while ((c = r.read()) != -1) {
647         if (c == ':' || c == ',' || c == '}' || c == '{' || c == '[' || c == ']') {
648            r.unread();
649            break;
650         }
651         sb.append((char)c);
652      }
653      return sb.toString().trim();
654   }
655
656   // ==========================================
657   // Flow sequence: [ value, ... ]
658   // ==========================================
659   private <E> Collection<E> readFlowSequence(ParserReader r, Collection<E> l, ClassMeta<?> type, BeanPropertyMeta pMeta) throws IOException, ParseException, ExecutableException {
660
661      // S1: Looking for outermost [
662      // S2: Looking for value or ]
663      // S3: Looking for , or ]
664      // S4: Looking for value
665
666      int argIndex = 0;
667
668      var state = S1;
669      int c = 0;
670      while (c != -1) {
671         c = r.read();
672         if (state == S1) {
673            if (c == '[')
674               state = S2;
675            else if (isWhitespace(c))
676               continue;
677            else
678               break;
679         } else if (state == S2) {
680            if (c == ']') {
681               return l;
682            } else if (isWhitespace(c)) {
683               continue;
684            } else if (c != -1) {
685               r.unread();
686               l.add((E)readAnything(type.isArgs() ? type.getArg(argIndex++) : type.getElementType(), r, l, pMeta));
687               state = S3;
688            }
689         } else if (state == S3) {
690            if (c == ',') {
691               state = S4;
692            } else if (isWhitespace(c)) {
693               continue;
694            } else if (c == ']') {
695               return l;
696            } else {
697               break;
698            }
699         } else if (state == S4) {
700            if (isWhitespace(c)) {
701               continue;
702            } else if (c == ']') {
703               break;
704            } else if (c != -1) {
705               r.unread();
706               l.add((E)readAnything(type.isArgs() ? type.getArg(argIndex++) : type.getElementType(), r, l, pMeta));
707               state = S3;
708            }
709         }
710      }
711      if (state == S1)
712         throw new ParseException(this, "Expected '[' at beginning of YAML flow sequence.");
713      if (state == S2)
714         throw new ParseException(this, "Expected value or ']' in YAML flow sequence.");
715      if (state == S3)
716         throw new ParseException(this, "Expected ',' or ']' in YAML flow sequence.");
717      if (state == S4)
718         throw new ParseException(this, "Unexpected trailing comma in YAML flow sequence.");
719
720      return null; // Unreachable.
721   }
722
723   // ==========================================
724   // Block mapping
725   // ==========================================
726   private <K,V> Map<K,V> readBlockMapping(ParserReader r, Map<K,V> m, ClassMeta<K> keyType, ClassMeta<V> valueType, BeanPropertyMeta pMeta, int parentIndent) throws IOException, ParseException, ExecutableException {
727
728      if (keyType == null)
729         keyType = (ClassMeta<K>)string();
730
731      int blockIndent = -1;
732
733      while (true) {
734         int consumed = skipBlanksAndCountIndent(r);
735         int lineIndent = r.getPosition().getColumn();
736         int c = r.peek();
737         if (c == -1)
738            break;
739
740         if (blockIndent == -1) {
741            if (lineIndent <= parentIndent && parentIndent > 0) {
742               unreadSpaces(r, consumed);
743               break;
744            }
745            blockIndent = lineIndent;
746         }
747
748         if (lineIndent < blockIndent) {
749            unreadSpaces(r, consumed);
750            break;
751         }
752
753         c = r.peek();
754         if (c == '#') {
755            skipToEndOfLine(r);
756            continue;
757         }
758
759         String keyStr = trim(readBlockMappingKey(r));
760
761         c = r.read(); // Should be ':'
762         if (c != ':')
763            throw new ParseException(this, "Expected ':' after key in YAML block mapping, found '%s'", (char)c);
764
765         c = r.peek();
766         if (c == ' ')
767            r.read();
768         K key = convertAttrToType(m, keyStr, keyType);
769         V value = (V)readAnything(valueType, r, m, pMeta);
770         setName(valueType, value, key);
771         m.put(key, value);
772      }
773
774      return m;
775   }
776
777   private static int skipBlanksAndCountIndent(ParserReader r) throws IOException {
778      int indent = 0;
779      int c;
780      while ((c = r.read()) != -1) {
781         if (c == ' ') {
782            indent++;
783         } else if (c == '\n' || c == '\r') {
784            indent = 0;
785         } else if (c == '\t') {
786            indent++;
787         } else {
788            r.unread();
789            break;
790         }
791      }
792      return indent;
793   }
794
795   private static void unreadSpaces(ParserReader r, int count) throws IOException {
796      for (int i = 0; i < count; i++)
797         r.unread();
798   }
799
800   private String readBlockMappingKey(ParserReader r) throws IOException, ParseException {
801      int c = r.peek();
802      if (c == '\'')
803         return readSingleQuotedString(r);
804      if (c == '"')
805         return readDoubleQuotedString(r);
806      var sb = new StringBuilder();
807      while ((c = r.read()) != -1) {
808         if (c == ':') {
809            int next = r.peek();
810            if (next == ' ' || next == '\n' || next == '\r' || next == -1) {
811               r.unread();
812               break;
813            }
814            sb.append((char)c);
815         } else if (c == '\n' || c == '\r') {
816            r.unread();
817            break;
818         } else {
819            sb.append((char)c);
820         }
821      }
822      String key = sb.toString().trim();
823      if (isYamlNull(key))
824         return null;
825      return key;
826   }
827
828   // ==========================================
829   // Block mapping for beans
830   // ==========================================
831   private <T> BeanMap<T> readIntoBeanMap(ParserReader r, BeanMap<T> m) throws IOException, ParseException, ExecutableException {
832      int c = r.peek();
833      if (c == '{') {
834         return readIntoBeanMapFlow(r, m);
835      }
836      return readIntoBeanMapBlock(r, m, 0);
837   }
838
839   private <T> BeanMap<T> readIntoBeanMapFlow(ParserReader r, BeanMap<T> m) throws IOException, ParseException, ExecutableException {
840
841      // S1: Looking for outer {
842      // S2: Looking for attrName start.
843      // S3: Found attrName end, looking for :.
844      // S4: Found :, looking for valStart.
845      // S5: Looking for , or }
846
847      var state = S1;
848      var currAttr = "";
849      int c = 0;
850      var pb = swapParentBean(m.getBean(false));
851      mark();
852      try {
853         while (c != -1) {
854            c = r.read();
855            if (state == S1) {
856               if (c == '{')
857                  state = S2;
858               else if (isWhitespace(c))
859                  continue;
860               else
861                  break;
862            } else if (state == S2) {
863               if (c == '}') {
864                  return m;
865               } else if (isWhitespace(c)) {
866                  continue;
867               } else {
868                  r.unread();
869                  mark();
870                  currAttr = readFlowMappingKey(r);
871                  state = S3;
872               }
873            } else if (state == S3) {
874               if (c == ':')
875                  state = S4;
876               else if (isWhitespace(c))
877                  continue;
878            } else if (state == S4) {
879               if (isWhitespace(c))
880                  continue;
881               if (! currAttr.equals(getBeanTypePropertyName((ClassMeta<?>) m.getBeanInfo()))) {
882                  var pm = m.getPropertyMeta(currAttr);
883                  setCurrentProperty(pm);
884                  if (pm == null) {
885                     onUnknownProperty(currAttr, m, readAnything(object(), r.unread(), m.getBean(false), null));
886                     unmark();
887                  } else {
888                     unmark();
889                     var cm = (ClassMeta<?>) pm.getBeanInfo();
890                     Object value = readAnything(cm, r.unread(), m.getBean(false), pm);
891                     setName(cm, value, currAttr);
892                     try {
893                        pm.set(m, currAttr, value);
894                     } catch (BeanRuntimeException e) {
895                        onBeanSetterException(pm, e);
896                        throw e;
897                     }
898                  }
899                  setCurrentProperty(null);
900               }
901               state = S5;
902            } else if (state == S5) {
903               if (c == ',')
904                  state = S2;
905               else if (isWhitespace(c))
906                  continue;
907               else if (c == '}') {
908                  return m;
909               }
910            }
911         }
912         if (state == S1)
913            throw new ParseException(this, "Expected '{' at beginning of YAML flow mapping.");
914         if (state == S2)
915            throw new ParseException(this, "Could not find attribute name in YAML flow mapping.");
916         if (state == S3)
917            throw new ParseException(this, "Could not find ':' following attribute name in YAML flow mapping.");
918         if (state == S4)
919            throw new ParseException(this, "Expected value in YAML flow mapping.");
920         if (state == S5)
921            throw new ParseException(this, "Could not find '}' marking end of YAML flow mapping.");
922      } finally {
923         unmark();
924         swapParentBean(pb);
925      }
926
927      return null; // Unreachable.
928   }
929
930   private <T> BeanMap<T> readIntoBeanMapBlock(ParserReader r, BeanMap<T> m, int parentIndent) throws IOException, ParseException, ExecutableException {
931
932      int blockIndent = -1;
933
934      var pb = swapParentBean(m.getBean(false));
935      mark();
936      try {
937         while (true) {
938            int consumed = skipBlanksAndCountIndent(r);
939            int lineIndent = r.getPosition().getColumn();
940            int c = r.peek();
941            if (c == -1)
942               break;
943
944            if (blockIndent == -1) {
945               if (lineIndent <= parentIndent && parentIndent > 0) {
946                  unreadSpaces(r, consumed);
947                  break;
948               }
949               blockIndent = lineIndent;
950            }
951
952            if (lineIndent < blockIndent) {
953               unreadSpaces(r, consumed);
954               break;
955            }
956
957            c = r.peek();
958            if (c == '#') {
959               skipToEndOfLine(r);
960               continue;
961            }
962
963            String currAttr = trim(readBlockMappingKey(r));
964
965            c = r.read(); // Should be ':'
966            if (c != ':')
967               throw new ParseException(this, "Expected ':' after attribute name in YAML block mapping, found '%s'", (char)c);
968
969            if (! currAttr.equals(getBeanTypePropertyName((ClassMeta<?>) m.getBeanInfo()))) {
970               var pm = m.getPropertyMeta(currAttr);
971               setCurrentProperty(pm);
972               if (pm == null) {
973                  c = r.peek();
974                  if (c == ' ')
975                     r.read();
976                  Object v = isNullBlockValue(r, blockIndent) ? null : readAnything(object(), r, m.getBean(false), null);
977                  onUnknownProperty(currAttr, m, v);
978                  unmark();
979               } else {
980                  unmark();
981                  var cm = (ClassMeta<?>) pm.getBeanInfo();
982                  c = r.peek();
983                  if (c == ' ')
984                     r.read();
985                  Object value = isNullBlockValue(r, blockIndent) ? null : readAnything(cm, r, m.getBean(false), pm);
986                  setName(cm, value, currAttr);
987                  try {
988                     pm.set(m, currAttr, value);
989                  } catch (BeanRuntimeException e) {
990                     onBeanSetterException(pm, e);
991                     throw e;
992                  }
993               }
994               setCurrentProperty(null);
995            }
996            mark();
997         }
998      } finally {
999         unmark();
1000         swapParentBean(pb);
1001      }
1002
1003      return m;
1004   }
1005
1006   // ==========================================
1007   // Block sequence: - value\n- value\n...
1008   // ==========================================
1009   private <E> Collection<E> readBlockSequence(ParserReader r, Collection<E> l, ClassMeta<?> type, BeanPropertyMeta pMeta, int parentIndent) throws IOException, ParseException, ExecutableException {
1010
1011      int blockIndent = -1;
1012      int argIndex = 0;
1013
1014      while (true) {
1015         int consumed = skipBlanksAndCountIndent(r);
1016         int lineIndent = r.getPosition().getColumn();
1017         int c = r.peek();
1018         if (c == -1)
1019            break;
1020
1021         if (blockIndent == -1) {
1022            if (lineIndent <= parentIndent && parentIndent > 0) {
1023               unreadSpaces(r, consumed);
1024               break;
1025            }
1026            blockIndent = lineIndent;
1027         }
1028
1029         if (lineIndent < blockIndent) {
1030            unreadSpaces(r, consumed);
1031            break;
1032         }
1033
1034         c = r.peek();
1035         if (c == '#') {
1036            skipToEndOfLine(r);
1037            continue;
1038         }
1039         if (c != '-') {
1040            unreadSpaces(r, lineIndent);
1041            break;
1042         }
1043
1044         r.read(); // consume '-'
1045         c = r.peek();
1046         if (c != ' ' && c != '\n' && c != '\r' && c != -1)
1047            throw new ParseException(this, "Expected space or line terminator after '-' in YAML block sequence, but found '%s'.", (char)c);
1048
1049         if (c == ' ')
1050            r.read(); // consume space after '-'
1051
1052         ClassMeta<?> elementType = type.isArgs() ? type.getArg(argIndex++) : type.getElementType();
1053         l.add((E)readAnything(elementType, r, l, pMeta));
1054      }
1055
1056      return l;
1057   }
1058
1059   // ==========================================
1060   // Single-quoted string: 'hello ''world'''
1061   // ==========================================
1062   private String readSingleQuotedString(ParserReader r) throws IOException, ParseException {
1063      int c = r.read(); // consume opening '
1064      if (c != '\'')
1065         throw new ParseException(this, "Expected single quote to start string.");
1066
1067      var sb = new StringBuilder();
1068      while ((c = r.read()) != -1) {
1069         if (c == '\'') {
1070            int next = r.peek();
1071            if (next == '\'') {
1072               r.read(); // consume escaped '
1073               sb.append('\'');
1074            } else {
1075               return sb.toString();
1076            }
1077         } else {
1078            sb.append((char)c);
1079         }
1080      }
1081      throw new ParseException(this, "Could not find end of single-quoted YAML string.");
1082   }
1083
1084   // ==========================================
1085   // Double-quoted string: "hello \"world\"\n"
1086   // ==========================================
1087   private String readDoubleQuotedString(ParserReader r) throws IOException, ParseException {
1088      int c = r.read(); // consume opening "
1089      if (c != '"')
1090         throw new ParseException(this, "Expected double quote to start string.");
1091
1092      var sb = new StringBuilder();
1093      while ((c = r.read()) != -1) {
1094         if (c == '\\') {
1095            c = r.read();
1096            // @formatter:off
1097            switch (c) {
1098               case '\\': sb.append('\\'); break;
1099               case '"': sb.append('"'); break;
1100               case 'n': sb.append('\n'); break;
1101               case 't': sb.append('\t'); break;
1102               case 'r': sb.append('\r'); break;
1103               case '0': sb.append('\0'); break;
1104               case 'a': sb.append('\u0007'); break;
1105               case 'b': sb.append('\b'); break;
1106               case 'f': sb.append('\f'); break;
1107               case 'e': sb.append('\u001b'); break;
1108               case '/': sb.append('/'); break;
1109               case 'x': {
1110                  String hex = r.read(2);
1111                  try {
1112                     sb.append((char)Integer.parseInt(hex, 16));
1113                  } catch (@SuppressWarnings("unused") NumberFormatException e) {
1114                     throw new ParseException(this, "Invalid \\x escape sequence in YAML string.");
1115                  }
1116                  break;
1117               }
1118               case 'u': {
1119                  String hex = r.read(4);
1120                  try {
1121                     sb.append((char)Integer.parseInt(hex, 16));
1122                  } catch (@SuppressWarnings("unused") NumberFormatException e) {
1123                     throw new ParseException(this, "Invalid \\u escape sequence in YAML string.");
1124                  }
1125                  break;
1126               }
1127               default:
1128                  throw new ParseException(this, "Invalid escape sequence '\\%s' in YAML string.", (char)c);
1129            }
1130            // @formatter:on
1131         } else if (c == '"') {
1132            return sb.toString();
1133         } else {
1134            sb.append((char)c);
1135         }
1136      }
1137      throw new ParseException(this, "Could not find end of double-quoted YAML string.");
1138   }
1139
1140   // ==========================================
1141   // Plain scalar (unquoted)
1142   // ==========================================
1143   private static String readPlainScalar(ParserReader r, int indent) throws IOException {
1144      var sb = new StringBuilder();
1145      int c;
1146      while ((c = r.read()) != -1) {
1147         if (c == '\n' || c == '\r') {
1148            r.unread();
1149            break;
1150         }
1151         if (c == ':') {
1152            int next = r.peek();
1153            if (next == ' ' || next == '\n' || next == '\r' || next == -1) {
1154               r.unread(); // unread ':'
1155               break;
1156            }
1157            sb.append((char)c);
1158         } else if (c == ' ') {
1159            int next = r.peek();
1160            if (next == '#') {
1161               // rest of line is comment
1162               r.unread();
1163               break;
1164            }
1165            sb.append((char)c);
1166         } else if ((c == ',' || c == '}' || c == ']') || (c == '#' && sb.isEmpty())) {
1167            r.unread();
1168            break;
1169         } else {
1170            sb.append((char)c);
1171         }
1172      }
1173      String result = sb.toString();
1174      // Trim trailing whitespace
1175      int end = result.length();
1176      while (end > 0 && result.charAt(end - 1) == ' ')
1177         end--;
1178      return result.substring(0, end);
1179   }
1180
1181   // ==========================================
1182   // Block scalar: | or >
1183   // ==========================================
1184   private String readBlockScalar(ParserReader r, char indicator) throws IOException, ParseException {
1185      r.read(); // consume '|' or '>'
1186
1187      // Parse indicator line for chomping
1188      char chomping = ' '; // default = clip
1189      int c;
1190      while ((c = r.read()) != -1) {
1191         if (c == '-') {
1192            chomping = '-'; // strip
1193         } else if (c == '+') {
1194            chomping = '+'; // keep
1195         } else if (c == '\n' || c == '\r') {
1196            if (c == '\r') {
1197               int next = r.peek();
1198               if (next == '\n')
1199                  r.read();
1200            }
1201            break;
1202         } else if (c >= '1' && c <= '9') {
1203            // explicit indent indicator, ignore for now (auto-detect below)
1204         } else if (c == ' ' || c == '\t') {
1205            continue;
1206         } else {
1207            throw new ParseException(this, "Unexpected character '%s' in YAML block scalar indicator.", (char)c);
1208         }
1209      }
1210
1211      // Read the block content
1212      int blockIndent = -1;
1213      var lines = new ArrayList<String>();
1214      int trailingNewlines = 0;
1215
1216      while (true) {
1217         // Count leading spaces
1218         int spaces = 0;
1219         while ((c = r.read()) != -1) {
1220            if (c == ' ')
1221               spaces++;
1222            else
1223               break;
1224         }
1225
1226         if (c == -1) {
1227            break;
1228         }
1229
1230         if (c == '\n' || c == '\r') {
1231            // Empty line.  Only tracked via trailingNewlines here -- the "" placeholder is added to
1232            // `lines` once, either by the flush below (once the next content line is reached, for an
1233            // interior blank run) or never at all (for a run of blank lines trailing the last content
1234            // line, which chomping='+' replays directly from trailingNewlines instead -- see below).
1235            trailingNewlines++;
1236            if (c == '\r' && r.peek() == '\n')
1237               r.read();
1238            continue;
1239         }
1240
1241         if (blockIndent == -1) {
1242            blockIndent = spaces;
1243         }
1244
1245         if (spaces < blockIndent) {
1246            // End of block, push back everything
1247            r.unread(); // push back non-space char
1248            for (int i = 0; i < spaces; i++)
1249               r.unread();
1250            break;
1251         }
1252
1253         // Read rest of line
1254         var lineSb = new StringBuilder();
1255         // Include extra spaces beyond blockIndent
1256         for (int i = blockIndent; i < spaces; i++)
1257            lineSb.append(' ');
1258         lineSb.append((char)c);
1259         while ((c = r.read()) != -1) {
1260            if (c == '\n' || c == '\r') {
1261               if (c == '\r' && r.peek() == '\n')
1262                  r.read();
1263               break;
1264            }
1265            lineSb.append((char)c);
1266         }
1267
1268         // Account for any blank lines that preceded this content line
1269         for (int i = 0; i < trailingNewlines; i++)
1270            lines.add("");
1271         trailingNewlines = 0;
1272         lines.add(lineSb.toString());
1273
1274         if (c == -1)
1275            break;
1276      }
1277
1278      // Build the result based on indicator and chomping
1279      var sb = new StringBuilder();
1280      for (int i = 0; i < lines.size(); i++) {
1281         String line = lines.get(i);
1282         if (indicator == '|') {
1283            // Literal: preserve newlines
1284            if (i > 0)
1285               sb.append('\n');
1286            sb.append(line);
1287         } else {
1288            // Folded: single newlines -> space, blank-line runs preserved as that many newlines.
1289            // Each blank line contributes its own '\n' via the "line.isEmpty()" arm below; a content
1290            // line immediately following a blank run needs no additional separator of its own (that
1291            // would double-count the boundary), so it's the "line.isEmpty()" check alone -- not an OR
1292            // against the *previous* line's emptiness -- that decides whether a newline is due here.
1293            if (i > 0) {
1294               if (line.isEmpty()) {
1295                  sb.append('\n');
1296               } else if (! lines.get(i - 1).isEmpty()) {
1297                  sb.append(' ');
1298               }
1299            }
1300            sb.append(line);
1301         }
1302      }
1303
1304      // Apply chomping
1305      if (chomping == '-') {
1306         // strip: no trailing newline
1307      } else if (chomping == '+') {
1308         // keep: preserve all trailing newlines
1309         sb.append('\n');
1310         for (int i = 0; i < trailingNewlines; i++)
1311            sb.append('\n');
1312      } else {
1313         // clip (default): single trailing newline
1314         sb.append('\n');
1315      }
1316
1317      return sb.toString();
1318   }
1319
1320   // ==========================================
1321   // Helper methods
1322   // ==========================================
1323
1324   private static void skipWhitespaceAndComments(ParserReader r) throws IOException {
1325      int c;
1326      while ((c = r.read()) != -1) {
1327         if (c == '#') {
1328            // Skip to end of line
1329            while ((c = r.read()) != -1) {
1330               if (c == '\n' || c == '\r')
1331                  break;
1332            }
1333         } else if (!isWhitespace(c)) {
1334            r.unread();
1335            return;
1336         }
1337      }
1338   }
1339
1340   private static void skipDocumentMarker(ParserReader r) throws IOException {
1341      int c = r.peek();
1342      if (c == '-') {
1343         r.read();
1344         int c2 = r.peek();
1345         if (c2 == '-') {
1346            r.read();
1347            int c3 = r.peek();
1348            if (c3 == '-') {
1349               r.read();
1350               // '---' found, skip rest of line
1351               skipToEndOfLine(r);
1352               return;
1353            }
1354            r.unread(); // unread second '-'
1355         }
1356         r.unread(); // unread first '-'
1357      } else if (c == '.') {
1358         r.read();
1359         int c2 = r.peek();
1360         if (c2 == '.') {
1361            r.read();
1362            int c3 = r.peek();
1363            if (c3 == '.') {
1364               r.read();
1365               // '...' found, skip rest of line
1366               skipToEndOfLine(r);
1367               return;
1368            }
1369            r.unread();
1370         }
1371         r.unread();
1372      }
1373   }
1374
1375   private static void skipToEndOfLine(ParserReader r) throws IOException {
1376      int c;
1377      while ((c = r.read()) != -1) {
1378         if (c == '\n' || c == '\r')
1379            return;
1380      }
1381   }
1382
1383   private static boolean isWhitespace(int c) {
1384      return c == ' ' || c == '\t' || c == '\n' || c == '\r';
1385   }
1386
1387   private static Object resolveScalarType(String s) {
1388      if (s == null || "null".equals(s) || "~".equals(s) || s.isEmpty())
1389         return null;
1390      if ("true".equals(s) || "True".equals(s) || "TRUE".equals(s))
1391         return Boolean.TRUE;
1392      if ("false".equals(s) || "False".equals(s) || "FALSE".equals(s))
1393         return Boolean.FALSE;
1394
1395      Object num = tryParseNumber(s);
1396      if (num != null)
1397         return num;
1398      return s;
1399   }
1400
1401   private static Object tryParseNumber(String s) {
1402      if (s.isEmpty())
1403         return null;
1404      char first = s.charAt(0);
1405      if (first != '-' && first != '+' && (first < '0' || first > '9') && first != '.')
1406         return null;
1407      try {
1408         if (s.contains(".") || s.contains("e") || s.contains("E")) {
1409            Double d = Double.parseDouble(s);
1410            return (!d.isInfinite() && !d.isNaN()) ? d : null;
1411         }
1412         return tryParseIntegerOrLong(s);
1413      } catch (@SuppressWarnings("unused") NumberFormatException e) {
1414         return null;
1415      }
1416   }
1417
1418   private static Object tryParseIntegerOrLong(String s) {
1419      try {
1420         return Integer.valueOf(s);
1421      } catch (@SuppressWarnings("unused") NumberFormatException e) {
1422         try {
1423            return Long.valueOf(s);
1424         } catch (@SuppressWarnings("unused") NumberFormatException e2) {
1425            return null;
1426         }
1427      }
1428   }
1429}