Skip to content

Commit 31aa67f

Browse files
authored
Merge pull request #640 from chriseth/globalPaths
Allow remappings to change depending on the context.
2 parents bc359af + 3150ab2 commit 31aa67f

File tree

8 files changed

+185
-94
lines changed

8 files changed

+185
-94
lines changed

docs/layout-of-source-files.rst

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ Source files can contain an arbitrary number of contract definitions and include
66

77
.. index:: source file, ! import
88

9+
.. _import:
10+
911
Importing other Source Files
1012
============================
1113

@@ -68,15 +70,20 @@ remappings so that e.g. ``github.com/ethereum/dapp-bin/library`` is remapped to
6870
``/usr/local/dapp-bin/library`` and the compiler will read the files from there. If
6971
remapping keys are prefixes of each other, the longest is tried first. This
7072
allows for a "fallback-remapping" with e.g. ``""`` maps to
71-
``"/usr/local/include/solidity"``.
73+
``"/usr/local/include/solidity"``. Furthermore, these remappings can
74+
depend on the context, which allows you to configure packages to
75+
import e.g. different versions of a library of the same name.
7276

7377
**solc**:
7478

75-
For solc (the commandline compiler), these remappings are provided as ``key=value``
76-
arguments, where the ``=value`` part is optional (and defaults to key in that
79+
For solc (the commandline compiler), these remappings are provided as
80+
``context:prefix=target`` arguments, where both the ``context:`` and the
81+
``=target`` parts are optional (where target defaults to prefix in that
7782
case). All remapping values that are regular files are compiled (including
7883
their dependencies). This mechanism is completely backwards-compatible (as long
79-
as no filename contains a =) and thus not a breaking change.
84+
as no filename contains = or :) and thus not a breaking change. All imports
85+
in files in or below the directory ``context`` that import a file that
86+
starts with ``prefix`` are redirected by replacing ``prefix`` by ``target``.
8087

8188
So as an example, if you clone
8289
``github.com/ethereum/dapp-bin/`` locally to ``/usr/local/dapp-bin``, you can use
@@ -92,6 +99,19 @@ and then run the compiler as
9299
93100
solc github.com/ethereum/dapp-bin/=/usr/local/dapp-bin/ source.sol
94101
102+
As a more complex example, suppose you rely on some module that uses a
103+
very old version of dapp-bin. That old version of dapp-bin is checked
104+
out at ``/usr/local/dapp-bin_old``, then you can use
105+
106+
.. code-block:: bash
107+
108+
solc module1:github.com/ethereum/dapp-bin/=/usr/local/dapp-bin/ \
109+
module2:github.com/ethereum/dapp-bin/=/usr/local/dapp-bin_old/ \
110+
source.sol
111+
112+
so that all imports in ``module2`` point to the old version but imports
113+
in ``module1`` get the new version.
114+
95115
Note that solc only allows you to include files from certain directories:
96116
They have to be in the directory (or subdirectory) of one of the explicitly
97117
specified source files or in the directory (or subdirectory) of a remapping

docs/miscellaneous.rst

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ Using ``solc --help`` provides you with an explanation of all options. The compi
108108
If you only want to compile a single file, you run it as ``solc --bin sourceFile.sol`` and it will print the binary. Before you deploy your contract, activate the optimizer while compiling using ``solc --optimize --bin sourceFile.sol``. If you want to get some of the more advanced output variants of ``solc``, it is probably better to tell it to output everything to separate files using ``solc -o outputDirectory --bin --ast --asm sourceFile.sol``.
109109

110110
The commandline compiler will automatically read imported files from the filesystem, but
111-
it is also possible to provide path redirects using ``prefix=path`` in the following way:
111+
it is also possible to provide path redirects using ``context:prefix=path`` in the following way:
112112

113113
::
114114

@@ -121,6 +121,10 @@ always matches). ``solc`` will not read files from the filesystem that lie outsi
121121
the remapping targets and outside of the directories where explicitly specified source
122122
files reside, so things like ``import "/etc/passwd";`` only work if you add ``=/`` as a remapping.
123123

124+
You can restrict remappings to only certain source files by prefixing a context.
125+
126+
The section on :ref:`import` provides more details on remappings.
127+
124128
If there are multiple matches due to remappings, the one with the longest common prefix is selected.
125129

126130
If your contracts use :ref:`libraries <libraries>`, you will notice that the bytecode contains substrings of the form ``__LibraryName______``. You can use ``solc`` as a linker meaning that it will insert the library addresses for you at those points:

libsolidity/interface/CompilerStack.cpp

Lines changed: 66 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,24 @@ CompilerStack::CompilerStack(bool _addStandardSources, ReadFileCallback const& _
6363
addSources(StandardSources, true); // add them as libraries
6464
}
6565

66+
void CompilerStack::setRemappings(vector<string> const& _remappings)
67+
{
68+
vector<Remapping> remappings;
69+
for (auto const& remapping: _remappings)
70+
{
71+
auto eq = find(remapping.begin(), remapping.end(), '=');
72+
if (eq == remapping.end())
73+
continue; // ignore
74+
auto colon = find(remapping.begin(), eq, ':');
75+
Remapping r;
76+
r.context = colon == eq ? string() : string(remapping.begin(), colon);
77+
r.prefix = colon == eq ? string(remapping.begin(), eq) : string(colon + 1, eq);
78+
r.target = string(eq + 1, remapping.end());
79+
remappings.push_back(r);
80+
}
81+
swap(m_remappings, remappings);
82+
}
83+
6684
void CompilerStack::reset(bool _keepSources, bool _addStandardSources)
6785
{
6886
m_parseSuccessful = false;
@@ -384,37 +402,72 @@ tuple<int, int, int, int> CompilerStack::positionFromSourceLocation(SourceLocati
384402
return make_tuple(++startLine, ++startColumn, ++endLine, ++endColumn);
385403
}
386404

387-
StringMap CompilerStack::loadMissingSources(SourceUnit const& _ast, std::string const& _path)
405+
StringMap CompilerStack::loadMissingSources(SourceUnit const& _ast, std::string const& _sourcePath)
388406
{
389407
StringMap newSources;
390408
for (auto const& node: _ast.nodes())
391409
if (ImportDirective const* import = dynamic_cast<ImportDirective*>(node.get()))
392410
{
393-
string path = absolutePath(import->path(), _path);
394-
import->annotation().absolutePath = path;
395-
if (m_sources.count(path) || newSources.count(path))
411+
string importPath = absolutePath(import->path(), _sourcePath);
412+
// The current value of `path` is the absolute path as seen from this source file.
413+
// We first have to apply remappings before we can store the actual absolute path
414+
// as seen globally.
415+
importPath = applyRemapping(importPath, _sourcePath);
416+
import->annotation().absolutePath = importPath;
417+
if (m_sources.count(importPath) || newSources.count(importPath))
396418
continue;
397-
string contents;
398-
string errorMessage;
399-
if (!m_readFile)
400-
errorMessage = "File not supplied initially.";
419+
420+
ReadFileResult result{false, string("File not supplied initially.")};
421+
if (m_readFile)
422+
result = m_readFile(importPath);
423+
424+
if (result.success)
425+
newSources[importPath] = result.contentsOrErrorMesage;
401426
else
402-
tie(contents, errorMessage) = m_readFile(path);
403-
if (!errorMessage.empty())
404427
{
405428
auto err = make_shared<Error>(Error::Type::ParserError);
406429
*err <<
407430
errinfo_sourceLocation(import->location()) <<
408-
errinfo_comment("Source not found: " + errorMessage);
431+
errinfo_comment("Source \"" + importPath + "\" not found: " + result.contentsOrErrorMesage);
409432
m_errors.push_back(std::move(err));
410433
continue;
411434
}
412-
else
413-
newSources[path] = contents;
414435
}
415436
return newSources;
416437
}
417438

439+
string CompilerStack::applyRemapping(string const& _path, string const& _context)
440+
{
441+
// Try to find the longest prefix match in all remappings that are active in the current context.
442+
auto isPrefixOf = [](string const& _a, string const& _b)
443+
{
444+
if (_a.length() > _b.length())
445+
return false;
446+
return std::equal(_a.begin(), _a.end(), _b.begin());
447+
};
448+
449+
size_t longestPrefix = 0;
450+
string longestPrefixTarget;
451+
for (auto const& redir: m_remappings)
452+
{
453+
// Skip if we already have a closer match.
454+
if (longestPrefix > 0 && redir.prefix.length() <= longestPrefix)
455+
continue;
456+
// Skip if redir.context is not a prefix of _context
457+
if (!isPrefixOf(redir.context, _context))
458+
continue;
459+
// Skip if the prefix does not match.
460+
if (!isPrefixOf(redir.prefix, _path))
461+
continue;
462+
463+
longestPrefix = redir.prefix.length();
464+
longestPrefixTarget = redir.target;
465+
}
466+
string path = longestPrefixTarget;
467+
path.append(_path.begin() + longestPrefix, _path.end());
468+
return path;
469+
}
470+
418471
void CompilerStack::resolveImports()
419472
{
420473
// topological sorting (depth first search) of the import graph, cutting potential cycles

libsolidity/interface/CompilerStack.h

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,15 +75,23 @@ enum class DocumentationType: uint8_t
7575
class CompilerStack: boost::noncopyable
7676
{
7777
public:
78-
/// File reading callback, should return a pair of content and error message (exactly one nonempty)
79-
/// for a given path.
80-
using ReadFileCallback = std::function<std::pair<std::string, std::string>(std::string const&)>;
78+
struct ReadFileResult
79+
{
80+
bool success;
81+
std::string contentsOrErrorMesage;
82+
};
83+
84+
/// File reading callback.
85+
using ReadFileCallback = std::function<ReadFileResult(std::string const&)>;
8186

8287
/// Creates a new compiler stack.
8388
/// @param _readFile callback to used to read files for import statements. Should return
8489
/// @param _addStandardSources Adds standard sources if @a _addStandardSources.
8590
explicit CompilerStack(bool _addStandardSources = true, ReadFileCallback const& _readFile = ReadFileCallback());
8691

92+
/// Sets path remappings in the format "context:prefix=target"
93+
void setRemappings(std::vector<std::string> const& _remappings);
94+
8795
/// Resets the compiler to a state where the sources are not parsed or even removed.
8896
void reset(bool _keepSources = false, bool _addStandardSources = true);
8997

@@ -209,6 +217,7 @@ class CompilerStack: boost::noncopyable
209217
/// @a m_readFile and stores the absolute paths of all imports in the AST annotations.
210218
/// @returns the newly loaded sources.
211219
StringMap loadMissingSources(SourceUnit const& _ast, std::string const& _path);
220+
std::string applyRemapping(std::string const& _path, std::string const& _context);
212221
void resolveImports();
213222
/// Checks whether there are libraries with the same name, reports that as an error and
214223
/// @returns false in this case.
@@ -226,7 +235,17 @@ class CompilerStack: boost::noncopyable
226235
Contract const& contract(std::string const& _contractName = "") const;
227236
Source const& source(std::string const& _sourceName = "") const;
228237

238+
struct Remapping
239+
{
240+
std::string context;
241+
std::string prefix;
242+
std::string target;
243+
};
244+
229245
ReadFileCallback m_readFile;
246+
/// list of path prefix remappings, e.g. mylibrary: github.com/ethereum = /usr/local/ethereum
247+
/// "context:prefix=target"
248+
std::vector<Remapping> m_remappings;
230249
bool m_parseSuccessful;
231250
std::map<std::string const, Source> m_sources;
232251
std::shared_ptr<GlobalContext> m_globalContext;

solc/CommandLineInterface.cpp

Lines changed: 34 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -318,36 +318,31 @@ void CommandLineInterface::readInputFilesAndConfigureRemappings()
318318
}
319319
}
320320
else
321-
for (string const& infile: m_args["input-file"].as<vector<string>>())
321+
for (string path: m_args["input-file"].as<vector<string>>())
322322
{
323-
auto eq = find(infile.begin(), infile.end(), '=');
324-
if (eq != infile.end())
325-
{
326-
string target(eq + 1, infile.end());
327-
m_remappings.push_back(make_pair(string(infile.begin(), eq), target));
328-
m_allowedDirectories.push_back(boost::filesystem::path(target).remove_filename());
329-
}
323+
auto eq = find(path.begin(), path.end(), '=');
324+
if (eq != path.end())
325+
path = string(eq + 1, path.end());
330326
else
331327
{
332-
auto path = boost::filesystem::path(infile);
333-
if (!boost::filesystem::exists(path))
328+
auto infile = boost::filesystem::path(path);
329+
if (!boost::filesystem::exists(infile))
334330
{
335331
cerr << "Skipping non existant input file \"" << infile << "\"" << endl;
336332
continue;
337333
}
338334

339-
if (!boost::filesystem::is_regular_file(path))
335+
if (!boost::filesystem::is_regular_file(infile))
340336
{
341337
cerr << "\"" << infile << "\" is not a valid file. Skipping" << endl;
342338
continue;
343339
}
344340

345-
m_sourceCodes[path.string()] = dev::contentsString(path.string());
346-
m_allowedDirectories.push_back(boost::filesystem::canonical(path).remove_filename());
341+
m_sourceCodes[infile.string()] = dev::contentsString(infile.string());
342+
path = boost::filesystem::canonical(infile).string();
347343
}
344+
m_allowedDirectories.push_back(boost::filesystem::path(path).remove_filename());
348345
}
349-
// Add empty remapping to try the path itself.
350-
m_remappings.push_back(make_pair(string(), string()));
351346
}
352347

353348
bool CommandLineInterface::parseLibraryOption(string const& _input)
@@ -534,67 +529,42 @@ bool CommandLineInterface::processInput()
534529
return link();
535530
}
536531

537-
function<pair<string,string>(string const&)> fileReader = [this](string const& _path)
532+
CompilerStack::ReadFileCallback fileReader = [this](string const& _path)
538533
{
539-
// Try to find the longest prefix match in all remappings. At the end, there will bean
540-
// empty remapping so that we also try the path itself, but any file should be either
541-
// in (a subdirectory of) the directory of an explicit source or a remapping target.
542-
int errorLevel = 0;
543-
size_t longestPrefix = 0;
544-
string bestMatchPath;
545-
for (auto const& redir: m_remappings)
534+
auto boostPath = boost::filesystem::path(_path);
535+
if (!boost::filesystem::exists(boostPath))
536+
return CompilerStack::ReadFileResult{false, "File not found."};
537+
boostPath = boost::filesystem::canonical(boostPath);
538+
bool isAllowed = false;
539+
for (auto const& allowedDir: m_allowedDirectories)
546540
{
547-
auto const& virt = redir.first;
548-
if (longestPrefix > 0 && virt.length() <= longestPrefix)
549-
continue;
550-
if (virt.length() > _path.length() || !std::equal(virt.begin(), virt.end(), _path.begin()))
551-
continue;
552-
string path = redir.second;
553-
path.append(_path.begin() + virt.length(), _path.end());
554-
auto boostPath = boost::filesystem::path(path);
555-
if (!boost::filesystem::exists(boostPath))
541+
// If dir is a prefix of boostPath, we are fine.
542+
if (
543+
std::distance(allowedDir.begin(), allowedDir.end()) <= std::distance(boostPath.begin(), boostPath.end()) &&
544+
std::equal(allowedDir.begin(), allowedDir.end(), boostPath.begin())
545+
)
556546
{
557-
errorLevel = max(errorLevel, 0);
558-
continue;
559-
}
560-
boostPath = boost::filesystem::canonical(boostPath);
561-
bool isAllowed = false;
562-
for (auto const& dir: m_allowedDirectories)
563-
{
564-
// If dir is a prefix of boostPath, we are fine.
565-
if (
566-
std::distance(dir.begin(), dir.end()) <= std::distance(boostPath.begin(), boostPath.end()) &&
567-
std::equal(dir.begin(), dir.end(), boostPath.begin())
568-
)
569-
{
570-
isAllowed = true;
571-
break;
572-
}
573-
}
574-
if (!isAllowed)
575-
errorLevel = max(errorLevel, 2);
576-
else if (!boost::filesystem::is_regular_file(boostPath))
577-
errorLevel = max(errorLevel, 1);
578-
else
579-
{
580-
longestPrefix = virt.length();
581-
bestMatchPath = path;
547+
isAllowed = true;
548+
break;
582549
}
583550
}
584-
if (!bestMatchPath.empty())
585-
return make_pair(m_sourceCodes[bestMatchPath] = dev::contentsString(bestMatchPath), string());
586-
if (errorLevel == 0)
587-
return make_pair(string(), string("File not found."));
588-
else if (errorLevel == 1)
589-
return make_pair(string(), string("Not a valid file."));
551+
if (!isAllowed)
552+
return CompilerStack::ReadFileResult{false, "File outside of allowed directories."};
553+
else if (!boost::filesystem::is_regular_file(boostPath))
554+
return CompilerStack::ReadFileResult{false, "Not a valid file."};
590555
else
591-
return make_pair(string(), string("File outside of allowed directories."));
556+
{
557+
auto contents = dev::contentsString(boostPath.string());
558+
m_sourceCodes[boostPath.string()] = contents;
559+
return CompilerStack::ReadFileResult{true, contents};
560+
}
592561
};
593562

594563
m_compiler.reset(new CompilerStack(m_args.count(g_argAddStandard) > 0, fileReader));
595564
auto scannerFromSourceName = [&](string const& _sourceName) -> solidity::Scanner const& { return m_compiler->scanner(_sourceName); };
596565
try
597566
{
567+
m_compiler->setRemappings(m_args["input-file"].as<vector<string>>());
598568
for (auto const& sourceCode: m_sourceCodes)
599569
m_compiler->addSource(sourceCode.first, sourceCode.second);
600570
// TODO: Perhaps we should not compile unless requested

solc/CommandLineInterface.h

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,6 @@ class CommandLineInterface
8585
boost::program_options::variables_map m_args;
8686
/// map of input files to source code strings
8787
std::map<std::string, std::string> m_sourceCodes;
88-
/// list of path prefix remappings, e.g. github.com/ethereum -> /usr/local/ethereum
89-
std::vector<std::pair<std::string, std::string>> m_remappings;
9088
/// list of allowed directories to read files from
9189
std::vector<boost::filesystem::path> m_allowedDirectories;
9290
/// map of library names to addresses

0 commit comments

Comments
 (0)