-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathStandardCompiler.cpp
1786 lines (1567 loc) · 63.5 KB
/
StandardCompiler.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Alex Beregszaszi
* @date 2016
* Standard JSON compiler interface.
*/
#include <libsolidity/interface/StandardCompiler.h>
#include <libsolidity/interface/ImportRemapper.h>
#include <libsolidity/ast/ASTJsonExporter.h>
#include <libyul/YulStack.h>
#include <libyul/Exceptions.h>
#include <libyul/optimiser/Suite.h>
#include <libevmasm/Disassemble.h>
#include <libevmasm/EVMAssemblyStack.h>
#include <libsmtutil/Exceptions.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsolutil/JSON.h>
#include <libsolutil/Keccak256.h>
#include <libsolutil/CommonData.h>
#include <boost/algorithm/string/predicate.hpp>
#include <algorithm>
#include <optional>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::frontend;
using namespace solidity::langutil;
using namespace solidity::util;
using namespace std::string_literals;
namespace
{
Json formatError(
Error::Type _type,
std::string const& _component,
std::string const& _message,
std::string const& _formattedMessage = "",
Json const& _sourceLocation = Json(),
Json const& _secondarySourceLocation = Json()
)
{
Json error;
error["type"] = Error::formatErrorType(_type);
error["component"] = _component;
error["severity"] = Error::formatErrorSeverityLowercase(Error::errorSeverity(_type));
error["message"] = _message;
error["formattedMessage"] = (_formattedMessage.length() > 0) ? _formattedMessage : _message;
if (_sourceLocation.is_object())
error["sourceLocation"] = _sourceLocation;
if (_secondarySourceLocation.is_array())
error["secondarySourceLocations"] = _secondarySourceLocation;
return error;
}
Json formatFatalError(Error::Type _type, std::string const& _message)
{
Json output;
output["errors"] = Json::array();
output["errors"].emplace_back(formatError(_type, "general", _message));
return output;
}
Json formatSourceLocation(SourceLocation const* location)
{
if (!location || !location->sourceName)
return Json();
Json sourceLocation;
sourceLocation["file"] = *location->sourceName;
sourceLocation["start"] = location->start;
sourceLocation["end"] = location->end;
return sourceLocation;
}
Json formatSecondarySourceLocation(SecondarySourceLocation const* _secondaryLocation)
{
if (!_secondaryLocation)
return Json();
Json secondarySourceLocation = Json::array();
for (auto const& location: _secondaryLocation->infos)
{
Json msg = formatSourceLocation(&location.second);
msg["message"] = location.first;
secondarySourceLocation.emplace_back(msg);
}
return secondarySourceLocation;
}
Json formatErrorWithException(
CharStreamProvider const& _charStreamProvider,
util::Exception const& _exception,
Error::Type _type,
std::string const& _component,
std::string const& _message,
std::optional<ErrorId> _errorId = std::nullopt
)
{
std::string message;
// TODO: consider enabling color
std::string formattedMessage = SourceReferenceFormatter::formatExceptionInformation(
_exception,
_type,
_charStreamProvider,
false // colored
);
if (std::string const* description = _exception.comment())
message = ((_message.length() > 0) ? (_message + ":") : "") + *description;
else
message = _message;
Json error = formatError(
_type,
_component,
message,
formattedMessage,
formatSourceLocation(boost::get_error_info<errinfo_sourceLocation>(_exception)),
formatSecondarySourceLocation(boost::get_error_info<errinfo_secondarySourceLocation>(_exception))
);
if (_errorId)
error["errorCode"] = std::to_string(_errorId.value().error);
return error;
}
/// Returns true iff @a _hash (hex with 0x prefix) is the Keccak256 hash of the binary data in @a _content.
bool hashMatchesContent(std::string const& _hash, std::string const& _content)
{
try
{
return util::h256(_hash) == util::keccak256(_content);
}
catch (util::BadHexCharacter const&)
{
return false;
}
}
bool isArtifactRequested(Json const& _outputSelection, std::string const& _artifact, bool _wildcardMatchesExperimental)
{
static std::set<std::string> experimental{"ir", "irAst", "irOptimized", "irOptimizedAst", "yulCFGJson"};
for (auto const& selectedArtifactJson: _outputSelection)
{
std::string const& selectedArtifact = selectedArtifactJson.get<std::string>();
if (
_artifact == selectedArtifact ||
boost::algorithm::starts_with(_artifact, selectedArtifact + ".")
)
return true;
else if (selectedArtifact == "*")
{
// TODO: yulCFGJson is only experimental now, so it should not be matched by "*".
if (_artifact == "yulCFGJson")
return false;
// "ir", "irOptimized" can only be matched by "*" if activated.
if (experimental.count(_artifact) == 0 || _wildcardMatchesExperimental)
return true;
}
}
return false;
}
///
/// @a _outputSelection is a JSON object containing a two-level hashmap, where the first level is the filename,
/// the second level is the contract name and the value is an array of artifact names to be requested for that contract.
/// @a _file is the current file
/// @a _contract is the current contract
/// @a _artifact is the current artifact name
///
/// @returns true if the @a _outputSelection has a match for the requested target in the specific file / contract.
///
/// In @a _outputSelection the use of '*' as a wildcard is permitted.
///
/// @TODO optimise this. Perhaps flatten the structure upfront.
///
bool isArtifactRequested(Json const& _outputSelection, std::string const& _file, std::string const& _contract, std::string const& _artifact, bool _wildcardMatchesExperimental)
{
if (!_outputSelection.is_object())
return false;
for (auto const& file: { _file, std::string("*") })
if (_outputSelection.contains(file) && _outputSelection[file].is_object())
{
/// For SourceUnit-level targets (such as AST) only allow empty name, otherwise
/// for Contract-level targets try both contract name and wildcard
std::vector<std::string> contracts{ _contract };
if (!_contract.empty())
contracts.emplace_back("*");
for (auto const& contract: contracts)
if (
_outputSelection[file].contains(contract) &&
_outputSelection[file][contract].is_array() &&
isArtifactRequested(_outputSelection[file][contract], _artifact, _wildcardMatchesExperimental)
)
return true;
}
return false;
}
bool isArtifactRequested(Json const& _outputSelection, std::string const& _file, std::string const& _contract, std::vector<std::string> const& _artifacts, bool _wildcardMatchesExperimental)
{
for (auto const& artifact: _artifacts)
if (isArtifactRequested(_outputSelection, _file, _contract, artifact, _wildcardMatchesExperimental))
return true;
return false;
}
/// @returns all artifact names of the EVM object, either for creation or deploy time.
std::vector<std::string> evmObjectComponents(std::string const& _objectKind)
{
solAssert(_objectKind == "bytecode" || _objectKind == "deployedBytecode", "");
std::vector<std::string> components{"", ".object", ".opcodes", ".sourceMap", ".functionDebugData", ".generatedSources", ".linkReferences"};
if (_objectKind == "deployedBytecode")
components.push_back(".immutableReferences");
return util::applyMap(components, [&](auto const& _s) { return "evm." + _objectKind + _s; });
}
/// @returns true if any binary was requested, i.e. we actually have to perform compilation.
bool isBinaryRequested(Json const& _outputSelection)
{
if (!_outputSelection.is_object())
return false;
// This does not include "evm.methodIdentifiers" on purpose!
static std::vector<std::string> const outputsThatRequireBinaries = std::vector<std::string>{
"*",
"ir", "irAst", "irOptimized", "irOptimizedAst", "yulCFGJson",
"evm.gasEstimates", "evm.legacyAssembly", "evm.assembly"
} + evmObjectComponents("bytecode") + evmObjectComponents("deployedBytecode");
for (auto const& fileRequests: _outputSelection)
for (auto const& requests: fileRequests)
for (auto const& output: outputsThatRequireBinaries)
if (isArtifactRequested(requests, output, false))
return true;
return false;
}
/// @returns true if EVM bytecode was requested, i.e. we have to run the old code generator.
bool isEvmBytecodeRequested(Json const& _outputSelection)
{
if (!_outputSelection.is_object())
return false;
static std::vector<std::string> const outputsThatRequireEvmBinaries = std::vector<std::string>{
"*",
"evm.gasEstimates", "evm.legacyAssembly", "evm.assembly"
} + evmObjectComponents("bytecode") + evmObjectComponents("deployedBytecode");
for (auto const& fileRequests: _outputSelection)
for (auto const& requests: fileRequests)
for (auto const& output: outputsThatRequireEvmBinaries)
if (isArtifactRequested(requests, output, false))
return true;
return false;
}
/// @returns The set of selected contracts, along with their compiler pipeline configuration, based
/// on outputs requested in the JSON. Translates wildcards to the ones understood by CompilerStack.
/// Note that as an exception, '*' does not yet match "ir", "irAst", "irOptimized" or "irOptimizedAst".
CompilerStack::ContractSelection pipelineConfig(
Json const& _jsonOutputSelection
)
{
if (!_jsonOutputSelection.is_object())
return {};
CompilerStack::ContractSelection contractSelection;
for (auto const& [sourceUnitName, jsonOutputSelectionForSource]: _jsonOutputSelection.items())
{
solAssert(jsonOutputSelectionForSource.is_object());
for (auto const& [contractName, jsonOutputSelectionForContract]: jsonOutputSelectionForSource.items())
{
solAssert(jsonOutputSelectionForContract.is_array());
CompilerStack::PipelineConfig pipelineForContract;
for (Json const& request: jsonOutputSelectionForContract)
{
solAssert(request.is_string());
pipelineForContract.irOptimization =
pipelineForContract.irOptimization ||
request == "irOptimized" ||
request == "irOptimizedAst" ||
request == "yulCFGJson";
pipelineForContract.irCodegen =
pipelineForContract.irCodegen ||
pipelineForContract.irOptimization ||
request == "ir" ||
request == "irAst";
pipelineForContract.bytecode = isEvmBytecodeRequested(_jsonOutputSelection);
}
std::string key = (sourceUnitName == "*") ? "" : sourceUnitName;
std::string value = (contractName == "*") ? "" : contractName;
contractSelection[key][value] = pipelineForContract;
}
}
return contractSelection;
}
Json formatLinkReferences(std::map<size_t, std::string> const& linkReferences)
{
Json ret = Json::object();
for (auto const& ref: linkReferences)
{
std::string const& fullname = ref.second;
// If the link reference does not contain a colon, assume that the file name is missing and
// the whole string represents the library name.
size_t colon = fullname.rfind(':');
std::string file = (colon != std::string::npos ? fullname.substr(0, colon) : "");
std::string name = (colon != std::string::npos ? fullname.substr(colon + 1) : fullname);
Json fileObject = ret.value(file, Json::object());
Json libraryArray = fileObject.value(name, Json::array());
Json entry;
entry["start"] = Json(ref.first);
entry["length"] = 20;
libraryArray.emplace_back(entry);
fileObject[name] = libraryArray;
ret[file] = fileObject;
}
return ret;
}
Json formatImmutableReferences(std::map<u256, evmasm::LinkerObject::ImmutableRefs> const& _immutableReferences)
{
Json ret = Json::object();
for (auto const& immutableReference: _immutableReferences)
{
auto const& [identifier, byteOffsets] = immutableReference.second;
Json array = Json::array();
for (size_t byteOffset: byteOffsets)
{
Json byteRange;
byteRange["start"] = Json::number_unsigned_t(byteOffset);
byteRange["length"] = Json::number_unsigned_t(32); // immutable references are currently always 32 bytes wide
array.emplace_back(byteRange);
}
ret[identifier] = array;
}
return ret;
}
Json collectEVMObject(
langutil::EVMVersion _evmVersion,
evmasm::LinkerObject const& _object,
std::string const* _sourceMap,
Json _generatedSources,
bool _runtimeObject,
std::function<bool(std::string)> const& _artifactRequested
)
{
Json output;
if (_artifactRequested("object"))
output["object"] = _object.toHex();
if (_artifactRequested("opcodes"))
output["opcodes"] = evmasm::disassemble(_object.bytecode, _evmVersion);
if (_artifactRequested("sourceMap"))
output["sourceMap"] = _sourceMap ? *_sourceMap : "";
if (_artifactRequested("functionDebugData"))
output["functionDebugData"] = StandardCompiler::formatFunctionDebugData(_object.functionDebugData);
if (_artifactRequested("linkReferences"))
output["linkReferences"] = formatLinkReferences(_object.linkReferences);
if (_runtimeObject && _artifactRequested("immutableReferences"))
output["immutableReferences"] = formatImmutableReferences(_object.immutableReferences);
if (_artifactRequested("generatedSources"))
output["generatedSources"] = std::move(_generatedSources);
return output;
}
std::optional<Json> checkKeys(Json const& _input, std::set<std::string> const& _keys, std::string const& _name)
{
if (!_input.empty() && !_input.is_object())
return formatFatalError(Error::Type::JSONError, "\"" + _name + "\" must be an object");
for (auto const& [member, _]: _input.items())
if (!_keys.count(member))
return formatFatalError(Error::Type::JSONError, "Unknown key \"" + member + "\"");
return std::nullopt;
}
std::optional<Json> checkRootKeys(Json const& _input)
{
static std::set<std::string> keys{"auxiliaryInput", "language", "settings", "sources"};
return checkKeys(_input, keys, "root");
}
std::optional<Json> checkSourceKeys(Json const& _input, std::string const& _name)
{
static std::set<std::string> keys{"content", "keccak256", "urls"};
return checkKeys(_input, keys, "sources." + _name);
}
std::optional<Json> checkAuxiliaryInputKeys(Json const& _input)
{
static std::set<std::string> keys{"smtlib2responses"};
return checkKeys(_input, keys, "auxiliaryInput");
}
std::optional<Json> checkSettingsKeys(Json const& _input)
{
static std::set<std::string> keys{"debug", "evmVersion", "eofVersion", "libraries", "metadata", "modelChecker", "optimizer", "outputSelection", "remappings", "stopAfter", "viaIR"};
return checkKeys(_input, keys, "settings");
}
std::optional<Json> checkModelCheckerSettingsKeys(Json const& _input)
{
static std::set<std::string> keys{"bmcLoopIterations", "contracts", "divModNoSlacks", "engine", "extCalls", "invariants", "printQuery", "showProvedSafe", "showUnproved", "showUnsupported", "solvers", "targets", "timeout"};
return checkKeys(_input, keys, "modelChecker");
}
std::optional<Json> checkOptimizerKeys(Json const& _input)
{
static std::set<std::string> keys{"details", "enabled", "runs"};
return checkKeys(_input, keys, "settings.optimizer");
}
std::optional<Json> checkOptimizerDetailsKeys(Json const& _input)
{
static std::set<std::string> keys{"peephole", "inliner", "jumpdestRemover", "orderLiterals", "deduplicate", "cse", "constantOptimizer", "yul", "yulDetails", "simpleCounterForLoopUncheckedIncrement"};
return checkKeys(_input, keys, "settings.optimizer.details");
}
std::optional<Json> checkOptimizerDetail(Json const& _details, std::string const& _name, bool& _setting)
{
if (_details.contains(_name))
{
if (!_details[_name].is_boolean())
return formatFatalError(Error::Type::JSONError, "\"settings.optimizer.details." + _name + "\" must be Boolean");
_setting = _details[_name].get<bool>();
}
return {};
}
std::optional<Json> checkOptimizerDetailSteps(Json const& _details, std::string const& _name, std::string& _optimiserSetting, std::string& _cleanupSetting, bool _runYulOptimizer)
{
if (_details.contains(_name))
{
if (_details[_name].is_string())
{
std::string const fullSequence = _details[_name].get<std::string>();
if (!_runYulOptimizer && !OptimiserSuite::isEmptyOptimizerSequence(fullSequence))
{
std::string errorMessage =
"If Yul optimizer is disabled, only an empty optimizerSteps sequence is accepted."
" Note that the empty optimizer sequence is properly denoted by \":\".";
return formatFatalError(Error::Type::JSONError, errorMessage);
}
try
{
yul::OptimiserSuite::validateSequence(_details[_name].get<std::string>());
}
catch (yul::OptimizerException const& _exception)
{
return formatFatalError(
Error::Type::JSONError,
"Invalid optimizer step sequence in \"settings.optimizer.details." + _name + "\": " + _exception.what()
);
}
auto const delimiterPos = fullSequence.find(":");
_optimiserSetting = fullSequence.substr(0, delimiterPos);
if (delimiterPos != std::string::npos)
_cleanupSetting = fullSequence.substr(delimiterPos + 1);
else
solAssert(_cleanupSetting == OptimiserSettings::DefaultYulOptimiserCleanupSteps);
}
else
return formatFatalError(Error::Type::JSONError, "\"settings.optimizer.details." + _name + "\" must be a string");
}
return {};
}
std::optional<Json> checkMetadataKeys(Json const& _input)
{
if (_input.is_object())
{
if (_input.contains("appendCBOR") && !_input["appendCBOR"].is_boolean())
return formatFatalError(Error::Type::JSONError, "\"settings.metadata.appendCBOR\" must be Boolean");
if (_input.contains("useLiteralContent") && !_input["useLiteralContent"].is_boolean())
return formatFatalError(Error::Type::JSONError, "\"settings.metadata.useLiteralContent\" must be Boolean");
static std::set<std::string> hashes{"ipfs", "bzzr1", "none"};
if (_input.contains("bytecodeHash") && !hashes.count(_input["bytecodeHash"].get<std::string>()))
return formatFatalError(Error::Type::JSONError, "\"settings.metadata.bytecodeHash\" must be \"ipfs\", \"bzzr1\" or \"none\"");
}
static std::set<std::string> keys{"appendCBOR", "useLiteralContent", "bytecodeHash"};
return checkKeys(_input, keys, "settings.metadata");
}
std::optional<Json> checkOutputSelection(Json const& _outputSelection)
{
if (!_outputSelection.empty() && !_outputSelection.is_object())
return formatFatalError(Error::Type::JSONError, "\"settings.outputSelection\" must be an object");
for (auto const& [sourceName, sourceVal]: _outputSelection.items())
{
if (!sourceVal.is_object())
return formatFatalError(
Error::Type::JSONError,
"\"settings.outputSelection." + sourceName + "\" must be an object"
);
for (auto const& [contractName, contractVal]: sourceVal.items())
{
if (!contractVal.is_array())
return formatFatalError(
Error::Type::JSONError,
"\"settings.outputSelection." +
sourceName +
"." +
contractName +
"\" must be a string array"
);
for (auto const& output: contractVal)
if (!output.is_string())
return formatFatalError(
Error::Type::JSONError,
"\"settings.outputSelection." +
sourceName +
"." +
contractName +
"\" must be a string array"
);
}
}
return std::nullopt;
}
/// Validates the optimizer settings and returns them in a parsed object.
/// On error returns the json-formatted error message.
std::variant<OptimiserSettings, Json> parseOptimizerSettings(Json const& _jsonInput)
{
if (auto result = checkOptimizerKeys(_jsonInput))
return *result;
OptimiserSettings settings = OptimiserSettings::minimal();
if (_jsonInput.contains("enabled"))
{
if (!_jsonInput["enabled"].is_boolean())
return formatFatalError(Error::Type::JSONError, "The \"enabled\" setting must be a Boolean.");
if (_jsonInput["enabled"].get<bool>())
settings = OptimiserSettings::standard();
}
if (_jsonInput.contains("runs"))
{
if (!_jsonInput["runs"].is_number_unsigned())
return formatFatalError(Error::Type::JSONError, "The \"runs\" setting must be an unsigned number.");
settings.expectedExecutionsPerDeployment = _jsonInput["runs"].get<size_t>();
}
if (_jsonInput.contains("details"))
{
Json const& details = _jsonInput["details"];
if (auto result = checkOptimizerDetailsKeys(details))
return *result;
if (auto error = checkOptimizerDetail(details, "peephole", settings.runPeephole))
return *error;
if (auto error = checkOptimizerDetail(details, "inliner", settings.runInliner))
return *error;
if (auto error = checkOptimizerDetail(details, "jumpdestRemover", settings.runJumpdestRemover))
return *error;
if (auto error = checkOptimizerDetail(details, "orderLiterals", settings.runOrderLiterals))
return *error;
if (auto error = checkOptimizerDetail(details, "deduplicate", settings.runDeduplicate))
return *error;
if (auto error = checkOptimizerDetail(details, "cse", settings.runCSE))
return *error;
if (auto error = checkOptimizerDetail(details, "constantOptimizer", settings.runConstantOptimiser))
return *error;
if (auto error = checkOptimizerDetail(details, "yul", settings.runYulOptimiser))
return *error;
if (auto error = checkOptimizerDetail(details, "simpleCounterForLoopUncheckedIncrement", settings.simpleCounterForLoopUncheckedIncrement))
return *error;
settings.optimizeStackAllocation = settings.runYulOptimiser;
if (details.contains("yulDetails"))
{
if (!settings.runYulOptimiser)
{
if (checkKeys(details["yulDetails"], {"optimizerSteps"}, "settings.optimizer.details.yulDetails"))
return formatFatalError(Error::Type::JSONError, "Only optimizerSteps can be set in yulDetails when Yul optimizer is disabled.");
if (auto error = checkOptimizerDetailSteps(details["yulDetails"], "optimizerSteps", settings.yulOptimiserSteps, settings.yulOptimiserCleanupSteps, settings.runYulOptimiser))
return *error;
return {std::move(settings)};
}
if (auto result = checkKeys(details["yulDetails"], {"stackAllocation", "optimizerSteps"}, "settings.optimizer.details.yulDetails"))
return *result;
if (auto error = checkOptimizerDetail(details["yulDetails"], "stackAllocation", settings.optimizeStackAllocation))
return *error;
if (auto error = checkOptimizerDetailSteps(details["yulDetails"], "optimizerSteps", settings.yulOptimiserSteps, settings.yulOptimiserCleanupSteps, settings.runYulOptimiser))
return *error;
}
}
return {std::move(settings)};
}
}
std::variant<StandardCompiler::InputsAndSettings, Json> StandardCompiler::parseInput(Json const& _input)
{
InputsAndSettings ret;
if (!_input.is_object())
return formatFatalError(Error::Type::JSONError, "Input is not a JSON object.");
if (auto result = checkRootKeys(_input))
return *result;
ret.language = _input.value<std::string>("language", "");
Json const& sources = _input.value<Json>("sources", Json());
if (!sources.is_object() && !sources.is_null())
return formatFatalError(Error::Type::JSONError, "\"sources\" is not a JSON object.");
if (sources.empty())
return formatFatalError(Error::Type::JSONError, "No input sources specified.");
ret.errors = Json::array();
ret.sources = Json::object();
if (ret.language == "Solidity" || ret.language == "Yul")
{
for (auto const& [sourceName, sourceValue]: sources.items())
{
std::string hash;
if (auto result = checkSourceKeys(sourceValue, sourceName))
return *result;
if (sourceValue.contains("keccak256") && sourceValue["keccak256"].is_string())
hash = sourceValue["keccak256"].get<std::string>();
if (sourceValue.contains("content") && sourceValue["content"].is_string())
{
std::string content = sourceValue["content"].get<std::string>();
if (!hash.empty() && !hashMatchesContent(hash, content))
ret.errors.emplace_back(formatError(
Error::Type::IOError,
"general",
"Mismatch between content and supplied hash for \"" + sourceName + "\""
));
else
ret.sources[sourceName] = content;
}
else if (sourceValue["urls"].is_array())
{
if (!m_readFile)
return formatFatalError(
Error::Type::JSONError, "No import callback supplied, but URL is requested."
);
std::vector<std::string> failures;
bool found = false;
for (auto const& url: sourceValue["urls"])
{
if (!url.is_string())
return formatFatalError(Error::Type::JSONError, "URL must be a string.");
ReadCallback::Result result = m_readFile(ReadCallback::kindString(ReadCallback::Kind::ReadFile), url.get<std::string>());
if (result.success)
{
if (!hash.empty() && !hashMatchesContent(hash, result.responseOrErrorMessage))
ret.errors.emplace_back(formatError(
Error::Type::IOError,
"general",
"Mismatch between content and supplied hash for \"" + sourceName + "\" at \"" + url.get<std::string>() + "\""
));
else
{
ret.sources[sourceName] = result.responseOrErrorMessage;
found = true;
break;
}
}
else
failures.push_back(
"Cannot import url (\"" + url.get<std::string>() + "\"): " + result.responseOrErrorMessage
);
}
for (auto const& failure: failures)
{
/// If the import succeeded, let mark all the others as warnings, otherwise all of them are errors.
ret.errors.emplace_back(formatError(
found ? Error::Type::Warning : Error::Type::IOError,
"general",
failure
));
}
}
else
return formatFatalError(Error::Type::JSONError, "Invalid input source specified.");
}
}
else if (ret.language == "SolidityAST")
{
for (auto const& [sourceName, sourceValue]: sources.items())
ret.sources[sourceName] = util::jsonCompactPrint(sourceValue);
}
else if (ret.language == "EVMAssembly")
{
for (auto const& [sourceName, sourceValue]: sources.items())
{
solAssert(sources.contains(sourceName));
if (
!sourceValue.contains("assemblyJson") ||
!sourceValue["assemblyJson"].is_object() ||
sourceValue.size() != 1
)
return formatFatalError(
Error::Type::JSONError,
"Invalid input source specified. Expected exactly one object, named 'assemblyJson', inside $.sources." + sourceName
);
ret.jsonSources[sourceName] = sourceValue["assemblyJson"];
}
if (ret.jsonSources.size() != 1)
return formatFatalError(
Error::Type::JSONError,
"EVMAssembly import only supports exactly one input file."
);
}
Json const& auxInputs = _input.value("auxiliaryInput", Json::object());
if (auto result = checkAuxiliaryInputKeys(auxInputs))
return *result;
if (!auxInputs.empty())
{
Json const& smtlib2Responses = auxInputs.value("smtlib2responses", Json::object());
if (!smtlib2Responses.empty())
{
if (!smtlib2Responses.is_object())
return formatFatalError(Error::Type::JSONError, "\"auxiliaryInput.smtlib2responses\" must be an object.");
for (auto const& [hashString, response]: smtlib2Responses.items())
{
util::h256 hash;
try
{
hash = util::h256(hashString);
}
catch (util::BadHexCharacter const&)
{
return formatFatalError(Error::Type::JSONError, "Invalid hex encoding of SMTLib2 auxiliary input.");
}
if (!response.is_string())
return formatFatalError(
Error::Type::JSONError,
"\"smtlib2Responses." + hashString + "\" must be a string."
);
ret.smtLib2Responses[hash] = response.get<std::string>();
}
}
}
Json const& settings = _input.value("settings", Json::object());
if (auto result = checkSettingsKeys(settings))
return *result;
if (settings.contains("stopAfter"))
{
if (!settings["stopAfter"].is_string())
return formatFatalError(Error::Type::JSONError, "\"settings.stopAfter\" must be a string.");
if (settings["stopAfter"].get<std::string>() != "parsing")
return formatFatalError(Error::Type::JSONError, "Invalid value for \"settings.stopAfter\". Only valid value is \"parsing\".");
ret.stopAfter = CompilerStack::State::Parsed;
}
if (settings.contains("viaIR"))
{
if (!settings["viaIR"].is_boolean())
return formatFatalError(Error::Type::JSONError, "\"settings.viaIR\" must be a Boolean.");
ret.viaIR = settings["viaIR"].get<bool>();
}
if (settings.contains("evmVersion"))
{
if (!settings["evmVersion"].is_string())
return formatFatalError(Error::Type::JSONError, "evmVersion must be a string.");
std::optional<langutil::EVMVersion> version = langutil::EVMVersion::fromString(settings["evmVersion"].get<std::string>());
if (!version)
return formatFatalError(Error::Type::JSONError, "Invalid EVM version requested.");
if (version < EVMVersion::constantinople())
ret.errors.emplace_back(formatError(
Error::Type::Warning,
"general",
"Support for EVM versions older than constantinople is deprecated and will be removed in the future."
));
ret.evmVersion = *version;
}
if (settings.contains("eofVersion"))
{
if (!settings["eofVersion"].is_number_unsigned())
return formatFatalError(Error::Type::JSONError, "eofVersion must be an unsigned integer.");
auto eofVersion = settings["eofVersion"].get<uint8_t>();
if (eofVersion != 1)
return formatFatalError(Error::Type::JSONError, "Invalid EOF version requested.");
ret.eofVersion = 1;
}
if (settings.contains("debug"))
{
if (auto result = checkKeys(settings["debug"], {"revertStrings", "debugInfo"}, "settings.debug"))
return *result;
if (settings["debug"].contains("revertStrings"))
{
if (!settings["debug"]["revertStrings"].is_string())
return formatFatalError(Error::Type::JSONError, "settings.debug.revertStrings must be a string.");
std::optional<RevertStrings> revertStrings = revertStringsFromString(settings["debug"]["revertStrings"].get<std::string>());
if (!revertStrings)
return formatFatalError(Error::Type::JSONError, "Invalid value for settings.debug.revertStrings.");
if (*revertStrings == RevertStrings::VerboseDebug)
return formatFatalError(
Error::Type::UnimplementedFeatureError,
"Only \"default\", \"strip\" and \"debug\" are implemented for settings.debug.revertStrings for now."
);
ret.revertStrings = *revertStrings;
}
if (settings["debug"].contains("debugInfo"))
{
if (!settings["debug"]["debugInfo"].is_array())
return formatFatalError(Error::Type::JSONError, "settings.debug.debugInfo must be an array.");
std::vector<std::string> components;
for (Json const& arrayValue: settings["debug"]["debugInfo"])
components.push_back(arrayValue.get<std::string>());
std::optional<DebugInfoSelection> debugInfoSelection = DebugInfoSelection::fromComponents(
components,
true /* _acceptWildcards */
);
if (!debugInfoSelection.has_value())
return formatFatalError(Error::Type::JSONError, "Invalid value in settings.debug.debugInfo.");
if (debugInfoSelection->snippet && !debugInfoSelection->location)
return formatFatalError(
Error::Type::JSONError,
"To use 'snippet' with settings.debug.debugInfo you must select also 'location'."
);
ret.debugInfoSelection = debugInfoSelection.value();
}
}
if (settings.contains("remappings") && !settings["remappings"].is_array())
return formatFatalError(Error::Type::JSONError, "\"settings.remappings\" must be an array of strings.");
for (auto const& remapping: settings.value("remappings", Json::object()))
{
if (!remapping.is_string())
return formatFatalError(Error::Type::JSONError, "\"settings.remappings\" must be an array of strings");
if (auto r = ImportRemapper::parseRemapping(remapping.get<std::string>()))
ret.remappings.emplace_back(std::move(*r));
else
return formatFatalError(Error::Type::JSONError, "Invalid remapping: \"" + remapping.get<std::string>() + "\"");
}
if (settings.contains("optimizer"))
{
auto optimiserSettings = parseOptimizerSettings(settings["optimizer"]);
if (std::holds_alternative<Json>(optimiserSettings))
return std::get<Json>(std::move(optimiserSettings)); // was an error
else
ret.optimiserSettings = std::get<OptimiserSettings>(std::move(optimiserSettings));
}
Json const& jsonLibraries = settings.value("libraries", Json::object());
if (!jsonLibraries.is_object())
return formatFatalError(Error::Type::JSONError, "\"libraries\" is not a JSON object.");
for (auto const& [sourceName, jsonSourceName]: jsonLibraries.items())
{
if (!jsonSourceName.is_object())
return formatFatalError(Error::Type::JSONError, "Library entry is not a JSON object.");
for (auto const& [library, libraryValue]: jsonSourceName.items())
{
if (!libraryValue.is_string())
return formatFatalError(Error::Type::JSONError, "Library address must be a string.");
std::string address = libraryValue.get<std::string>();
if (!boost::starts_with(address, "0x"))
return formatFatalError(
Error::Type::JSONError,
"Library address is not prefixed with \"0x\"."
);
if (address.length() != 42)
return formatFatalError(
Error::Type::JSONError,
"Library address is of invalid length."
);
try
{
ret.libraries[sourceName + ":" + library] = util::h160(address);
}
catch (util::BadHexCharacter const&)
{
return formatFatalError(
Error::Type::JSONError,
"Invalid library address (\"" + address + "\") supplied."
);
}
}
}
Json const& metadataSettings = settings.value("metadata", Json::object());
if (auto result = checkMetadataKeys(metadataSettings))
return *result;
solAssert(CompilerStack::defaultMetadataFormat() != CompilerStack::MetadataFormat::NoMetadata, "");
ret.metadataFormat =
metadataSettings.value("appendCBOR", Json(true)) ?
CompilerStack::defaultMetadataFormat() :
CompilerStack::MetadataFormat::NoMetadata;
ret.metadataLiteralSources =
metadataSettings.contains("useLiteralContent") &&
metadataSettings["useLiteralContent"].is_boolean() &&
metadataSettings["useLiteralContent"].get<bool>();
if (metadataSettings.contains("bytecodeHash"))
{
auto metadataHash = metadataSettings["bytecodeHash"].get<std::string>();
ret.metadataHash =
metadataHash == "ipfs" ?
CompilerStack::MetadataHash::IPFS :
metadataHash == "bzzr1" ?
CompilerStack::MetadataHash::Bzzr1 :
CompilerStack::MetadataHash::None;
if (ret.metadataFormat == CompilerStack::MetadataFormat::NoMetadata && ret.metadataHash != CompilerStack::MetadataHash::None)
return formatFatalError(
Error::Type::JSONError,
"When the parameter \"appendCBOR\" is set to false, the parameter \"bytecodeHash\" cannot be set to \"" +
metadataHash +
"\". The parameter \"bytecodeHash\" should either be skipped, or set to \"none\"."
);
}
Json const& outputSelection = settings.value("outputSelection", Json::object());
if (auto jsonError = checkOutputSelection(outputSelection))
return *jsonError;
ret.outputSelection = outputSelection;
if (ret.stopAfter != CompilerStack::State::CompilationSuccessful && isBinaryRequested(ret.outputSelection))