1/*
2 * Copyright (C) 2015 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#include "util/Maybe.h"
18#include "util/Util.h"
19#include "xml/XmlUtil.h"
20
21#include <string>
22
23namespace aapt {
24namespace xml {
25
26Maybe<ExtractedPackage> extractPackageFromNamespace(const std::u16string& namespaceUri) {
27    if (util::stringStartsWith<char16_t>(namespaceUri, kSchemaPublicPrefix)) {
28        StringPiece16 schemaPrefix = kSchemaPublicPrefix;
29        StringPiece16 package = namespaceUri;
30        package = package.substr(schemaPrefix.size(), package.size() - schemaPrefix.size());
31        if (package.empty()) {
32            return {};
33        }
34        return ExtractedPackage{ package.toString(), false /* isPrivate */ };
35
36    } else if (util::stringStartsWith<char16_t>(namespaceUri, kSchemaPrivatePrefix)) {
37        StringPiece16 schemaPrefix = kSchemaPrivatePrefix;
38        StringPiece16 package = namespaceUri;
39        package = package.substr(schemaPrefix.size(), package.size() - schemaPrefix.size());
40        if (package.empty()) {
41            return {};
42        }
43        return ExtractedPackage{ package.toString(), true /* isPrivate */ };
44
45    } else if (namespaceUri == kSchemaAuto) {
46        return ExtractedPackage{ std::u16string(), true /* isPrivate */ };
47    }
48    return {};
49}
50
51void transformReferenceFromNamespace(IPackageDeclStack* declStack,
52                                     const StringPiece16& localPackage, Reference* inRef) {
53    if (inRef->name) {
54        if (Maybe<ExtractedPackage> transformedPackage =
55                   declStack->transformPackageAlias(inRef->name.value().package, localPackage)) {
56            ExtractedPackage& extractedPackage = transformedPackage.value();
57            inRef->name.value().package = std::move(extractedPackage.package);
58
59            // If the reference was already private (with a * prefix) and the namespace is public,
60            // we keep the reference private.
61            inRef->privateReference |= extractedPackage.privateNamespace;
62        }
63    }
64}
65
66} // namespace xml
67} // namespace aapt
68