Home | History | Annotate | Download | only in elements
      1 /*
      2  * Copyright (C) 2017 The Android Open Source Project
      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 parser.elements
     18 
     19 import lexer.Token
     20 import lexer.TokenCategory
     21 import lexer.TokenGrammar
     22 import parser.peekPreviousToken
     23 import parser.peekToken
     24 import java.text.ParseException
     25 
     26 class AnnotationParser(iter: ListIterator<Token>, var shouldResetIterator: Boolean = false) : AbstractParser(iter) {
     27 
     28     lateinit var name: TokenGrammar
     29     lateinit var value: String
     30 
     31     init {
     32         parseTokens(scanTokens(iter))
     33         if (shouldResetIterator) resetIterator(iter)
     34     }
     35 
     36     override fun scanTokens(iter: ListIterator<Token>): List<Token> {
     37         val tokens = mutableListOf<Token>()
     38         //depending how called, queue up annotation
     39         if (peekToken(iter)?.identifier == TokenGrammar.AT) iter.next()
     40         if (peekPreviousToken(iter)?.category == TokenCategory.Annotation) iter.previous()
     41 
     42         if (peekToken(iter)!!.category != TokenCategory.Annotation)
     43             throw ParseException("Doc token sequence must begin with an annotation", this.indexStart)
     44 
     45         //just one token, info embedded
     46         tokens.add(iter.next())
     47         return tokens
     48     }
     49 
     50     override fun parseTokens(tokens: List<Token>) {
     51         val iter = tokens.listIterator()
     52         assert(peekToken(iter)!!.category == TokenCategory.Annotation)
     53         var token = iter.next()
     54 
     55         this.name = token.identifier
     56         this.value = parseAnnotationValue(token)
     57     }
     58 
     59     //capture text between parens
     60     private fun parseAnnotationValue(token: Token): String {
     61         return Regex(""".*\((.*)\).*""")
     62                 .matchEntire(token.value)
     63                 ?.groups?.get(1)
     64                 ?.value?.trim()
     65                 ?: ""
     66     }
     67 }