Skip to content

Commit 07f8e77

Browse files
Optimize concatenation of flat parsers.
1 parent f729ecc commit 07f8e77

File tree

1 file changed

+30
-1
lines changed
  • core/common/src/internal/format/parser

1 file changed

+30
-1
lines changed

core/common/src/internal/format/parser/Parser.kt

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,36 @@ internal fun <T> List<ParserStructure<T>>.concat(): ParserStructure<T> {
128128
}
129129
}
130130

131-
return foldRight(ParserStructure(emptyList(), emptyList())) { parser, acc -> parser.simplifyAndAppend(acc) }
131+
var result = ParserStructure<T>(emptyList(), emptyList())
132+
val flatParsers = mutableListOf<List<ParserOperation<T>>>()
133+
134+
for (parser in this.asReversed()) {
135+
if (parser.followedBy.isEmpty()) {
136+
flatParsers.add(parser.operations)
137+
} else {
138+
if (flatParsers.isNotEmpty()) {
139+
val operations = buildList() {
140+
for (i in flatParsers.lastIndex downTo 0) {
141+
addAll(flatParsers[i])
142+
}
143+
}
144+
result = ParserStructure(operations, emptyList()).simplifyAndAppend(result)
145+
flatParsers.clear()
146+
}
147+
result = parser.simplifyAndAppend(result)
148+
}
149+
}
150+
151+
if (flatParsers.isNotEmpty()) {
152+
val operations = buildList {
153+
for (i in flatParsers.lastIndex downTo 0) {
154+
addAll(flatParsers[i])
155+
}
156+
}
157+
result = ParserStructure(operations, emptyList()).simplifyAndAppend(result)
158+
}
159+
160+
return result
132161
}
133162

134163
internal interface Copyable<Self> {

0 commit comments

Comments
 (0)