1 /* 2 * Copyright (c) Meta Platforms, Inc. and affiliates. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.facebook.ktfmt.kdoc 18 19 object Escaping { 20 21 private const val SLASH_STAR_ESCAPE = "\u0004\u0005" 22 23 private const val STAR_SLASH_ESCAPE = "\u0005\u0004" 24 indexOfCommentEscapeSequencesnull25 fun indexOfCommentEscapeSequences(s: String) = 26 s.indexOfAny(listOf(SLASH_STAR_ESCAPE, STAR_SLASH_ESCAPE)) 27 28 /** 29 * kotlin-compiler's KDoc lexer doesn't correctly handle nested slash-star comments, so we escape 30 * them into tombstones, format, then unescape. 31 */ 32 fun escapeKDoc(s: String): String { 33 val startMarkerIndex = s.indexOf("/*") 34 val endMarkerIndex = s.lastIndexOf("*/") 35 36 if (startMarkerIndex == -1 || endMarkerIndex == -1) { 37 throw RuntimeException("KDoc with no /** and/or */") 38 } 39 40 return s.substring(0, startMarkerIndex + 3) + 41 s.substring(startMarkerIndex + 3, endMarkerIndex) 42 .replace("/*", SLASH_STAR_ESCAPE) 43 .replace("*/", STAR_SLASH_ESCAPE) + 44 s.substring(endMarkerIndex) 45 } 46 47 /** See [escapeKDoc]. */ unescapeKDocnull48 fun unescapeKDoc(s: String): String = 49 s.replace(SLASH_STAR_ESCAPE, "/*").replace(STAR_SLASH_ESCAPE, "*/") 50 } 51