1cb93a386Sopenharmony_ci/*
2cb93a386Sopenharmony_ci * Copyright 2020 Google LLC
3cb93a386Sopenharmony_ci *
4cb93a386Sopenharmony_ci * Use of this source code is governed by a BSD-style license that can be
5cb93a386Sopenharmony_ci * found in the LICENSE file.
6cb93a386Sopenharmony_ci */
7cb93a386Sopenharmony_ci
8cb93a386Sopenharmony_ci#include "include/private/SkSLProgramElement.h"
9cb93a386Sopenharmony_ci#include "include/private/SkSLString.h"
10cb93a386Sopenharmony_ci#include "src/sksl/SkSLIntrinsicMap.h"
11cb93a386Sopenharmony_ci
12cb93a386Sopenharmony_cinamespace SkSL {
13cb93a386Sopenharmony_ci
14cb93a386Sopenharmony_civoid IntrinsicMap::insertOrDie(String key, std::unique_ptr<ProgramElement> element) {
15cb93a386Sopenharmony_ci    SkASSERT(fIntrinsics.find(key) == fIntrinsics.end());
16cb93a386Sopenharmony_ci    fIntrinsics[key] = Intrinsic{std::move(element), false};
17cb93a386Sopenharmony_ci}
18cb93a386Sopenharmony_ci
19cb93a386Sopenharmony_ciconst ProgramElement* IntrinsicMap::find(const String& key) {
20cb93a386Sopenharmony_ci    auto iter = fIntrinsics.find(key);
21cb93a386Sopenharmony_ci    if (iter == fIntrinsics.end()) {
22cb93a386Sopenharmony_ci        return fParent ? fParent->find(key) : nullptr;
23cb93a386Sopenharmony_ci    }
24cb93a386Sopenharmony_ci    return iter->second.fIntrinsic.get();
25cb93a386Sopenharmony_ci}
26cb93a386Sopenharmony_ci
27cb93a386Sopenharmony_ci// Only returns an intrinsic that isn't already marked as included, and then marks it.
28cb93a386Sopenharmony_ciconst ProgramElement* IntrinsicMap::findAndInclude(const String& key) {
29cb93a386Sopenharmony_ci    auto iter = fIntrinsics.find(key);
30cb93a386Sopenharmony_ci    if (iter == fIntrinsics.end()) {
31cb93a386Sopenharmony_ci        return fParent ? fParent->findAndInclude(key) : nullptr;
32cb93a386Sopenharmony_ci    }
33cb93a386Sopenharmony_ci    if (iter->second.fAlreadyIncluded) {
34cb93a386Sopenharmony_ci        return nullptr;
35cb93a386Sopenharmony_ci    }
36cb93a386Sopenharmony_ci    iter->second.fAlreadyIncluded = true;
37cb93a386Sopenharmony_ci    return iter->second.fIntrinsic.get();
38cb93a386Sopenharmony_ci}
39cb93a386Sopenharmony_ci
40cb93a386Sopenharmony_civoid IntrinsicMap::resetAlreadyIncluded() {
41cb93a386Sopenharmony_ci    for (auto& pair : fIntrinsics) {
42cb93a386Sopenharmony_ci        pair.second.fAlreadyIncluded = false;
43cb93a386Sopenharmony_ci    }
44cb93a386Sopenharmony_ci    if (fParent) {
45cb93a386Sopenharmony_ci        fParent->resetAlreadyIncluded();
46cb93a386Sopenharmony_ci    }
47cb93a386Sopenharmony_ci}
48cb93a386Sopenharmony_ci
49cb93a386Sopenharmony_ci} // namespace SkSL
50