forked from sorbet/sorbet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
realmain.cc
657 lines (591 loc) · 25 KB
/
realmain.cc
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
#ifdef SORBET_REALMAIN_MIN
// minimal build to speedup compilation. Remove extra features
#else
#define FULL_BUILD_ONLY(X) X;
#include "core/proto/proto.h" // has to be included first as it violates our poisons
// intentional comment to stop from reformatting
#include "absl/debugging/symbolize.h"
#include "common/statsd/statsd.h"
#include "common/web_tracer_framework/tracing.h"
#include "main/autogen/autogen.h"
#include "main/autogen/autoloader.h"
#include "main/autogen/subclasses.h"
#include "main/lsp/LSPInput.h"
#include "main/lsp/LSPOutput.h"
#include "main/lsp/lsp.h"
#endif
#include "absl/strings/str_cat.h"
#include "common/FileOps.h"
#include "common/Timer.h"
#include "common/sort.h"
#include "core/Error.h"
#include "core/ErrorQueue.h"
#include "core/Files.h"
#include "core/Unfreeze.h"
#include "core/errors/errors.h"
#include "core/lsp/QueryResponse.h"
#include "core/serialize/serialize.h"
#include "main/pipeline/pipeline.h"
#include "main/realmain.h"
#include "payload/payload.h"
#include "resolver/resolver.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "version/version.h"
#include <csignal>
#include <poll.h>
namespace spd = spdlog;
using namespace std;
namespace sorbet::realmain {
shared_ptr<spd::logger> logger;
int returnCode;
shared_ptr<spd::sinks::ansicolor_stderr_sink_mt> make_stderrColorSink() {
auto color_sink = make_shared<spd::sinks::ansicolor_stderr_sink_mt>();
color_sink->set_color(spd::level::info, color_sink->white);
color_sink->set_color(spd::level::debug, color_sink->magenta);
color_sink->set_level(spd::level::info);
return color_sink;
}
shared_ptr<spd::sinks::ansicolor_stderr_sink_mt> stderrColorSink = make_stderrColorSink();
/*
* Workaround https://bugzilla.mindrot.org/show_bug.cgi?id=2863 ; We are
* commonly run under ssh with a controlmaster, and we write exclusively to
* STDERR in normal usage. If the client goes away, we can hang forever writing
* to a full pipe buffer on stderr.
*
* Workaround by monitoring for STDOUT to go away and self-HUPing.
*/
void startHUPMonitor() {
thread monitor([]() {
struct pollfd pfd;
setCurrentThreadName("HUPMonitor");
pfd.fd = 1; // STDOUT
pfd.events = 0;
pfd.revents = 0;
while (true) {
int rv = poll(&pfd, 1, -1);
if (rv <= 0) {
continue;
}
if ((pfd.revents & (POLLHUP | POLLERR)) != 0) {
// STDOUT has gone away; Exit via SIGHUP.
kill(getpid(), SIGHUP);
}
}
});
monitor.detach();
}
void addStandardMetrics() {
#ifndef SORBET_REALMAIN_MIN
prodCounterAdd("release.build_scm_commit_count", Version::build_scm_commit_count);
prodCounterAdd("release.build_timestamp",
chrono::duration_cast<std::chrono::seconds>(Version::build_timestamp.time_since_epoch()).count());
StatsD::addRusageStats();
#endif
}
core::StrictLevel levelMinusOne(core::StrictLevel level) {
switch (level) {
case core::StrictLevel::Ignore:
return core::StrictLevel::None;
case core::StrictLevel::False:
return core::StrictLevel::Ignore;
case core::StrictLevel::True:
return core::StrictLevel::False;
case core::StrictLevel::Strict:
return core::StrictLevel::True;
case core::StrictLevel::Strong:
return core::StrictLevel::Strict;
case core::StrictLevel::Max:
return core::StrictLevel::Strong;
default:
Exception::raise("Should never happen");
}
}
string levelToSigil(core::StrictLevel level) {
switch (level) {
case core::StrictLevel::None:
Exception::raise("Should never happen");
case core::StrictLevel::Internal:
Exception::raise("Should never happen");
case core::StrictLevel::Ignore:
return "ignore";
case core::StrictLevel::False:
return "false";
case core::StrictLevel::True:
return "true";
case core::StrictLevel::Strict:
return "strict";
case core::StrictLevel::Strong:
return "strong";
case core::StrictLevel::Max:
Exception::raise("Should never happen");
case core::StrictLevel::Autogenerated:
Exception::raise("Should never happen");
case core::StrictLevel::Stdlib:
return "__STDLIB_INTERNAL";
}
}
core::Loc findTyped(unique_ptr<core::GlobalState> &gs, core::FileRef file) {
auto source = file.data(*gs).source();
if (file.data(*gs).originalSigil == core::StrictLevel::None) {
if (source.length() >= 2 && source[0] == '#' && source[1] == '!') {
int newline = source.find("\n", 0);
return core::Loc(file, newline + 1, newline + 1);
}
return core::Loc(file, 0, 0);
}
size_t start = 0;
start = source.find("typed:", start);
if (start == string_view::npos) {
return core::Loc(file, 0, 0);
}
while (start >= 0 && source[start] != '#') {
--start;
}
auto end = start;
while (end < source.size() && source[end] != '\n') {
++end;
}
if (source[end] == '\n') {
++end;
}
return core::Loc(file, start, end);
}
#ifndef SORBET_REALMAIN_MIN
struct AutogenResult {
struct Serialized {
// Selectively populated based on print options
string strval;
string msgpack;
vector<string> classlist;
optional<autogen::Subclasses::Map> subclasses;
};
CounterState counters;
vector<pair<int, Serialized>> prints;
unique_ptr<autogen::DefTree> defTree = make_unique<autogen::DefTree>();
};
void runAutogen(core::Context ctx, options::Options &opts, const autogen::AutoloaderConfig &autoloaderCfg,
WorkerPool &workers, vector<ast::ParsedFile> &indexed) {
Timer timeit(logger, "autogen");
auto resultq = make_shared<BlockingBoundedQueue<AutogenResult>>(indexed.size());
auto fileq = make_shared<ConcurrentBoundedQueue<int>>(indexed.size());
for (int i = 0; i < indexed.size(); ++i) {
fileq->push(move(i), 1);
}
workers.multiplexJob("runAutogen", [&ctx, &opts, &indexed, &autoloaderCfg, fileq, resultq]() {
AutogenResult out;
int n = 0;
{
Timer timeit(logger, "autogenWorker");
int idx = 0;
for (auto result = fileq->try_pop(idx); !result.done(); result = fileq->try_pop(idx)) {
++n;
auto &tree = indexed[idx];
if (tree.file.data(ctx).isRBI()) {
continue;
}
auto pf = autogen::Autogen::generate(ctx, move(tree));
tree = move(pf.tree);
AutogenResult::Serialized serialized;
if (opts.print.Autogen.enabled) {
Timer timeit(logger, "autogenToString");
serialized.strval = pf.toString(ctx);
}
if (opts.print.AutogenMsgPack.enabled) {
Timer timeit(logger, "autogenToMsgpack");
serialized.msgpack = pf.toMsgpack(ctx, opts.autogenVersion);
}
if (opts.print.AutogenClasslist.enabled) {
Timer timeit(logger, "autogenClasslist");
serialized.classlist = pf.listAllClasses(ctx);
}
if (opts.print.AutogenSubclasses.enabled) {
Timer timeit(logger, "autogenSubclasses");
serialized.subclasses =
autogen::Subclasses::listAllSubclasses(ctx, pf, opts.autogenSubclassesAbsoluteIgnorePatterns,
opts.autogenSubclassesRelativeIgnorePatterns);
}
if (opts.print.AutogenAutoloader.enabled) {
Timer timeit(logger, "autogenNamedDefs");
autogen::DefTreeBuilder::addParsedFileDefinitions(ctx, autoloaderCfg, out.defTree, pf);
}
out.prints.emplace_back(make_pair(idx, serialized));
}
}
out.counters = getAndClearThreadCounters();
resultq->push(move(out), n);
});
autogen::DefTree root;
AutogenResult out;
vector<pair<int, AutogenResult::Serialized>> merged;
for (auto res = resultq->wait_pop_timed(out, chrono::seconds{1}, *logger); !res.done();
res = resultq->wait_pop_timed(out, chrono::seconds{1}, *logger)) {
if (!res.gotItem()) {
continue;
}
counterConsume(move(out.counters));
merged.insert(merged.end(), make_move_iterator(out.prints.begin()), make_move_iterator(out.prints.end()));
if (opts.print.AutogenAutoloader.enabled) {
Timer timeit(logger, "autogenAutoloaderDefTreeMerge");
root = autogen::DefTreeBuilder::merge(ctx, move(root), move(*out.defTree));
}
}
fast_sort(merged, [](const auto &lhs, const auto &rhs) -> bool { return lhs.first < rhs.first; });
for (auto &elem : merged) {
if (opts.print.Autogen.enabled) {
opts.print.Autogen.print(elem.second.strval);
}
if (opts.print.AutogenMsgPack.enabled) {
opts.print.AutogenMsgPack.print(elem.second.msgpack);
}
}
if (opts.print.AutogenAutoloader.enabled) {
{
Timer timeit(logger, "autogenAutoloaderPrune");
autogen::DefTreeBuilder::collapseSameFileDefs(ctx, autoloaderCfg, root);
}
{
Timer timeit(logger, "autogenAutoloaderWrite");
autogen::AutoloadWriter::writeAutoloads(ctx, autoloaderCfg, opts.print.AutogenAutoloader.outputPath, root);
}
}
if (opts.print.AutogenClasslist.enabled) {
Timer timeit(logger, "autogenClasslistPrint");
vector<string> mergedClasslist;
for (auto &el : merged) {
auto &v = el.second.classlist;
mergedClasslist.insert(mergedClasslist.end(), make_move_iterator(v.begin()), make_move_iterator(v.end()));
}
fast_sort(mergedClasslist);
auto last = unique(mergedClasslist.begin(), mergedClasslist.end());
opts.print.AutogenClasslist.fmt("{}\n", fmt::join(mergedClasslist.begin(), last, "\n"));
}
if (opts.print.AutogenSubclasses.enabled) {
Timer timeit(logger, "autogenSubclassesPrint");
// Merge the {Parent: Set{Child1, Child2}} maps from each thread
autogen::Subclasses::Map childMap;
for (const auto &el : merged) {
if (!el.second.subclasses) {
// File doesn't define any Child < Parent relationships
continue;
}
for (const auto &[parentName, children] : *el.second.subclasses) {
if (!parentName.empty()) {
childMap[parentName].entries.insert(children.entries.begin(), children.entries.end());
childMap[parentName].classKind = children.classKind;
}
}
}
vector<string> serializedDescendantsMap =
autogen::Subclasses::genDescendantsMap(childMap, opts.autogenSubclassesParents);
opts.print.AutogenSubclasses.fmt(
"{}\n", fmt::join(serializedDescendantsMap.begin(), serializedDescendantsMap.end(), "\n"));
}
}
#endif
int realmain(int argc, char *argv[]) {
#ifndef SORBET_REALMAIN_MIN
absl::InitializeSymbolizer(argv[0]);
#endif
returnCode = 0;
logger = make_shared<spd::logger>("console", stderrColorSink);
logger->set_level(spd::level::trace); // pass through everything, let the sinks decide
logger->set_pattern("%v");
fatalLogger = logger;
auto typeErrorsConsole = make_shared<spd::logger>("typeDiagnostics", stderrColorSink);
typeErrorsConsole->set_pattern("%v");
options::Options opts;
auto extensionProviders = sorbet::pipeline::semantic_extension::SemanticExtensionProvider::getProviders();
vector<unique_ptr<sorbet::pipeline::semantic_extension::SemanticExtension>> extensions;
options::readOptions(opts, extensions, argc, argv, extensionProviders, logger);
while (opts.waitForDebugger && !stopInDebugger()) {
// spin
}
if (opts.stdoutHUPHack) {
startHUPMonitor();
}
if (!opts.debugLogFile.empty()) {
// LSP could run for a long time. Rotate log files, and trim at 1 GiB. Keep around 3 log files.
// Cast first number to size_t to prevent integer multiplication.
// TODO(jvilk): Reduce size once LSP logging is less chunderous.
auto fileSink =
make_shared<spdlog::sinks::rotating_file_sink_mt>(opts.debugLogFile, ((size_t)1) * 1024 * 1024 * 1024, 3);
fileSink->set_level(spd::level::debug);
{ // replace console & fatal loggers
vector<spd::sink_ptr> sinks{stderrColorSink, fileSink};
auto combinedLogger = make_shared<spd::logger>("consoleAndFile", begin(sinks), end(sinks));
combinedLogger->flush_on(spdlog::level::err);
combinedLogger->set_level(spd::level::trace); // pass through everything, let the sinks decide
spd::register_logger(combinedLogger);
fatalLogger = combinedLogger;
logger = combinedLogger;
}
{ // replace type error logger
vector<spd::sink_ptr> sinks{stderrColorSink, fileSink};
auto combinedLogger = make_shared<spd::logger>("typeDiagnosticsAndFile", begin(sinks), end(sinks));
spd::register_logger(combinedLogger);
combinedLogger->set_level(spd::level::trace); // pass through everything, let the sinks decide
typeErrorsConsole = combinedLogger;
}
}
// Use a custom formatter so we don't get a default newline
switch (opts.logLevel) {
case 0:
stderrColorSink->set_level(spd::level::info);
break;
case 1:
stderrColorSink->set_level(spd::level::debug);
logger->set_pattern("[T%t][%Y-%m-%dT%T.%f] %v");
logger->debug("Debug logging enabled");
break;
default:
stderrColorSink->set_level(spd::level::trace);
logger->set_pattern("[T%t][%Y-%m-%dT%T.%f] %v");
logger->trace("Trace logging enabled");
break;
}
{
string argsConcat(argv[0]);
for (int i = 1; i < argc; i++) {
absl::StrAppend(&argsConcat, " ", argv[i]);
}
logger->debug("Running sorbet version {} with arguments: {}", Version::full_version_string, argsConcat);
if (!Version::isReleaseBuild && !opts.silenceDevMessage &&
std::getenv("SORBET_SILENCE_DEV_MESSAGE") == nullptr) {
logger->info("👋 Hey there! Heads up that this is not a release build of sorbet.\n"
"Release builds are faster and more well-supported by the Sorbet team.\n"
"Check out the README to learn how to build Sorbet in release mode.\n"
"To forcibly silence this error, either pass --silence-dev-message,\n"
"or set SORBET_SILENCE_DEV_MESSAGE=1 in your shell environment.\n");
}
}
unique_ptr<WorkerPool> workers = WorkerPool::create(opts.threads, *logger);
unique_ptr<core::GlobalState> gs =
make_unique<core::GlobalState>((make_shared<core::ErrorQueue>(*typeErrorsConsole, *logger)));
gs->pathPrefix = opts.pathPrefix;
gs->errorUrlBase = opts.errorUrlBase;
gs->semanticExtensions = move(extensions);
vector<ast::ParsedFile> indexed;
logger->trace("building initial global state");
unique_ptr<KeyValueStore> kvstore;
if (!opts.cacheDir.empty()) {
kvstore = make_unique<KeyValueStore>(Version::full_version_string, opts.cacheDir,
opts.skipRewriterPasses ? "nodsl" : "default");
}
payload::createInitialGlobalState(gs, opts, kvstore);
if (opts.silenceErrors) {
gs->silenceErrors = true;
}
if (opts.autocorrect) {
gs->autocorrect = true;
}
if (opts.suggestRuntimeProfiledType) {
gs->suggestRuntimeProfiledType = true;
}
if (opts.print.isAutogen()) {
gs->runningUnderAutogen = true;
}
if (opts.censorForSnapshotTests) {
gs->censorForSnapshotTests = true;
}
if (opts.sleepInSlowPath) {
gs->sleepInSlowPath = true;
}
if (opts.reserveMemKiB > 0) {
gs->reserveMemory(opts.reserveMemKiB);
}
for (auto code : opts.errorCodeWhiteList) {
gs->onlyShowErrorClass(code);
}
for (auto code : opts.errorCodeBlackList) {
gs->suppressErrorClass(code);
}
for (auto &plugin : opts.dslPluginTriggers) {
core::UnfreezeNameTable nameTableAccess(*gs);
gs->addDslPlugin(plugin.first, plugin.second);
}
gs->dslRubyExtraArgs = opts.dslRubyExtraArgs;
if (!opts.stripeMode) {
// Definitions in multiple locations interact poorly with autoloader this error is enforced in Stripe code.
if (opts.errorCodeWhiteList.empty()) {
gs->suppressErrorClass(core::errors::Namer::MultipleBehaviorDefs.code);
}
}
logger->trace("done building initial global state");
if (opts.runLSP) {
#ifndef SORBET_REALMAIN_MIN
gs->errorQueue->ignoreFlushes = true;
logger->debug("Starting sorbet version {} in LSP server mode. "
"Talk ‘\\r\\n’-separated JSON-RPC to me. "
"More details at https://microsoft.github.io/language-server-protocol/specification."
"If you're developing an LSP extension to some editor, make sure to run sorbet with `-v` flag,"
"it will enable outputing the LSP session to stderr(`Write: ` and `Read: ` log lines)",
Version::full_version_string);
auto output = make_shared<lsp::LSPStdout>(logger);
lsp::LSPLoop loop(move(gs), *workers, make_shared<lsp::LSPConfiguration>(opts, output, logger));
gs = loop.runLSP(make_shared<lsp::LSPFDInput>(logger, STDIN_FILENO)).value_or(nullptr);
#endif
} else {
Timer timeall(logger, "wall_time");
vector<core::FileRef> inputFiles;
logger->trace("Files: ");
{ inputFiles = pipeline::reserveFiles(gs, opts.inputFileNames); }
{
core::UnfreezeFileTable fileTableAccess(*gs);
if (!opts.inlineInput.empty()) {
prodCounterAdd("types.input.bytes", opts.inlineInput.size());
prodCounterInc("types.input.lines");
prodCounterInc("types.input.files");
auto input = opts.inlineInput;
if (core::File::fileSigil(opts.inlineInput) == core::StrictLevel::None) {
// put it at the end so as to not upset line numbers
input += "\n# typed: true";
}
auto file = gs->enterFile(string("-e"), input);
inputFiles.emplace_back(file);
}
}
{ indexed = pipeline::index(gs, inputFiles, opts, *workers, kvstore); }
payload::retainGlobalState(gs, opts, kvstore);
if (gs->runningUnderAutogen) {
#ifndef SORBET_REALMAIN_MIN
gs->suppressErrorClass(core::errors::Namer::MethodNotFound.code);
gs->suppressErrorClass(core::errors::Namer::RedefinitionOfMethod.code);
gs->suppressErrorClass(core::errors::Namer::ModuleKindRedefinition.code);
gs->suppressErrorClass(core::errors::Resolver::StubConstant.code);
core::MutableContext ctx(*gs, core::Symbols::root());
indexed = pipeline::name(*gs, move(indexed), opts);
autogen::AutoloaderConfig autoloaderCfg;
{
core::UnfreezeNameTable nameTableAccess(*gs);
core::UnfreezeSymbolTable symbolAccess(*gs);
vector<core::ErrorRegion> errs;
for (auto &tree : indexed) {
auto file = tree.file;
errs.emplace_back(*gs, file);
}
indexed = resolver::Resolver::runConstantResolution(ctx, move(indexed), *workers);
autoloaderCfg = autogen::AutoloaderConfig::enterConfig(*gs, opts.autoloaderConfig);
}
runAutogen(ctx, opts, autoloaderCfg, *workers, indexed);
#endif
} else {
indexed = move(pipeline::resolve(gs, move(indexed), opts, *workers).result());
indexed = move(pipeline::typecheck(gs, move(indexed), opts, *workers).result());
}
if (opts.suggestTyped) {
for (auto &tree : indexed) {
auto file = tree.file;
if (file.data(*gs).minErrorLevel() <= core::StrictLevel::Ignore) {
continue;
}
if (file.data(*gs).originalSigil > core::StrictLevel::Max) {
// don't change the sigil on "special" files
continue;
}
auto minErrorLevel = levelMinusOne(file.data(*gs).minErrorLevel());
if (file.data(*gs).originalSigil == minErrorLevel) {
continue;
}
auto loc = findTyped(gs, file);
if (auto e = gs->beginError(loc, core::errors::Infer::SuggestTyped)) {
auto sigil = levelToSigil(minErrorLevel);
e.setHeader("You could add `# typed: {}`", sigil);
e.replaceWith(fmt::format("Add `typed: {}` sigil", sigil), loc, "# typed: {}\n", sigil);
}
}
}
gs->errorQueue->flushErrors(true);
if (!opts.noErrorCount) {
gs->errorQueue->flushErrorCount();
}
if (opts.autocorrect) {
gs->errorQueue->flushAutocorrects(*gs, *opts.fs);
}
logger->trace("sorbet done");
if (!opts.storeState.empty()) {
gs->markAsPayload();
FileOps::write(opts.storeState.c_str(), core::serialize::Serializer::store(*gs));
}
auto untypedSources = getAndClearHistogram("untyped.sources");
if (opts.suggestSig) {
ENFORCE(sorbet::debug_mode);
vector<pair<string, int>> withNames;
long sum = 0;
for (auto e : untypedSources) {
withNames.emplace_back(core::SymbolRef(*gs, e.first).dataAllowingNone(*gs)->showFullName(*gs),
e.second);
sum += e.second;
}
fast_sort(withNames, [](const auto &lhs, const auto &rhs) -> bool { return lhs.second > rhs.second; });
for (auto &p : withNames) {
logger->error("Typing `{}` would impact {}% callsites({} out of {}).", p.first, p.second * 100.0 / sum,
p.second, sum);
}
}
}
#ifndef SORBET_REALMAIN_MIN
addStandardMetrics();
if (!opts.someCounters.empty()) {
if (opts.enableCounters) {
logger->error("Don't pass both --counters and --counter");
return 1;
}
logger->warn("" + getCounterStatistics(opts.someCounters));
}
if (opts.enableCounters) {
logger->warn("" + getCounterStatistics(Counters::ALL_COUNTERS));
} else {
logger->debug("" + getCounterStatistics(Counters::ALL_COUNTERS));
}
auto counters = getAndClearThreadCounters();
if (!opts.statsdHost.empty()) {
auto prefix = opts.statsdPrefix;
if (opts.runLSP) {
prefix += ".lsp";
}
StatsD::submitCounters(counters, opts.statsdHost, opts.statsdPort, prefix + ".counters");
}
if (!opts.webTraceFile.empty()) {
web_tracer_framework::Tracing::storeTraces(counters, opts.webTraceFile);
}
if (!opts.metricsFile.empty()) {
auto metrics = core::Proto::toProto(counters, opts.metricsPrefix);
string status;
if (gs->hadCriticalError()) {
status = "Error";
} else if (returnCode != 0) {
status = "Failure";
} else {
status = "Success";
}
metrics.set_repo(opts.metricsRepo);
metrics.set_branch(opts.metricsBranch);
metrics.set_sha(opts.metricsSha);
metrics.set_status(status);
auto json = core::Proto::toJSON(metrics);
// Create output directory if it doesn't exist
try {
opts.fs->writeFile(opts.metricsFile, json);
} catch (FileNotFoundException e) {
logger->error("Cannot write metrics file at `{}`", opts.metricsFile);
}
}
#endif
if (!gs || gs->hadCriticalError()) {
returnCode = 10;
} else if (returnCode == 0 && gs->totalErrors() > 0 && !opts.supressNonCriticalErrors) {
returnCode = 1;
}
opts.flushPrinters();
if (!sorbet::emscripten_build) {
// Let it go: leak memory so that we don't need to call destructors
for (auto &e : indexed) {
intentionallyLeakMemory(e.tree.release());
}
intentionallyLeakMemory(gs.release());
}
// je_malloc_stats_print(nullptr, nullptr, nullptr); // uncomment this to print jemalloc statistics
return returnCode;
}
} // namespace sorbet::realmain