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 "ResourceUtils.h"
18#include "ResourceValues.h"
19#include "compile/XmlIdCollector.h"
20#include "xml/XmlDom.h"
21
22#include <algorithm>
23#include <vector>
24
25namespace aapt {
26
27namespace {
28
29static bool cmpName(const SourcedResourceName& a, const ResourceNameRef& b) {
30    return a.name < b;
31}
32
33struct IdCollector : public xml::Visitor {
34    using xml::Visitor::visit;
35
36    std::vector<SourcedResourceName>* mOutSymbols;
37
38    IdCollector(std::vector<SourcedResourceName>* outSymbols) : mOutSymbols(outSymbols) {
39    }
40
41    void visit(xml::Element* element) override {
42        for (xml::Attribute& attr : element->attributes) {
43            ResourceNameRef name;
44            bool create = false;
45            if (ResourceUtils::tryParseReference(attr.value, &name, &create, nullptr)) {
46                if (create && name.type == ResourceType::kId) {
47                    auto iter = std::lower_bound(mOutSymbols->begin(), mOutSymbols->end(),
48                                                 name, cmpName);
49                    if (iter == mOutSymbols->end() || iter->name != name) {
50                        mOutSymbols->insert(iter, SourcedResourceName{ name.toResourceName(),
51                                                                       element->lineNumber });
52                    }
53                }
54            }
55        }
56
57        xml::Visitor::visit(element);
58    }
59};
60
61} // namespace
62
63bool XmlIdCollector::consume(IAaptContext* context, xml::XmlResource* xmlRes) {
64    xmlRes->file.exportedSymbols.clear();
65    IdCollector collector(&xmlRes->file.exportedSymbols);
66    xmlRes->root->accept(&collector);
67    return true;
68}
69
70} // namespace aapt
71