xref: /aosp_15_r20/external/ktfmt/core/src/main/java/com/facebook/ktfmt/kdoc/CommentType.kt (revision 5be3f65c8cf0e6db0a7e312df5006e8e93cdf9ec)
1 /*
2  * Copyright (c) Tor Norbye.
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 enum class CommentType(
20     /** The opening string of the comment. */
21     val prefix: String,
22     /** The closing string of the comment. */
23     val suffix: String,
24     /** For multi line comments, the prefix at each comment line after the first one. */
25     val linePrefix: String
26 ) {
27   KDOC("/**", "*/", " * "),
28   BLOCK("/*", "*/", ""),
29   LINE("//", "", "// ");
30 
31   /**
32    * The number of characters needed to fit a comment on a line: the prefix, suffix and a single
33    * space padding inside these.
34    */
singleLineOverheadnull35   fun singleLineOverhead(): Int {
36     return prefix.length + suffix.length + 1 + if (suffix.isEmpty()) 0 else 1
37   }
38 
39   /**
40    * The number of characters required in addition to the line comment for each line in a multi line
41    * comment.
42    */
lineOverheadnull43   fun lineOverhead(): Int {
44     return linePrefix.length
45   }
46 }
47 
isKDocCommentnull48 fun String.isKDocComment(): Boolean = startsWith("/**")
49 
50 fun String.isBlockComment(): Boolean = startsWith("/*") && !startsWith("/**")
51 
52 fun String.isLineComment(): Boolean = startsWith("//")
53 
54 fun String.commentType(): CommentType {
55   return if (isKDocComment()) {
56     CommentType.KDOC
57   } else if (isBlockComment()) {
58     CommentType.BLOCK
59   } else if (isLineComment()) {
60     CommentType.LINE
61   } else {
62     error("Not a comment: $this")
63   }
64 }
65