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.markdown;
018
019import static org.apache.juneau.commons.function.Suppliers.*;
020import static org.apache.juneau.commons.utils.Shorts.*;
021
022import java.io.*;
023import java.util.*;
024
025import org.apache.juneau.commons.bean.*;
026import org.apache.juneau.commons.function.*;
027import org.apache.juneau.marshall.*;
028import org.apache.juneau.marshall.json.*;
029import org.apache.juneau.marshall.json5.*;
030import org.apache.juneau.marshall.parser.*;
031import org.apache.juneau.marshall.stream.*;
032import org.apache.juneau.marshall.swap.spi.*;
033
034/**
035 * Session object for {@link MarkdownParser}.
036 *
037 * <p>
038 * Parses Markdown tables and bulleted lists into Java objects.
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 */
045@SuppressWarnings({
046   "java:S110", // Inheritance depth acceptable for parser session hierarchy
047   "java:S115", // Constants use UPPER_snakeCase convention
048   "java:S1192", // Duplicated literals read more clearly inline than as constants.
049   "java:S3740", // Raw Map needed for generic map construction from ClassMeta
050   "java:S3776", // Cognitive complexity acceptable for doRead / readAnything
051   "java:S6541", // Brain method acceptable for readAnything
052   "rawtypes", // Raw Map is used where the map is created from ClassMeta and its key/value types are only known at runtime
053   "resource", // Closeable resources are owned by the caller's parser session; Eclipse JDT @Owning warning is by design.
054   "unchecked" // (T) casts of parsed cell values and (Collection<Object>) casts of eType.newInstance() match the requested ClassMeta eType
055})
056public class MarkdownParserSession extends ReaderParserSession implements RecordReadable {
057
058   final String nullValue;
059   private final Memoizer<JsonParser> json5Parser = memoizer(() -> {
060      var b = Json5Parser.create().marshallingContext((MarshallingContext) getContext());
061      if (isTrimStrings())
062         b = b.trimStrings();
063      return b.build();
064   });
065
066   /**
067    * Builder class.
068    */
069   @SuppressWarnings({
070      "java:S119" // 'SELF' (CRTP self-type) is intentional and clearer than a single-letter name.
071   })
072   public abstract static class Builder<SELF extends Builder<SELF>> extends ReaderParserSession.Builder<SELF> {
073
074      String nullValue;
075
076      /**
077       * Constructor.
078       *
079       * @param ctx The context creating this session.
080       */
081      protected Builder(MarkdownParser ctx) {
082         super(ctx);
083         nullValue = ctx.getNullValue();
084      }
085
086      @Override
087      public MarkdownParserSession build() {
088         return new MarkdownParserSession(this);
089      }
090
091   }
092
093   /**
094    * Concrete default builder leaf for the non-subclassed {@code create()} path (CRTP terminal).
095    */
096   public static final class DefaultBuilder extends Builder<DefaultBuilder> {
097
098      DefaultBuilder(MarkdownParser ctx) {
099         super(ctx);
100      }
101   }
102
103   /**
104    * Creates a new builder for this object.
105    *
106    * @param ctx The context creating this session.
107    *    <br>Cannot be <jk>null</jk>.
108    * @return A new builder.
109    */
110   @SuppressWarnings({
111      "java:S1452" // Builder<?> wildcard return intentional; callers use it to construct session instances polymorphically
112   })
113   public static Builder<?> create(MarkdownParser ctx) {
114      return new DefaultBuilder(ctx);
115   }
116
117   /**
118    * Constructor.
119    *
120    * @param builder The builder for this object.
121    */
122   protected MarkdownParserSession(Builder<?> builder) {
123      super(builder);
124      nullValue = or(builder.nullValue, "*null*");
125   }
126
127   @Override /* RecordReadable */
128   public RecordReader readRecords(Object input) throws IOException {
129      return RecordAdapter.reader(this, input);
130   }
131
132   @Override /* RecordReadable */
133   public boolean isRecordStreaming() {
134      return false;
135   }
136
137   @Override /* Overridden from ParserSession */
138   protected <T> T doRead(ParserPipe pipe, ClassMeta<T> type) throws IOException, ParseException {
139      try (var r = new BufferedReader(pipe.getReader())) {
140         var lines = readAllLines(r);
141         return readAnything(lines, type, getOuter(), null);
142      }
143   }
144
145   /**
146    * Main parse dispatch method.
147    *
148    * @param <T> The target type.
149    * @param lines All input lines.
150    * @param eType The expected type.
151    * @param outer The outer object (for inner class instantiation).
152    * @param pMeta The parent bean property meta (may be null).
153    * @return The parsed object.
154    * @throws IOException Thrown by underlying stream.
155    * @throws ParseException If parsing fails.
156    */
157   protected <T> T readAnything(List<String> lines, ClassMeta<T> eType, Object outer, BeanPropertyMeta pMeta) throws IOException, ParseException {
158      enterParseDepth();
159      try {
160         return readAnything0(lines, eType, outer, pMeta);
161      } finally {
162         exitParseDepth();
163      }
164   }
165
166   // Workhorse method, wrapped by readAnything() with the recursion-depth guard.
167   private <T> T readAnything0(List<String> lines, ClassMeta<T> eType, Object outer, BeanPropertyMeta pMeta) throws IOException, ParseException {
168      if (eType == null)
169         eType = (ClassMeta<T>) object();
170
171      var swap = (ObjectSwap<T,Object>) eType.getSwap(this);
172      var builder = (BuilderSwap<T,Object>) eType.getBuilderSwap(this);
173      ClassMeta<?> sType;
174      if (builder != null)
175         sType = builder.getBuilderClassMeta(this);
176      else if (swap != null)
177         sType = swap.getSwapClassMeta(this);
178      else
179         sType = eType;
180
181      if (sType.isOptional())
182         return (T) o(readAnything(lines, eType.getElementType(), outer, pMeta));
183
184      // Skip blank lines and handle empty input
185      var nonBlank = lines.stream().filter(l -> !l.isBlank()).toList();
186      if (lines.isEmpty() || nonBlank.isEmpty())
187         return sType.isString() ? (T) "" : null;
188
189      var firstNonBlank = nonBlank.get(0).trim();
190
191      Object o;
192
193      if (firstNonBlank.startsWith("|")) {
194         // Table input
195         o = readTable(lines, sType, outer);
196      } else if (firstNonBlank.startsWith("- ") || firstNonBlank.startsWith("* ") || firstNonBlank.startsWith("+ ")) {
197         // Bulleted list input
198         o = readBulletList(lines, sType, outer);
199      } else {
200         // Plain text — treat as simple value
201         o = readCellValue(firstNonBlank, sType, null);
202      }
203
204      if (builder != null && o != null)
205         o = builder.build(this, o, eType);
206
207      if (swap != null && o != null)
208         o = unswap(swap, o, eType);
209
210      return (T) o;
211   }
212
213   /**
214    * Parses a Markdown table (either 2-column key/value or multi-column).
215    *
216    * @param lines All input lines.
217    * @param eType The expected type.
218    * @param outer The outer object.
219    * @return The parsed object.
220    * @throws ParseException If parsing fails.
221    */
222   protected Object readTable(List<String> lines, ClassMeta<?> eType, Object outer) throws ParseException {
223      // Extract table rows (lines starting with |)
224      var tableLines = lines.stream().filter(l -> l.trim().startsWith("|")).toList();
225      if (tableLines.isEmpty())
226         return null;
227
228      // Parse header row
229      var headerLine = tableLines.get(0);
230      var headers = splitTableRow(headerLine);
231      if (headers.isEmpty())
232         return null;
233
234      // Skip separator row (|---|---|)
235      var dataLines = tableLines.stream().skip(1).filter(l -> !isSeparatorRow(l)).toList();
236
237      // Detect table type: if 2 columns and first header is "Property"/"Key", treat as key/value table
238      var isKeyValue = headers.size() == 2
239         && (eqic(headers.get(0), "Property") || eqic(headers.get(0), "Key"))
240         && eqic(headers.get(1), "Value");
241
242      if (isKeyValue)
243         return readKeyValueTable(headers, dataLines, eType, outer);
244      return readMultiColumnTable(headers, dataLines, eType, outer);
245   }
246
247   /**
248    * Parses a 2-column key/value Markdown table.
249    *
250    * @param headers The header names.
251    * @param dataLines The data row lines.
252    * @param eType The expected type.
253    * @param outer The outer object.
254    * @return The parsed bean, map, or other object.
255    * @throws ParseException If parsing fails.
256    */
257   @SuppressWarnings({
258      "java:S135" // Two continue statements needed: skip short rows and skip _type row
259   })
260   protected Object readKeyValueTable(List<String> headers, List<String> dataLines, ClassMeta<?> eType, Object outer) throws ParseException {
261
262      // For types with ObjectSwaps or that can't be populated via BeanMap property-setting,
263      // convert the key-value table to a JSON5 object and delegate to the full JSON5 parser.
264      if (needsJson5Path(eType)) {
265         var json5 = keyValueTableToJson5(dataLines);
266         try {
267            return getJson5Parser().readWithOuter(json5, eType, outer);
268         } catch (Exception e) {
269            throw new ParseException(this, e, "Could not parse key-value table as '%s' via JSON5 '%s'.", eType, json5);
270         }
271      }
272
273      if (eType.isBean()) {
274         // First pass: look for _type to resolve concrete class for abstract/interface types
275         ClassMeta<?> actualType = eType;
276         for (var line : dataLines) {
277            var cells = splitTableRow(line);
278            if (cells.size() >= 2 && eq(cells.get(0), "_type")) {
279               var typeName = cells.get(1);
280               var registry = eType.getBeanRegistry();
281               var resolved = registry != null ? registry.getClassMeta(typeName) : null;
282               if (resolved != null)
283                  actualType = resolved;
284               break;
285            }
286         }
287         var m = newBeanMap(outer, actualType.inner());
288         for (var line : dataLines) {
289            var cells = splitTableRow(line);
290            if (cells.size() < 2)
291               continue;
292            var key = cells.get(0);
293
294            // Skip _type row - it was used for type resolution above
295            if (eq(key, "_type"))
296               continue;
297
298            var rawVal = cells.get(1);
299            var pm = m.getPropertyMeta(key);
300            if (pm != null) {
301               setCurrentProperty(pm);
302               var pmcm = (ClassMeta<?>) pm.getBeanInfo();
303               var val = readCellValue(rawVal, pmcm, m.getBean(false));
304               try {
305                  setName(pmcm, val, key);
306               } catch (Exception e) {
307                  throw new ParseException(this, e, "Could not set @NameProperty on '%s'.", key);
308               }
309               pm.set(m, key, val);
310               setCurrentProperty(null);
311            } else {
312               onUnknownProperty(key, m, rawVal);
313            }
314         }
315         return checkRequired(m).getBean();
316      }
317
318      if (eType.isMap()) {
319         Map map = eType.canCreateNewInstance(outer) ? (Map) eType.newInstance(outer) : newGenericMap();
320         var keyType = eType.getKeyType() != null ? eType.getKeyType() : string();
321         var valueType = eType.getValueType() != null ? eType.getValueType() : object();
322         for (var line : dataLines) {
323            var cells = splitTableRow(line);
324            if (cells.size() < 2)
325               continue;
326            var rawKey = cells.get(0);
327            var key = readCellValue(rawKey, keyType, null);
328            // Pass the map being built as the outer when parsing values - non-static inner
329            // classes whose enclosing class is the map type (e.g. H1 inside H extends LinkedHashMap)
330            // need that map instance to satisfy their implicit outer-class constructor argument.
331            var val = readCellValue(cells.get(1), valueType, map);
332            try {
333               setName(valueType, val, key);
334            } catch (Exception e) {
335               throw new ParseException(this, e, "Could not set @NameProperty for map key '%s'.", key);
336            }
337            map.put(key, val);
338         }
339         return map;
340      }
341
342      if (!eType.isObject()) {
343         // Scalar/Number/primitive (or any other non-bean, non-map, non-Object) target: a key/value
344         // table has no shape that maps onto a single scalar *value*, but this used to fall through to
345         // the generic "Object or unknown" handling below regardless of eType, unconditionally building
346         // a MarshalledMap and returning that instead of a T -- throwing a ClassCastException back at
347         // the caller. Only the first data row's value cell (if any) is meaningful for a genuine scalar
348         // target, so parse and return it directly instead of wrapping the whole table in a map.
349         for (var line : dataLines) {
350            var cells = splitTableRow(line);
351            if (cells.size() >= 2)
352               return readCellValue(cells.get(1), eType, null);
353         }
354         return null;
355      }
356
357      // Object or unknown: return MarshalledMap, check for _type and cast if possible
358      var resultMap = newGenericMap();
359      for (var line : dataLines) {
360         var cells = splitTableRow(line);
361         if (cells.size() < 2)
362            continue;
363         var key = cells.get(0);
364         var val = readCellValue(cells.get(1), object(), null);
365         resultMap.put(key, val);
366      }
367      
368      // Check for _type property and cast to typed bean if found
369      if (resultMap.containsKey(getBeanTypePropertyName(eType))) {
370         return cast(resultMap, null, eType);
371      }
372      
373      return resultMap;
374   }
375
376   /**
377    * Parses a multi-column Markdown table (N columns).
378    *
379    * @param headers The column header names.
380    * @param dataLines The data row lines.
381    * @param eType The expected type.
382    * @param outer The outer object.
383    * @return The parsed list of beans, maps, or other objects.
384    * @throws ParseException If parsing fails.
385    */
386   protected Object readMultiColumnTable(List<String> headers, List<String> dataLines, ClassMeta<?> eType, Object outer) throws ParseException {
387      ClassMeta<?> elementType;
388      Collection<Object> result;
389
390      if (eType.isArray()) {
391         elementType = eType.getElementType();
392         result = l();
393      } else if (eType.isCollection()) {
394         elementType = eType.getElementType();
395         result = eType.canCreateNewInstance(outer) ? (Collection<Object>) eType.newInstance() : l();
396      } else if (eType.isObject()) {
397         elementType = object();
398         result = l();
399      } else {
400         // Single bean/map with multiple columns — not a standard use case, parse first row
401         if (!dataLines.isEmpty()) {
402            var cells = splitTableRow(dataLines.get(0));
403            return readRow(headers, cells, eType, outer);
404         }
405         return null;
406      }
407
408      for (var line : dataLines) {
409         var cells = splitTableRow(line);
410         var item = readRow(headers, cells, elementType, result);
411         result.add(item);
412      }
413
414      if (eType.isArray())
415         return toArray(eType, result);
416
417      return result;
418   }
419
420   /**
421    * Parses a single data row into the specified element type.
422    *
423    * @param headers The column header names.
424    * @param cells The cell values for this row.
425    * @param eType The element type.
426    * @param outer The outer object.
427    * @return The parsed element.
428    * @throws ParseException If parsing fails.
429    */
430   protected Object readRow(List<String> headers, List<String> cells, ClassMeta<?> eType, Object outer) throws ParseException {
431      // Check if all cells are null - if so, return null for the entire row
432      boolean allNull = true;
433      for (var cell : cells) {
434         if (cell != null && neq(cell, nullValue) && !cell.trim().isEmpty()) {
435            allNull = false;
436            break;
437         }
438      }
439      if (allNull) {
440         return null;
441      }
442
443      // Check if there's a _type column and resolve the actual type using the bean registry
444      ClassMeta<?> actualType = eType;
445      int typeColIndex = headers.indexOf("_type");
446      if (typeColIndex >= 0 && typeColIndex < cells.size()) {
447         var typeName = cells.get(typeColIndex);
448         if (ine(typeName)) {
449            var registry = eType != null ? eType.getBeanRegistry() : null;
450            var resolved = registry != null ? registry.getClassMeta(typeName) : null;
451            if (resolved != null)
452               actualType = resolved;
453         }
454      }
455
456      // For types with ObjectSwaps or that can't be populated via BeanMap property-setting,
457      // convert the row to a JSON5 object and delegate to the full JSON5 parser.  This correctly
458      // handles ObjectSwaps, @ParentProperty, JsonMap-constructor beans, etc.
459      if (needsJson5Path(actualType)) {
460         var json5 = rowToJson5(headers, cells);
461            try {
462            return getJson5Parser().readWithOuter(json5, actualType, outer);
463         } catch (Exception e) {
464            throw new ParseException(this, e, "Could not parse table row as '%s' via JSON5 '%s'.", actualType, json5);
465         }
466      }
467
468      if (actualType == null || actualType.isObject()) {
469         var m = newGenericMap();
470         for (var i = 0; i < headers.size(); i++) {
471            var header = headers.get(i);
472            if (eq(header, "_type"))
473               continue;
474            var val = i < cells.size() ? cells.get(i) : null;
475            m.put(header, readCellValue(val, object(), null));
476         }
477         if (typeColIndex >= 0 && m.size() > 0)
478            return cast(m, null, eType);
479         return m;
480      }
481      if (actualType.isBean()) {
482         var m = newBeanMap(outer, actualType.inner());
483         for (var i = 0; i < headers.size(); i++) {
484            var header = headers.get(i);
485            if (eq(header, "_type"))
486               continue;
487            var rawVal = i < cells.size() ? cells.get(i) : null;
488            var pm = m.getPropertyMeta(header);
489            if (pm != null) {
490               setCurrentProperty(pm);
491               var val = readCellValue(rawVal, (ClassMeta<?>) pm.getBeanInfo(), m.getBean(false));
492               pm.set(m, header, val);
493               setCurrentProperty(null);
494            } else {
495               onUnknownProperty(header, m, rawVal);
496            }
497         }
498         return checkRequired(m).getBean();
499      }
500      if (actualType.isMap()) {
501         Map map = actualType.canCreateNewInstance(outer) ? (Map) actualType.newInstance(outer) : newGenericMap();
502         var keyType = actualType.getKeyType() != null ? actualType.getKeyType() : string();
503         var valueType = actualType.getValueType() != null ? actualType.getValueType() : object();
504         for (var i = 0; i < headers.size(); i++) {
505            var header = headers.get(i);
506            if (eq(header, "_type"))
507               continue;
508            var key = convertAttrToType(map, header, keyType);
509            var rawVal = i < cells.size() ? cells.get(i) : null;
510            // Pass the map being built as the outer when parsing values - mirrors the
511            // key-value-table branch so non-static inner classes whose enclosing class is the
512            // map type can be instantiated correctly.
513            var val = readCellValue(rawVal, valueType, map);
514            map.put(key, val);
515         }
516         return map;
517      }
518      // Simple type: use first cell
519      return readCellValue(cells.isEmpty() ? null : cells.get(0), actualType, null);
520   }
521
522   /**
523    * Parses a Markdown bulleted list into a collection or array.
524    *
525    * @param lines All input lines.
526    * @param eType The expected type.
527    * @param outer The outer object.
528    * @return The parsed collection, array, or single element.
529    * @throws ParseException If parsing fails.
530    */
531   protected Object readBulletList(List<String> lines, ClassMeta<?> eType, Object outer) throws ParseException {
532      var items = new ArrayList<String>();
533      for (var line : lines) {
534         var trimmed = line.trim();
535         if (trimmed.startsWith("- ") || trimmed.startsWith("* ") || trimmed.startsWith("+ "))
536            items.add(trimmed.substring(2));
537         else if (eqa(trimmed, "-", "*", "+"))
538            items.add("");
539      }
540
541      ClassMeta<?> elementType;
542      Collection<Object> result;
543
544      if (eType.isArray()) {
545         elementType = eType.getElementType();
546         result = l();
547      } else if (eType.isCollection()) {
548         elementType = eType.getElementType();
549         result = eType.canCreateNewInstance(outer) ? (Collection<Object>) eType.newInstance() : l();
550      } else if (!eType.isMap() && !eType.isBean()) {
551         // Scalar/Number/primitive target: a bullet list has no shape that maps onto a single scalar
552         // *value*, but the code below always wrapped every parsed item into a List and returned that --
553         // even when the caller asked for a bare T -- which threw a ClassCastException back at the
554         // top-level read() cast. Only the first item (if any) is meaningful for a genuine scalar
555         // target, so parse and return it directly instead of wrapping it in a list.
556         if (items.isEmpty())
557            return null;
558         ClassMeta<?> scalarType = eType.isObject() ? object() : eType;
559         return readCellValue(items.get(0), scalarType, null);
560      } else {
561         elementType = eType.isObject() ? object() : eType;
562         result = l();
563      }
564
565      for (var item : items)
566         result.add(readCellValue(item, elementType, null));
567
568      if (eType.isArray())
569         return toArray(eType, result);
570
571      return result;
572   }
573
574   /**
575    * Returns a Json5Parser that shares this session's bean context (swaps, implClasses, dictionary).
576    *
577    * <p>
578    * Memoized via {@link Memoizer} — first call constructs the parser; subsequent calls return the cached instance.
579    */
580   private JsonParser getJson5Parser() {
581      return json5Parser.get();
582   }
583
584   /**
585    * Converts a raw Markdown table cell string to the target type.
586    *
587    * <p>
588    * If the cell matches the configured null value, returns {@code null}.
589    * If the cell is backtick-wrapped JSON5, parses via {@link Json5Parser}.
590    * Otherwise, attempts numeric/boolean auto-detection when the target type is {@code Object}.
591    *
592    * @param <T> The target type.
593    * @param val The raw cell string (already unescaped).
594    * @param eType The target type.
595    * @param outer The outer object (parent bean) for @ParentProperty support.
596    * @return The parsed value.
597    * @throws ParseException If parsing fails.
598    */
599   protected <T> T readCellValue(String val, ClassMeta<T> eType, Object outer) throws ParseException {
600      if (val == null)
601         return null;
602      val = val.trim();
603      if (eq(val, nullValue))
604         return null;
605      if (isTrimStrings())
606         val = val.trim();
607      // For String types, preserve empty cells as empty strings; for other types, treat as null
608      if (val.isEmpty())
609         return eType.isString() ? (T) "" : null;
610
611      // Inline JSON5 wrapped in backticks — use context-aware parser with outer for full support
612      // (handles ObjectSwaps, @ParentProperty, JsonMap constructors, etc.)
613      if (val.startsWith("`") && val.endsWith("`") && val.length() > 1) {
614         var inner = val.substring(1, val.length() - 1);
615         try {
616            return getJson5Parser().readWithOuter(inner, eType, outer);
617         } catch (Exception e) {
618            throw new ParseException(this, e, "Could not parse inline JSON5 '%s' to type '%s'.", inner, eType);
619         }
620      }
621
622      // Unescape table cell escaping
623      val = unescapeCell(val);
624
625      if (eType.isObject()) {
626         // Auto-detect type
627         if (eq(val, "true")) return (T) Boolean.TRUE;
628         if (eq(val, "false")) return (T) Boolean.FALSE;
629         try { return (T) Integer.valueOf(val); } catch (@SuppressWarnings("unused") NumberFormatException ignored) { /* not int, try next */ }
630         try { return (T) Long.valueOf(val); } catch (@SuppressWarnings("unused") NumberFormatException ignored) { /* not long, try next */ }
631         try { return (T) Double.valueOf(val); } catch (@SuppressWarnings("unused") NumberFormatException ignored) { /* not double, treat as string */ }
632         return (T) val;
633      }
634
635      // Date / time / duration cluster: route through the format-aware parsers so the configured
636      // MarshallingContext.get<Format>() hint reaches the wire-form coercion.  Without this the
637      // fall-through to convertToType(val, eType) below would route a bare numeric cell through a
638      // generic Number → T coercion (e.g. Duration.ofMillis(long)) that drops the format hint.
639      if (eType.isDate())
640         return readDate(val, eType);
641      if (eType.isCalendar())
642         return readCalendar(val, eType);
643      if (eType.isTemporal())
644         return readTemporal(val, eType);
645      if (eType.isDuration())
646         return (T) readDuration(val);
647      if (eType.isPeriod())
648         return (T) readPeriod(val);
649
650      try {
651         return convertToType(val, eType);
652      } catch (@SuppressWarnings("unused") Exception e) {
653         throw new ParseException(this, "Could not convert Markdown cell value '%s' to type '%s'.", val, eType);
654      }
655   }
656
657   /**
658    * Returns true if the given ClassMeta requires the full JSON5 parsing machinery to be correctly
659    * instantiated — i.e., it has an ObjectSwap, cannot be created as a standard bean, or cannot be
660    * populated via direct property-setting through a BeanMap.
661    *
662    * <p>
663    * When this returns true, table rows and key-value tables should be converted to a JSON5 string
664    * and parsed via {@link Json5Parser} (using
665    * {@link Parser#readWithOuter}) to correctly handle swaps,
666    * {@link ParentProperty @ParentProperty}, and non-standard constructors.
667    */
668   private boolean needsJson5Path(ClassMeta<?> type) {
669      if (type == null || type.isObject() || type.isMap() || type.isPrimitive() || type.isNumber() || type.isString())
670         return false;
671      // If the type has an ObjectSwap, it cannot be parsed via BeanMap property-setting
672      if (type.getSwap(this) != null)
673         return true;
674      // If not a bean (no public properties), can't use BeanMap approach
675      return !type.isBean();
676   }
677
678   /**
679    * Converts a single Markdown table cell value to its JSON5 literal representation.
680    *
681    * <p>
682    * Inline JSON5 (backtick-wrapped) is unwrapped directly. Booleans and numbers are written bare.
683    * Everything else is single-quoted as a JSON5 string.
684    */
685   private String cellToJson5(String cell) {
686      if (cell == null || eq(cell, nullValue))
687         return "null";
688      cell = cell.trim();
689      if (cell.isEmpty())
690         return "''";
691      // Inline JSON5 wrapped in backticks — unwrap and embed directly
692      if (cell.startsWith("`") && cell.endsWith("`") && cell.length() > 1)
693         return cell.substring(1, cell.length() - 1);
694      // Unescape Markdown table escaping first
695      cell = unescapeCell(cell);
696      // Booleans and numbers don't need quoting
697      if (eqa(cell, "true", "false"))
698         return cell;
699      try { Integer.parseInt(cell); return cell; } catch (@SuppressWarnings("unused") NumberFormatException ignored) { /* not int, try next */ }
700      try { Long.parseLong(cell); return cell; } catch (@SuppressWarnings("unused") NumberFormatException ignored) { /* not long, try next */ }
701      try { Double.parseDouble(cell); return cell; } catch (@SuppressWarnings("unused") NumberFormatException ignored) { /* not double, quote as string */ }
702      // String: single-quote with escaping for JSON5
703      return "'" + cell.replace("\\", "\\\\").replace("'", "\\'") + "'";
704   }
705
706   /**
707    * Converts a table row (headers + cells) into a JSON5 object string, suitable for parsing via
708    * {@link Json5Parser}.
709    *
710    * <p>
711    * Example: headers=["f1","f2"], cells=["a","2"] → <code>{f1:'a',f2:2}</code>
712    *
713    * <p>
714    * The {@code _type} column, if present, is included as-is (as a quoted string) so that the JSON5
715    * parser can perform type resolution via the bean dictionary.
716    */
717   private String rowToJson5(List<String> headers, List<String> cells) {
718      var sb = new StringBuilder("{");
719      var first = true;
720      for (var i = 0; i < headers.size(); i++) {
721         var header = headers.get(i);
722         var cell = i < cells.size() ? cells.get(i) : null;
723         if (!first) sb.append(",");
724         first = false;
725         sb.append(header).append(":");
726         if (eq(header, "_type")) {
727            // Keep _type as a quoted string so the JSON5 parser can resolve it
728            sb.append(cell == null ? "null" : "'" + cell + "'");
729         } else {
730            sb.append(cellToJson5(cell));
731         }
732      }
733      sb.append("}");
734      return sb.toString();
735   }
736
737   /**
738    * Converts a key-value table (list of [key, value] row lines) into a JSON5 object string.
739    */
740   private String keyValueTableToJson5(List<String> dataLines) {
741      var sb = new StringBuilder("{");
742      var first = true;
743      for (var line : dataLines) {
744         var cells = splitTableRow(line);
745         if (cells.size() < 2)
746            continue;
747         var key = cells.get(0);
748         var val = cells.get(1);
749         if (!first) sb.append(",");
750         first = false;
751         sb.append(key).append(":");
752         if (eq(key, "_type")) {
753            sb.append(val == null ? "null" : "'" + val + "'");
754         } else {
755            sb.append(cellToJson5(val));
756         }
757      }
758      sb.append("}");
759      return sb.toString();
760   }
761
762   /**
763    * Splits a Markdown table row into its cell values, stripping leading/trailing whitespace and pipes.
764    *
765    * @param line The raw table row line.
766    * @return The list of trimmed cell values.
767    */
768   protected List<String> splitTableRow(String line) {
769      var trimmed = line.trim();
770      if (trimmed.startsWith("|"))
771         trimmed = trimmed.substring(1);
772      if (trimmed.endsWith("|") && (trimmed.length() < 2 || trimmed.charAt(trimmed.length() - 2) != '\\'))
773         trimmed = trimmed.substring(0, trimmed.length() - 1);
774
775      // Split on unescaped pipe characters
776      var result = new ArrayList<String>();
777      var sb = new StringBuilder();
778      var i = 0;
779      while (i < trimmed.length()) {
780         var c = trimmed.charAt(i);
781         if (c == '\\' && i + 1 < trimmed.length()) {
782            var next = trimmed.charAt(i + 1);
783            if (next == '|' || next == '\\') {
784               sb.append('\\');
785               sb.append(next);
786               i += 2;
787               continue;
788            }
789         }
790         if (c == '|') {
791            result.add(sb.toString().trim());
792            sb.setLength(0);
793         } else {
794            sb.append(c);
795         }
796         i++;
797      }
798      if (!sb.isEmpty() || !result.isEmpty())
799         result.add(sb.toString().trim());
800      return result;
801   }
802
803   /**
804    * Returns whether a table row is a separator row (e.g. {@code |---|---|}).
805    *
806    * @param line The table row line.
807    * @return Whether it is a separator row.
808    */
809   protected boolean isSeparatorRow(String line) {
810      var trimmed = line.trim();
811      if (!trimmed.startsWith("|"))
812         return false;
813      // Equivalent of trimmed.replaceAll("[|\\-: ]", "").isEmpty(): true iff every char is one of | - : space.
814      for (var i = 0; i < trimmed.length(); i++) {
815         var c = trimmed.charAt(i);
816         if (c != '|' && c != '-' && c != ':' && c != ' ')
817            return false;
818      }
819      return true;
820   }
821
822   /**
823    * Reads all lines from the given reader.
824    *
825    * @param r The reader.
826    *    <br>Must not be <jk>null</jk>.
827    * @return All lines.
828    * @throws IOException Thrown by underlying stream.
829    */
830   protected List<String> readAllLines(BufferedReader r) throws IOException {
831      var lines = new ArrayList<String>();
832      String line;
833      while ((line = r.readLine()) != null)
834         lines.add(line);
835      return lines;
836   }
837
838   /**
839    * Unescapes Markdown table cell escape sequences.
840    *
841    * @param s The escaped cell value.
842    *    <br>Can be <jk>null</jk> (returns <jk>null</jk>).
843    * @return The unescaped value.  Returns <jk>null</jk> if the input was <jk>null</jk>.
844    */
845   protected String unescapeCell(String s) {
846      if (s == null || !s.contains("\\"))
847         return s;
848      var sb = new StringBuilder(s.length());
849      var i = 0;
850      while (i < s.length()) {
851         var c = s.charAt(i);
852         if (c == '\\' && i + 1 < s.length()) {
853            var next = s.charAt(i + 1);
854            if (next == '|' || next == '\\') {
855               sb.append(next);
856               i += 2;
857               continue;
858            }
859         }
860         sb.append(c);
861         i++;
862      }
863      return sb.toString();
864   }
865}