• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.files
18 
19 import lexer.Token
20 import lexer.TokenCategory
21 import lexer.TokenGrammar
22 import java.text.ParseException
23 
24 data class PackageInfo(val name: String, val version: Float)
25 
26 /**
27  * Find and parse package info. Throw error if it can't find a valid declarationParser format.
28  * Example format: package android.hardware.audio@2.0;
29  */
parsePackageInfonull30 fun parsePackageInfo(tokens: List<Token>): PackageInfo {
31     val iter: ListIterator<Token> = tokens.listIterator()
32     var token: Token
33 
34     while (iter.hasNext()) {
35         token = iter.next()
36 
37         if (token.identifier == TokenGrammar.PACKAGE) {
38             //collect namespace
39             val pkgNameToks = mutableListOf<Token>()
40             while (iter.hasNext()) {
41                 token = iter.next()
42                 if (token.identifier != TokenGrammar.AT && token.identifier != TokenGrammar.SEMICOLON) {
43                     pkgNameToks.add(token)
44                 } else {
45                     break
46                 }
47             }
48             val pkgName = pkgNameToks.map { it.value }.joinToString("")
49 
50             //step through format and test syntax
51             if (token.identifier != TokenGrammar.AT) break
52             token = iter.next()
53             if (token.category != TokenCategory.Number) break //version
54             val pkgVer = token.value.toFloat()
55             token = iter.next()
56             if (token.identifier != TokenGrammar.SEMICOLON) break
57 
58             //hooray, a proper package format
59             return PackageInfo(pkgName, pkgVer)
60         }
61     }
62     throw ParseException("Unable to find a valid package declaration", 0)
63 }