aboutsummaryrefslogtreecommitdiffstats
path: root/libyul/optimiser/NameDispenser.cpp
blob: 172e6907ab72dded76335f9a7b97e8bf2badbca1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
    This file is part of solidity.

    solidity is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    solidity is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * Optimiser component that can create new unique names.
 */

#include <libyul/optimiser/NameDispenser.h>

#include <libyul/optimiser/NameCollector.h>
#include <libyul/AsmData.h>
#include <libyul/Dialect.h>

using namespace std;
using namespace dev;
using namespace yul;

NameDispenser::NameDispenser(Dialect const& _dialect, Block const& _ast):
    NameDispenser(_dialect, NameCollector(_ast).names())
{
}

NameDispenser::NameDispenser(Dialect const& _dialect, set<YulString> _usedNames):
    m_dialect(_dialect),
    m_usedNames(std::move(_usedNames))
{
}

YulString NameDispenser::newName(YulString _nameHint, YulString _context)
{
    // Shortening rules: Use a suffix of _prefix and a prefix of _context.
    YulString prefix = _nameHint;

    if (!_context.empty())
        prefix = YulString{_context.str().substr(0, 10) + "_" + prefix.str()};

    return newNameInternal(prefix);
}

YulString NameDispenser::newNameInternal(YulString _nameHint)
{
    YulString name = _nameHint;
    while (name.empty() || m_usedNames.count(name) || m_dialect.builtin(name))
    {
        m_counter++;
        name = YulString(_nameHint.str() + "_" + to_string(m_counter));
    }
    m_usedNames.emplace(name);
    return name;
}