@@ -42,6 +42,21 @@ internal class ParserStructure<in Output>(
4242}
4343
4444internal fun <T > List<ParserStructure<T>>.concat (): ParserStructure <T > {
45+ /* *
46+ * Merges pending operations (base operations, number span, and unconditional modifications)
47+ * with a simplified parser structure.
48+ *
49+ * Invariant: this function should only be called when `simplifiedParserStructure.operations`
50+ * is non-empty. If the structure consists solely of alternatives (empty operations with
51+ * non-empty followedBy), this function should NOT be called.
52+ *
53+ * @param baseOperations Operations to prepend (already processed operations from this parser)
54+ * @param numberSpan Pending number consumers that need to be merged or added (`null` if none pending)
55+ * @param unconditionalModifications Operations that must execute after all others
56+ * @param simplifiedParserStructure The simplified parser structure to merge with (must have operations)
57+ *
58+ * @return A new parser structure with all operations merged and the alternatives from [simplifiedParserStructure]
59+ */
4560 fun mergeOperations (
4661 baseOperations : List <ParserOperation <T >>,
4762 numberSpan : List <NumberConsumer <T >>? ,
@@ -53,20 +68,24 @@ internal fun <T> List<ParserStructure<T>>.concat(): ParserStructure<T> {
5368 val mergedOperations = buildList {
5469 addAll(baseOperations)
5570 when {
71+ // No pending number span: just append all operations
5672 numberSpan == null -> {
5773 addAll(operationsToMerge)
5874 }
75+ // Merge the pending number span with the first operation if it's also a number span
5976 firstOperation is NumberSpanParserOperation -> {
6077 add(NumberSpanParserOperation (numberSpan + firstOperation.consumers))
6178 for (i in 1 .. operationsToMerge.lastIndex) {
6279 add(operationsToMerge[i])
6380 }
6481 }
82+ // Add the pending number span as a separate operation before the others
6583 else -> {
6684 add(NumberSpanParserOperation (numberSpan))
6785 addAll(operationsToMerge)
6886 }
6987 }
88+ // Unconditional modifications always go at the end of the branch
7089 addAll(unconditionalModifications)
7190 }
7291 return ParserStructure (mergedOperations, simplifiedParserStructure.followedBy)
0 commit comments