| 1 |
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors |
| 2 |
// Licensed under the MIT License: |
| 3 |
// |
| 4 |
// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 5 |
// of this software and associated documentation files (the "Software"), to deal |
| 6 |
// in the Software without restriction, including without limitation the rights |
| 7 |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8 |
// copies of the Software, and to permit persons to whom the Software is |
| 9 |
// furnished to do so, subject to the following conditions: |
| 10 |
// |
| 11 |
// The above copyright notice and this permission notice shall be included in |
| 12 |
// all copies or substantial portions of the Software. |
| 13 |
// |
| 14 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 19 |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 20 |
// THE SOFTWARE. |
| 21 |
|
| 22 |
#ifndef _GNU_SOURCE |
| 23 |
#define _GNU_SOURCE |
| 24 |
#endif |
| 25 |
|
| 26 |
#ifndef _FILE_OFFSET_BITS |
| 27 |
#define _FILE_OFFSET_BITS 64 |
| 28 |
// Request 64-bit off_t and ino_t, otherwise this code will break when either value exceeds 2^32. |
| 29 |
#endif |
| 30 |
|
| 31 |
#if _WIN32 |
| 32 |
#include <kj/win32-api-version.h> |
| 33 |
#endif |
| 34 |
|
| 35 |
#include "lexer.h" |
| 36 |
#include "parser.h" |
| 37 |
#include "compiler.h" |
| 38 |
#include "module-loader.h" |
| 39 |
#include "node-translator.h" |
| 40 |
#include <capnp/pretty-print.h> |
| 41 |
#include <capnp/schema.capnp.h> |
| 42 |
#include <kj/vector.h> |
| 43 |
#include <kj/io.h> |
| 44 |
#include <kj/miniposix.h> |
| 45 |
#include <kj/debug.h> |
| 46 |
#include "../message.h" |
| 47 |
#include <iostream> |
| 48 |
#include <kj/main.h> |
| 49 |
#include <kj/parse/char.h> |
| 50 |
#include <sys/stat.h> |
| 51 |
#include <sys/types.h> |
| 52 |
#include <capnp/serialize.h> |
| 53 |
#include <capnp/serialize-packed.h> |
| 54 |
#include <capnp/serialize-text.h> |
| 55 |
#include <capnp/compat/json.h> |
| 56 |
#include <errno.h> |
| 57 |
#include <stdlib.h> |
| 58 |
#include <kj/map.h> |
| 59 |
|
| 60 |
#if _WIN32 |
| 61 |
#include <process.h> |
| 62 |
#include <windows.h> |
| 63 |
#include <kj/windows-sanity.h> |
| 64 |
#undef CONST |
| 65 |
#else |
| 66 |
#include <sys/wait.h> |
| 67 |
#endif |
| 68 |
|
| 69 |
#if HAVE_CONFIG_H |
| 70 |
#include "config.h" |
| 71 |
#endif |
| 72 |
|
| 73 |
#ifndef VERSION |
| 74 |
#define VERSION "(unknown)" |
| 75 |
#endif |
| 76 |
|
| 77 |
namespace capnp { |
| 78 |
namespace compiler { |
| 79 |
|
| 80 |
static const char VERSION_STRING[] = "Cap'n Proto version " VERSION; |
| 81 |
|
| 82 |
class CompilerMain final: public GlobalErrorReporter { |
| 83 |
public: |
| 84 |
explicit CompilerMain(kj::ProcessContext& context) |
| 85 |
: context(context), disk(kj::newDiskFilesystem()), loader(*this) {} |
| 86 |
|
| 87 |
kj::MainFunc getMain() { |
| 88 |
if (context.getProgramName().endsWith("capnpc") || context.getProgramName().endsWith("capnpc.exe")) { |
| 89 |
kj::MainBuilder builder(context, VERSION_STRING, |
| 90 |
"Compiles Cap'n Proto schema files and generates corresponding source code in one or " |
| 91 |
"more languages."); |
| 92 |
addGlobalOptions(builder); |
| 93 |
addCompileOptions(builder); |
| 94 |
builder.addOption({'i', "generate-id"}, KJ_BIND_METHOD(*this, generateId), |
| 95 |
"Generate a new 64-bit unique ID for use in a Cap'n Proto schema."); |
| 96 |
return builder.build(); |
| 97 |
} else { |
| 98 |
kj::MainBuilder builder(context, VERSION_STRING, |
| 99 |
"Command-line tool for Cap'n Proto development and debugging."); |
| 100 |
builder.addSubCommand("compile", KJ_BIND_METHOD(*this, getCompileMain), |
| 101 |
"Generate source code from schema files.") |
| 102 |
.addSubCommand("id", KJ_BIND_METHOD(*this, getGenIdMain), |
| 103 |
"Generate a new unique ID.") |
| 104 |
.addSubCommand("convert", KJ_BIND_METHOD(*this, getConvertMain), |
| 105 |
"Convert messages between binary, text, JSON, etc.") |
| 106 |
.addSubCommand("decode", KJ_BIND_METHOD(*this, getDecodeMain), |
| 107 |
"DEPRECATED (use `convert`)") |
| 108 |
.addSubCommand("encode", KJ_BIND_METHOD(*this, getEncodeMain), |
| 109 |
"DEPRECATED (use `convert`)") |
| 110 |
.addSubCommand("eval", KJ_BIND_METHOD(*this, getEvalMain), |
| 111 |
"Evaluate a const from a schema file."); |
| 112 |
addGlobalOptions(builder); |
| 113 |
return builder.build(); |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
kj::MainFunc getCompileMain() { |
| 118 |
kj::MainBuilder builder(context, VERSION_STRING, |
| 119 |
"Compiles Cap'n Proto schema files and generates corresponding source code in one or " |
| 120 |
"more languages."); |
| 121 |
addGlobalOptions(builder); |
| 122 |
addCompileOptions(builder); |
| 123 |
return builder.build(); |
| 124 |
} |
| 125 |
|
| 126 |
kj::MainFunc getGenIdMain() { |
| 127 |
return kj::MainBuilder(context, VERSION_STRING, |
| 128 |
"Generates a new 64-bit unique ID for use in a Cap'n Proto schema.") |
| 129 |
.callAfterParsing(KJ_BIND_METHOD(*this, generateId)) |
| 130 |
.build(); |
| 131 |
} |
| 132 |
|
| 133 |
kj::MainFunc getConvertMain() { |
| 134 |
// Only parse the schemas we actually need for decoding. |
| 135 |
compileEagerness = Compiler::NODE; |
| 136 |
|
| 137 |
// Drop annotations since we don't need them. This avoids importing files like c++.capnp. |
| 138 |
annotationFlag = Compiler::DROP_ANNOTATIONS; |
| 139 |
|
| 140 |
kj::MainBuilder builder(context, VERSION_STRING, |
| 141 |
"Converts messages between formats. Reads a stream of messages from stdin in format " |
| 142 |
"<from> and writes them to stdout in format <to>. Valid formats are:\n" |
| 143 |
" binary standard binary format\n" |
| 144 |
" packed packed binary format (deflates zeroes)\n" |
| 145 |
" flat binary single segment, no segment table (rare)\n" |
| 146 |
" flat-packed flat and packed\n" |
| 147 |
" canonical canonicalized binary single segment, no segment table\n" |
| 148 |
" text schema language struct literal format\n" |
| 149 |
" json JSON format\n" |
| 150 |
"When using \"text\" or \"json\" format, you must specify <schema-file> and <type> " |
| 151 |
"(but they are ignored and can be omitted for binary-to-binary conversions). " |
| 152 |
"<type> names names a struct type defined in <schema-file>, which is the root type " |
| 153 |
"of the message(s)."); |
| 154 |
addGlobalOptions(builder); |
| 155 |
builder.addOption({"short"}, KJ_BIND_METHOD(*this, printShort), |
| 156 |
"Write text or JSON output in short (non-pretty) format. Each message will " |
| 157 |
"be printed on one line, without using whitespace to improve readability.") |
| 158 |
.addOptionWithArg({"segment-size"}, KJ_BIND_METHOD(*this, setSegmentSize), "<n>", |
| 159 |
"For binary output, sets the preferred segment size on the MallocMessageBuilder to <n> " |
| 160 |
"words and turns off heuristic growth. This flag is mainly useful " |
| 161 |
"for testing. Without it, each message will be written as a single " |
| 162 |
"segment.") |
| 163 |
.addOption({"quiet"}, KJ_BIND_METHOD(*this, setQuiet), |
| 164 |
"Do not print warning messages about the input being in the wrong format. " |
| 165 |
"Use this if you find the warnings are wrong (but also let us know so " |
| 166 |
"we can improve them).") |
| 167 |
.expectArg("<from>:<to>", KJ_BIND_METHOD(*this, setConversion)) |
| 168 |
.expectOptionalArg("<schema-file>", KJ_BIND_METHOD(*this, addSource)) |
| 169 |
.expectOptionalArg("<type>", KJ_BIND_METHOD(*this, setRootType)) |
| 170 |
.callAfterParsing(KJ_BIND_METHOD(*this, convert)); |
| 171 |
return builder.build(); |
| 172 |
} |
| 173 |
|
| 174 |
kj::MainFunc getDecodeMain() { |
| 175 |
// Only parse the schemas we actually need for decoding. |
| 176 |
compileEagerness = Compiler::NODE; |
| 177 |
|
| 178 |
// Drop annotations since we don't need them. This avoids importing files like c++.capnp. |
| 179 |
annotationFlag = Compiler::DROP_ANNOTATIONS; |
| 180 |
|
| 181 |
kj::MainBuilder builder(context, VERSION_STRING, |
| 182 |
"Decodes one or more encoded Cap'n Proto messages as text. The messages have root " |
| 183 |
"type <type> defined in <schema-file>. Messages are read from standard input and " |
| 184 |
"by default are expected to be in standard Cap'n Proto serialization format."); |
| 185 |
addGlobalOptions(builder); |
| 186 |
builder.addOption({"flat"}, KJ_BIND_METHOD(*this, codeFlat), |
| 187 |
"Interpret the input as one large single-segment message rather than a " |
| 188 |
"stream in standard serialization format. (Rarely used.)") |
| 189 |
.addOption({'p', "packed"}, KJ_BIND_METHOD(*this, codePacked), |
| 190 |
"Expect the input to be packed using standard Cap'n Proto packing, which " |
| 191 |
"deflates zero-valued bytes. (This reads messages written with " |
| 192 |
"capnp::writePackedMessage*() from <capnp/serialize-packed.h>. Do not use " |
| 193 |
"this for messages written with capnp::writeMessage*() from " |
| 194 |
"<capnp/serialize.h>.)") |
| 195 |
.addOption({"short"}, KJ_BIND_METHOD(*this, printShort), |
| 196 |
"Print in short (non-pretty) format. Each message will be printed on one " |
| 197 |
"line, without using whitespace to improve readability.") |
| 198 |
.addOption({"quiet"}, KJ_BIND_METHOD(*this, setQuiet), |
| 199 |
"Do not print warning messages about the input being in the wrong format. " |
| 200 |
"Use this if you find the warnings are wrong (but also let us know so " |
| 201 |
"we can improve them).") |
| 202 |
.expectArg("<schema-file>", KJ_BIND_METHOD(*this, addSource)) |
| 203 |
.expectArg("<type>", KJ_BIND_METHOD(*this, setRootType)) |
| 204 |
.callAfterParsing(KJ_BIND_METHOD(*this, decode)); |
| 205 |
return builder.build(); |
| 206 |
} |
| 207 |
|
| 208 |
kj::MainFunc getEncodeMain() { |
| 209 |
// Only parse the schemas we actually need for decoding. |
| 210 |
compileEagerness = Compiler::NODE; |
| 211 |
|
| 212 |
// Drop annotations since we don't need them. This avoids importing files like c++.capnp. |
| 213 |
annotationFlag = Compiler::DROP_ANNOTATIONS; |
| 214 |
|
| 215 |
kj::MainBuilder builder(context, VERSION_STRING, |
| 216 |
"Encodes one or more textual Cap'n Proto messages to binary. The messages have root " |
| 217 |
"type <type> defined in <schema-file>. Messages are read from standard input. Each " |
| 218 |
"message is a parenthesized struct literal, like the format used to specify constants " |
| 219 |
"and default values of struct type in the schema language. For example:\n" |
| 220 |
" (foo = 123, bar = \"hello\", baz = [true, false, true])\n" |
| 221 |
"The input may contain any number of such values; each will be encoded as a separate " |
| 222 |
"message.", |
| 223 |
|
| 224 |
"Note that the current implementation reads the entire input into memory before " |
| 225 |
"beginning to encode. A better implementation would read and encode one message at " |
| 226 |
"a time."); |
| 227 |
addGlobalOptions(builder); |
| 228 |
builder.addOption({"flat"}, KJ_BIND_METHOD(*this, codeFlat), |
| 229 |
"Expect only one input value, serializing it as a single-segment message " |
| 230 |
"with no framing.") |
| 231 |
.addOption({'p', "packed"}, KJ_BIND_METHOD(*this, codePacked), |
| 232 |
"Pack the output message with standard Cap'n Proto packing, which " |
| 233 |
"deflates zero-valued bytes. (This writes messages using " |
| 234 |
"capnp::writePackedMessage() from <capnp/serialize-packed.h>. Without " |
| 235 |
"this, capnp::writeMessage() from <capnp/serialize.h> is used.)") |
| 236 |
.addOptionWithArg({"segment-size"}, KJ_BIND_METHOD(*this, setSegmentSize), "<n>", |
| 237 |
"Sets the preferred segment size on the MallocMessageBuilder to <n> " |
| 238 |
"words and turns off heuristic growth. This flag is mainly useful " |
| 239 |
"for testing. Without it, each message will be written as a single " |
| 240 |
"segment.") |
| 241 |
.expectArg("<schema-file>", KJ_BIND_METHOD(*this, addSource)) |
| 242 |
.expectArg("<type>", KJ_BIND_METHOD(*this, setRootType)) |
| 243 |
.callAfterParsing(KJ_BIND_METHOD(*this, encode)); |
| 244 |
return builder.build(); |
| 245 |
} |
| 246 |
|
| 247 |
kj::MainFunc getEvalMain() { |
| 248 |
// Only parse the schemas we actually need for decoding. |
| 249 |
compileEagerness = Compiler::NODE; |
| 250 |
|
| 251 |
// Drop annotations since we don't need them. This avoids importing files like c++.capnp. |
| 252 |
annotationFlag = Compiler::DROP_ANNOTATIONS; |
| 253 |
|
| 254 |
// Default convert to text unless -o is given. |
| 255 |
convertTo = Format::TEXT; |
| 256 |
|
| 257 |
// When using `capnp eval`, type IDs don't really matter, because `eval` won't actually use |
| 258 |
// them for anything. When using Cap'n Proto an a config format -- the common use case for |
| 259 |
// `capnp eval` -- the exercise of adding a file ID to every file is pointless busy work. So, |
| 260 |
// we don't require it. |
| 261 |
loader.setFileIdsRequired(false); |
| 262 |
|
| 263 |
kj::MainBuilder builder(context, VERSION_STRING, |
| 264 |
"Prints (or encodes) the value of <name>, which must be defined in <schema-file>. " |
| 265 |
"<name> must refer to a const declaration, a field of a struct type (prints the default " |
| 266 |
"value), or a field or list element nested within some other value. Examples:\n" |
| 267 |
" capnp eval myschema.capnp MyType.someField\n" |
| 268 |
" capnp eval myschema.capnp someConstant\n" |
| 269 |
" capnp eval myschema.capnp someConstant.someField\n" |
| 270 |
" capnp eval myschema.capnp someConstant.someList[4]\n" |
| 271 |
" capnp eval myschema.capnp someConstant.someList[4].anotherField[1][2][3]\n" |
| 272 |
"Since consts can have complex struct types, and since you can define a const using " |
| 273 |
"import and variable substitution, this can be a convenient way to write text-format " |
| 274 |
"config files which are compiled to binary before deployment.", |
| 275 |
|
| 276 |
"By default the value is written in text format and can have any type. The -b, -p, " |
| 277 |
"and --flat flags specify binary output, in which case the const must be of struct " |
| 278 |
"type."); |
| 279 |
addGlobalOptions(builder); |
| 280 |
builder.addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, setEvalOutputFormat), |
| 281 |
"<format>", "Encode the output in the given format. See `capnp help convert` " |
| 282 |
"for a list of formats. Defaults to \"text\".") |
| 283 |
.addOption({'b', "binary"}, KJ_BIND_METHOD(*this, codeBinary), |
| 284 |
"same as -obinary") |
| 285 |
.addOption({"flat"}, KJ_BIND_METHOD(*this, codeFlat), |
| 286 |
"same as -oflat") |
| 287 |
.addOption({'p', "packed"}, KJ_BIND_METHOD(*this, codePacked), |
| 288 |
"same as -opacked") |
| 289 |
.addOption({"short"}, KJ_BIND_METHOD(*this, printShort), |
| 290 |
"If output format is text or JSON, write in short (non-pretty) format. The " |
| 291 |
"message will be printed on one line, without using whitespace to improve " |
| 292 |
"readability.") |
| 293 |
.expectArg("<schema-file>", KJ_BIND_METHOD(*this, addSource)) |
| 294 |
.expectArg("<name>", KJ_BIND_METHOD(*this, evalConst)); |
| 295 |
return builder.build(); |
| 296 |
} |
| 297 |
|
| 298 |
void addGlobalOptions(kj::MainBuilder& builder) { |
| 299 |
builder.addOptionWithArg({'I', "import-path"}, KJ_BIND_METHOD(*this, addImportPath), "<dir>", |
| 300 |
"Add <dir> to the list of directories searched for non-relative " |
| 301 |
"imports (ones that start with a '/').") |
| 302 |
.addOption({"no-standard-import"}, KJ_BIND_METHOD(*this, noStandardImport), |
| 303 |
"Do not add any default import paths; use only those specified by -I. " |
| 304 |
"Otherwise, typically /usr/include and /usr/local/include are added by " |
| 305 |
"default."); |
| 306 |
} |
| 307 |
|
| 308 |
void addCompileOptions(kj::MainBuilder& builder) { |
| 309 |
builder.addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, addOutput), "<lang>[:<dir>]", |
| 310 |
"Generate source code for language <lang> in directory <dir> " |
| 311 |
"(default: current directory). <lang> actually specifies a plugin " |
| 312 |
"to use. If <lang> is a simple word, the compiler searches for a plugin " |
| 313 |
"called 'capnpc-<lang>' in $PATH. If <lang> is a file path " |
| 314 |
"containing slashes, it is interpreted as the exact plugin " |
| 315 |
"executable file name, and $PATH is not searched. If <lang> is '-', " |
| 316 |
"the compiler dumps the request to standard output.") |
| 317 |
.addOptionWithArg({"src-prefix"}, KJ_BIND_METHOD(*this, addSourcePrefix), "<prefix>", |
| 318 |
"If a file specified for compilation starts with <prefix>, remove " |
| 319 |
"the prefix for the purpose of deciding the names of output files. " |
| 320 |
"For example, the following command:\n" |
| 321 |
" capnp compile --src-prefix=foo/bar -oc++:corge foo/bar/baz/qux.capnp\n" |
| 322 |
"would generate the files corge/baz/qux.capnp.{h,c++}.") |
| 323 |
.expectOneOrMoreArgs("<source>", KJ_BIND_METHOD(*this, addSource)) |
| 324 |
.callAfterParsing(KJ_BIND_METHOD(*this, generateOutput)); |
| 325 |
} |
| 326 |
|
| 327 |
// ===================================================================================== |
| 328 |
// shared options |
| 329 |
|
| 330 |
kj::MainBuilder::Validity addImportPath(kj::StringPtr path) { |
| 331 |
KJ_IF_MAYBE(dir, getSourceDirectory(path, false)) { |
| 332 |
loader.addImportPath(*dir); |
| 333 |
return true; |
| 334 |
} else { |
| 335 |
return "no such directory"; |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
kj::MainBuilder::Validity noStandardImport() { |
| 340 |
addStandardImportPaths = false; |
| 341 |
return true; |
| 342 |
} |
| 343 |
|
| 344 |
kj::MainBuilder::Validity addSource(kj::StringPtr file) { |
| 345 |
if (!compilerConstructed) { |
| 346 |
compiler = compilerSpace.construct(annotationFlag); |
| 347 |
compilerConstructed = true; |
| 348 |
} |
| 349 |
|
| 350 |
if (addStandardImportPaths) { |
| 351 |
static constexpr kj::StringPtr STANDARD_IMPORT_PATHS[] = { |
| 352 |
"/usr/local/include"_kj, |
| 353 |
"/usr/include"_kj, |
| 354 |
#ifdef CAPNP_INCLUDE_DIR |
| 355 |
KJ_CONCAT(CAPNP_INCLUDE_DIR, _kj), |
| 356 |
#endif |
| 357 |
}; |
| 358 |
for (auto path: STANDARD_IMPORT_PATHS) { |
| 359 |
KJ_IF_MAYBE(dir, getSourceDirectory(path, false)) { |
| 360 |
loader.addImportPath(*dir); |
| 361 |
} else { |
| 362 |
// ignore standard path that doesn't exist |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
addStandardImportPaths = false; |
| 367 |
} |
| 368 |
|
| 369 |
auto dirPathPair = interpretSourceFile(file); |
| 370 |
KJ_IF_MAYBE(module, loader.loadModule(dirPathPair.dir, dirPathPair.path)) { |
| 371 |
auto compiled = compiler->add(*module); |
| 372 |
compiler->eagerlyCompile(compiled.getId(), compileEagerness); |
| 373 |
sourceFiles.add(SourceFile { compiled.getId(), compiled, module->getSourceName(), &*module }); |
| 374 |
} else { |
| 375 |
return "no such file"; |
| 376 |
} |
| 377 |
|
| 378 |
return true; |
| 379 |
} |
| 380 |
|
| 381 |
public: |
| 382 |
// ===================================================================================== |
| 383 |
// "id" command |
| 384 |
|
| 385 |
kj::MainBuilder::Validity generateId() { |
| 386 |
context.exitInfo(kj::str("@0x", kj::hex(generateRandomId()))); |
| 387 |
KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT; |
| 388 |
} |
| 389 |
|
| 390 |
// ===================================================================================== |
| 391 |
// "compile" command |
| 392 |
|
| 393 |
kj::MainBuilder::Validity addOutput(kj::StringPtr spec) { |
| 394 |
KJ_IF_MAYBE(split, spec.findFirst(':')) { |
| 395 |
kj::StringPtr dir = spec.slice(*split + 1); |
| 396 |
auto plugin = spec.slice(0, *split); |
| 397 |
|
| 398 |
if (*split == 1 && (dir.startsWith("/") || dir.startsWith("\\"))) { |
| 399 |
// The colon is the second character and is immediately followed by a slash or backslash. |
| 400 |
// So, the user passed something like `-o c:/foo`. Is this a request to run the C plugin |
| 401 |
// and output to `/foo`? Or are we on Windows, and is this a request to run the plugin |
| 402 |
// `c:/foo`? |
| 403 |
KJ_IF_MAYBE(split2, dir.findFirst(':')) { |
| 404 |
// There are two colons. The first ':' was the second char, and was followed by '/' or |
| 405 |
// '\', e.g.: |
| 406 |
// capnp compile -o c:/foo.exe:bar |
| 407 |
// |
| 408 |
// In this case we can conclude that the second colon is actually meant to be the |
| 409 |
// plugin/location separator, and the first colon was simply signifying a drive letter. |
| 410 |
// |
| 411 |
// Proof by contradiction: |
| 412 |
// - Say that none of the colons were meant to be plugin/location separators; i.e. the |
| 413 |
// whole argument is meant to be a plugin indicator and the location defaults to ".". |
| 414 |
// -> In this case, the plugin path has two colons, which is not valid. |
| 415 |
// -> CONTRADICTION |
| 416 |
// - Say that the first colon was meant to be the plugin/location separator. |
| 417 |
// -> In this case, the second colon must be the drive letter separator for the |
| 418 |
// output location. |
| 419 |
// -> However, the output location begins with '/' or '\', which is not a drive letter. |
| 420 |
// -> CONTRADICTION |
| 421 |
// - Say that there are more colons beyond the first two, and one of these is meant to |
| 422 |
// be the plugin/location separator. |
| 423 |
// -> In this case, the plugin path has two or more colons, which is not valid. |
| 424 |
// -> CONTRADICTION |
| 425 |
// |
| 426 |
// We therefore conclude that the *second* colon is in fact the plugin/location separator. |
| 427 |
|
| 428 |
dir = dir.slice(*split2 + 1); |
| 429 |
plugin = spec.slice(0, *split2 + 2); |
| 430 |
#if _WIN32 |
| 431 |
} else { |
| 432 |
// The user wrote something like: |
| 433 |
// |
| 434 |
// capnp compile -o c:/foo/bar |
| 435 |
// |
| 436 |
// What does this mean? It depends on what system we're on. On a Unix system, the above |
| 437 |
// clearly is a request to run the `capnpc-c` plugin (perhaps to output C code) and write |
| 438 |
// to the directory /foo/bar. But on Windows, absolute paths do not start with '/', and |
| 439 |
// the above is actually a request to run the plugin `c:/foo/bar`, outputting to the |
| 440 |
// current directory. |
| 441 |
|
| 442 |
outputs.add(OutputDirective { spec.asArray(), nullptr }); |
| 443 |
return true; |
| 444 |
#endif |
| 445 |
} |
| 446 |
} |
| 447 |
|
| 448 |
struct stat stats; |
| 449 |
if (stat(dir.cStr(), &stats) < 0 || !S_ISDIR(stats.st_mode)) { |
| 450 |
return "output location is inaccessible or is not a directory"; |
| 451 |
} |
| 452 |
outputs.add(OutputDirective { plugin, disk->getCurrentPath().evalNative(dir) }); |
| 453 |
} else { |
| 454 |
outputs.add(OutputDirective { spec.asArray(), nullptr }); |
| 455 |
} |
| 456 |
|
| 457 |
return true; |
| 458 |
} |
| 459 |
|
| 460 |
kj::MainBuilder::Validity addSourcePrefix(kj::StringPtr prefix) { |
| 461 |
if (getSourceDirectory(prefix, true) == nullptr) { |
| 462 |
return "no such directory"; |
| 463 |
} else { |
| 464 |
return true; |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
kj::MainBuilder::Validity generateOutput() { |
| 469 |
if (hadErrors()) { |
| 470 |
// Skip output if we had any errors. |
| 471 |
return true; |
| 472 |
} |
| 473 |
|
| 474 |
// We require one or more sources and if they failed to compile we quit above, so this should |
| 475 |
// pass. (This assertion also guarantees that `compiler` has been initialized.) |
| 476 |
KJ_ASSERT(sourceFiles.size() > 0, "Shouldn't have gotten here without sources."); |
| 477 |
|
| 478 |
if (outputs.size() == 0) { |
| 479 |
return "no outputs specified"; |
| 480 |
} |
| 481 |
|
| 482 |
MallocMessageBuilder message; |
| 483 |
auto request = message.initRoot<schema::CodeGeneratorRequest>(); |
| 484 |
|
| 485 |
auto version = request.getCapnpVersion(); |
| 486 |
version.setMajor(CAPNP_VERSION_MAJOR); |
| 487 |
version.setMinor(CAPNP_VERSION_MINOR); |
| 488 |
version.setMicro(CAPNP_VERSION_MICRO); |
| 489 |
|
| 490 |
auto schemas = compiler->getLoader().getAllLoaded(); |
| 491 |
auto nodes = request.initNodes(schemas.size()); |
| 492 |
for (size_t i = 0; i < schemas.size(); i++) { |
| 493 |
nodes.setWithCaveats(i, schemas[i].getProto()); |
| 494 |
} |
| 495 |
|
| 496 |
request.adoptSourceInfo(compiler->getAllSourceInfo(message.getOrphanage())); |
| 497 |
|
| 498 |
auto requestedFiles = request.initRequestedFiles(sourceFiles.size()); |
| 499 |
for (size_t i = 0; i < sourceFiles.size(); i++) { |
| 500 |
auto requestedFile = requestedFiles[i]; |
| 501 |
requestedFile.setId(sourceFiles[i].id); |
| 502 |
requestedFile.setFilename(sourceFiles[i].name); |
| 503 |
requestedFile.adoptImports(compiler->getFileImportTable( |
| 504 |
*sourceFiles[i].module, Orphanage::getForMessageContaining(requestedFile))); |
| 505 |
// Populate FileSourceInfo with identifier resolutions, including type IDs and member details. |
| 506 |
auto fileSourceInfo = requestedFile.initFileSourceInfo(); |
| 507 |
const auto resolutions = sourceFiles[i].module->getResolutions(); |
| 508 |
auto identifiers = fileSourceInfo.initIdentifiers(resolutions.size()); |
| 509 |
for (size_t j = 0; j < resolutions.size(); j++) { |
| 510 |
auto identifier = identifiers[j]; |
| 511 |
identifier.setStartByte(resolutions[j].startByte); |
| 512 |
identifier.setEndByte(resolutions[j].endByte); |
| 513 |
KJ_SWITCH_ONEOF(resolutions[j].target) { |
| 514 |
KJ_CASE_ONEOF(type, Resolution::Type) { |
| 515 |
identifier.setTypeId(type.typeId); |
| 516 |
} |
| 517 |
KJ_CASE_ONEOF(member, Resolution::Member) { |
| 518 |
identifier.initMember(); |
| 519 |
auto identifier_member = identifier.getMember(); |
| 520 |
identifier_member.setParentTypeId(member.parentTypeId); |
| 521 |
identifier_member.setOrdinal(member.ordinal); |
| 522 |
} |
| 523 |
} |
| 524 |
} |
| 525 |
} |
| 526 |
|
| 527 |
for (auto& output: outputs) { |
| 528 |
if (kj::str(output.name) == "-") { |
| 529 |
writeMessageToFd(STDOUT_FILENO, message); |
| 530 |
continue; |
| 531 |
} |
| 532 |
|
| 533 |
int pipeFds[2]; |
| 534 |
KJ_SYSCALL(kj::miniposix::pipe(pipeFds)); |
| 535 |
|
| 536 |
kj::String exeName; |
| 537 |
bool shouldSearchPath = true; |
| 538 |
for (char c: output.name) { |
| 539 |
#if _WIN32 |
| 540 |
if (c == '/' || c == '\\') { |
| 541 |
#else |
| 542 |
if (c == '/') { |
| 543 |
#endif |
| 544 |
shouldSearchPath = false; |
| 545 |
break; |
| 546 |
} |
| 547 |
} |
| 548 |
if (shouldSearchPath) { |
| 549 |
exeName = kj::str("capnpc-", output.name); |
| 550 |
} else { |
| 551 |
exeName = kj::heapString(output.name); |
| 552 |
} |
| 553 |
|
| 554 |
kj::Array<char> pwd = kj::heapArray<char>(256); |
| 555 |
while (getcwd(pwd.begin(), pwd.size()) == nullptr) { |
| 556 |
KJ_REQUIRE(pwd.size() < 8192, "WTF your working directory path is more than 8k?"); |
| 557 |
pwd = kj::heapArray<char>(pwd.size() * 2); |
| 558 |
} |
| 559 |
|
| 560 |
#if _WIN32 |
| 561 |
int oldStdin; |
| 562 |
KJ_SYSCALL(oldStdin = dup(STDIN_FILENO)); |
| 563 |
intptr_t child; |
| 564 |
|
| 565 |
#else // _WIN32 |
| 566 |
pid_t child; |
| 567 |
KJ_SYSCALL(child = fork()); |
| 568 |
if (child == 0) { |
| 569 |
// I am the child! |
| 570 |
|
| 571 |
KJ_SYSCALL(close(pipeFds[1])); |
| 572 |
#endif // _WIN32, else |
| 573 |
|
| 574 |
KJ_SYSCALL(dup2(pipeFds[0], STDIN_FILENO)); |
| 575 |
KJ_SYSCALL(close(pipeFds[0])); |
| 576 |
|
| 577 |
KJ_IF_MAYBE(d, output.dir) { |
| 578 |
#if _WIN32 |
| 579 |
KJ_SYSCALL(SetCurrentDirectoryW(d->forWin32Api(true).begin()), d->toWin32String(true)); |
| 580 |
#else |
| 581 |
auto wd = d->toString(true); |
| 582 |
KJ_SYSCALL(chdir(wd.cStr()), wd); |
| 583 |
KJ_SYSCALL(setenv("PWD", wd.cStr(), true)); |
| 584 |
#endif |
| 585 |
} |
| 586 |
|
| 587 |
#if _WIN32 |
| 588 |
// MSVCRT's spawn*() don't correctly escape arguments, which is necessary on Windows |
| 589 |
// since the underlying system call takes a single command line string rather than |
| 590 |
// an arg list. We do the escaping ourselves by wrapping the name in quotes. We know |
| 591 |
// that exeName itself can't contain quotes (since filenames aren't allowed to contain |
| 592 |
// quotes on Windows), so we don't have to account for those. |
| 593 |
KJ_ASSERT(exeName.findFirst('\"') == nullptr, |
| 594 |
"Windows filenames can't contain quotes", exeName); |
| 595 |
auto escapedExeName = kj::str("\"", exeName, "\""); |
| 596 |
#endif |
| 597 |
|
| 598 |
if (shouldSearchPath) { |
| 599 |
#if _WIN32 |
| 600 |
child = _spawnlp(_P_NOWAIT, exeName.cStr(), escapedExeName.cStr(), nullptr); |
| 601 |
#else |
| 602 |
execlp(exeName.cStr(), exeName.cStr(), nullptr); |
| 603 |
#endif |
| 604 |
} else { |
| 605 |
#if _WIN32 |
| 606 |
if (!exeName.startsWith("/") && !exeName.startsWith("\\") && |
| 607 |
!(exeName.size() >= 2 && exeName[1] == ':')) { |
| 608 |
#else |
| 609 |
if (!exeName.startsWith("/")) { |
| 610 |
#endif |
| 611 |
// The name is relative. Prefix it with our original working directory path. |
| 612 |
exeName = kj::str(pwd.begin(), "/", exeName); |
| 613 |
} |
| 614 |
|
| 615 |
#if _WIN32 |
| 616 |
child = _spawnl(_P_NOWAIT, exeName.cStr(), escapedExeName.cStr(), nullptr); |
| 617 |
#else |
| 618 |
execl(exeName.cStr(), exeName.cStr(), nullptr); |
| 619 |
#endif |
| 620 |
} |
| 621 |
|
| 622 |
#if _WIN32 |
| 623 |
if (child == -1) { |
| 624 |
#endif |
| 625 |
int error = errno; |
| 626 |
if (error == ENOENT) { |
| 627 |
context.exitError(kj::str(output.name, ": no such plugin (executable should be '", |
| 628 |
exeName, "')")); |
| 629 |
} else { |
| 630 |
#if _WIN32 |
| 631 |
KJ_FAIL_SYSCALL("spawn()", error); |
| 632 |
#else |
| 633 |
KJ_FAIL_SYSCALL("exec()", error); |
| 634 |
#endif |
| 635 |
} |
| 636 |
#if _WIN32 |
| 637 |
} |
| 638 |
|
| 639 |
// Restore stdin. |
| 640 |
KJ_SYSCALL(dup2(oldStdin, STDIN_FILENO)); |
| 641 |
KJ_SYSCALL(close(oldStdin)); |
| 642 |
|
| 643 |
// Restore current directory. |
| 644 |
KJ_SYSCALL(chdir(pwd.begin()), pwd.begin()); |
| 645 |
#else // _WIN32 |
| 646 |
} |
| 647 |
|
| 648 |
KJ_SYSCALL(close(pipeFds[0])); |
| 649 |
#endif // _WIN32, else |
| 650 |
|
| 651 |
writeMessageToFd(pipeFds[1], message); |
| 652 |
KJ_SYSCALL(close(pipeFds[1])); |
| 653 |
|
| 654 |
#if _WIN32 |
| 655 |
int status; |
| 656 |
if (_cwait(&status, child, 0) == -1) { |
| 657 |
KJ_FAIL_SYSCALL("_cwait()", errno); |
| 658 |
} |
| 659 |
|
| 660 |
if (status != 0) { |
| 661 |
context.error(kj::str(output.name, ": plugin failed: exit code ", status)); |
| 662 |
} |
| 663 |
|
| 664 |
#else // _WIN32 |
| 665 |
int status; |
| 666 |
KJ_SYSCALL(waitpid(child, &status, 0)); |
| 667 |
if (WIFSIGNALED(status)) { |
| 668 |
context.error(kj::str(output.name, ": plugin failed: ", strsignal(WTERMSIG(status)))); |
| 669 |
} else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { |
| 670 |
context.error(kj::str(output.name, ": plugin failed: exit code ", WEXITSTATUS(status))); |
| 671 |
} |
| 672 |
#endif // _WIN32, else |
| 673 |
} |
| 674 |
|
| 675 |
return true; |
| 676 |
} |
| 677 |
|
| 678 |
// ===================================================================================== |
| 679 |
// "convert" command |
| 680 |
|
| 681 |
private: |
| 682 |
enum class Format { |
| 683 |
BINARY, |
| 684 |
PACKED, |
| 685 |
FLAT, |
| 686 |
FLAT_PACKED, |
| 687 |
CANONICAL, |
| 688 |
TEXT, |
| 689 |
JSON |
| 690 |
}; |
| 691 |
|
| 692 |
kj::Maybe<Format> parseFormatName(kj::StringPtr name) { |
| 693 |
if (name == "binary" ) return Format::BINARY; |
| 694 |
if (name == "packed" ) return Format::PACKED; |
| 695 |
if (name == "flat" ) return Format::FLAT; |
| 696 |
if (name == "flat-packed") return Format::FLAT_PACKED; |
| 697 |
if (name == "canonical" ) return Format::CANONICAL; |
| 698 |
if (name == "text" ) return Format::TEXT; |
| 699 |
if (name == "json" ) return Format::JSON; |
| 700 |
|
| 701 |
return nullptr; |
| 702 |
} |
| 703 |
|
| 704 |
kj::StringPtr toString(Format format) { |
| 705 |
switch (format) { |
| 706 |
case Format::BINARY : return "binary"; |
| 707 |
case Format::PACKED : return "packed"; |
| 708 |
case Format::FLAT : return "flat"; |
| 709 |
case Format::FLAT_PACKED: return "flat-packed"; |
| 710 |
case Format::CANONICAL : return "canonical"; |
| 711 |
case Format::TEXT : return "text"; |
| 712 |
case Format::JSON : return "json"; |
| 713 |
} |
| 714 |
KJ_UNREACHABLE; |
| 715 |
} |
| 716 |
|
| 717 |
Format formatFromDeprecatedFlags(Format defaultFormat) { |
| 718 |
// For deprecated commands "decode" and "encode". |
| 719 |
if (flat) { |
| 720 |
if (packed) { |
| 721 |
return Format::FLAT_PACKED; |
| 722 |
} else { |
| 723 |
return Format::FLAT; |
| 724 |
} |
| 725 |
} if (packed) { |
| 726 |
return Format::PACKED; |
| 727 |
} else if (binary) { |
| 728 |
return Format::BINARY; |
| 729 |
} else { |
| 730 |
return defaultFormat; |
| 731 |
} |
| 732 |
} |
| 733 |
|
| 734 |
kj::MainBuilder::Validity verifyRequirements(Format format) { |
| 735 |
if ((format == Format::TEXT || format == Format::JSON) && rootType == StructSchema()) { |
| 736 |
return kj::str("format requires schema: ", toString(format)); |
| 737 |
} else { |
| 738 |
return true; |
| 739 |
} |
| 740 |
} |
| 741 |
|
| 742 |
public: |
| 743 |
kj::MainBuilder::Validity setConversion(kj::StringPtr conversion) { |
| 744 |
KJ_IF_MAYBE(colon, conversion.findFirst(':')) { |
| 745 |
auto from = kj::str(conversion.slice(0, *colon)); |
| 746 |
auto to = conversion.slice(*colon + 1); |
| 747 |
|
| 748 |
KJ_IF_MAYBE(f, parseFormatName(from)) { |
| 749 |
convertFrom = *f; |
| 750 |
} else { |
| 751 |
return kj::str("unknown format: ", from); |
| 752 |
} |
| 753 |
|
| 754 |
KJ_IF_MAYBE(t, parseFormatName(to)) { |
| 755 |
convertTo = *t; |
| 756 |
} else { |
| 757 |
return kj::str("unknown format: ", to); |
| 758 |
} |
| 759 |
|
| 760 |
if (convertFrom == Format::JSON || convertTo == Format::JSON) { |
| 761 |
// We need annotations to process JSON. |
| 762 |
// TODO(someday): Find a way that we can process annotations from json.capnp without |
| 763 |
// requiring other annotation-only imports like c++.capnp |
| 764 |
annotationFlag = Compiler::COMPILE_ANNOTATIONS; |
| 765 |
} |
| 766 |
|
| 767 |
return true; |
| 768 |
} else { |
| 769 |
return "invalid conversion, format is: <from>:<to>"; |
| 770 |
} |
| 771 |
} |
| 772 |
|
| 773 |
kj::MainBuilder::Validity convert() { |
| 774 |
{ |
| 775 |
auto result = verifyRequirements(convertFrom); |
| 776 |
if (result.getError() != nullptr) return result; |
| 777 |
} |
| 778 |
{ |
| 779 |
auto result = verifyRequirements(convertTo); |
| 780 |
if (result.getError() != nullptr) return result; |
| 781 |
} |
| 782 |
|
| 783 |
kj::FdInputStream rawInput(STDIN_FILENO); |
| 784 |
kj::BufferedInputStreamWrapper input(rawInput); |
| 785 |
|
| 786 |
kj::FdOutputStream output(STDOUT_FILENO); |
| 787 |
|
| 788 |
if (!quiet) { |
| 789 |
auto result = checkPlausibility(convertFrom, input.getReadBuffer()); |
| 790 |
if (result.getError() != nullptr) { |
| 791 |
return kj::mv(result); |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
while (input.tryGetReadBuffer().size() > 0) { |
| 796 |
readOneAndConvert(input, output); |
| 797 |
} |
| 798 |
|
| 799 |
context.exit(); |
| 800 |
KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT; |
| 801 |
} |
| 802 |
|
| 803 |
private: |
| 804 |
kj::Vector<byte> readAll(kj::BufferedInputStreamWrapper& input) { |
| 805 |
kj::Vector<byte> allBytes; |
| 806 |
for (;;) { |
| 807 |
auto buffer = input.tryGetReadBuffer(); |
| 808 |
if (buffer.size() == 0) break; |
| 809 |
allBytes.addAll(buffer); |
| 810 |
input.skip(buffer.size()); |
| 811 |
} |
| 812 |
return allBytes; |
| 813 |
} |
| 814 |
|
| 815 |
kj::String readOneText(kj::BufferedInputStreamWrapper& input) { |
| 816 |
// Consume and return one parentheses-delimited message from the input. |
| 817 |
// |
| 818 |
// Accounts for nested parentheses, comments, and string literals. |
| 819 |
|
| 820 |
enum { |
| 821 |
NORMAL, |
| 822 |
COMMENT, |
| 823 |
QUOTE, |
| 824 |
QUOTE_ESCAPE, |
| 825 |
DQUOTE, |
| 826 |
DQUOTE_ESCAPE |
| 827 |
} state = NORMAL; |
| 828 |
uint depth = 0; |
| 829 |
bool sawClose = false; |
| 830 |
|
| 831 |
kj::Vector<char> chars; |
| 832 |
|
| 833 |
for (;;) { |
| 834 |
auto buffer = input.tryGetReadBuffer(); |
| 835 |
|
| 836 |
if (buffer == nullptr) { |
| 837 |
// EOF |
| 838 |
chars.add('\0'); |
| 839 |
return kj::String(chars.releaseAsArray()); |
| 840 |
} |
| 841 |
|
| 842 |
for (auto i: kj::indices(buffer)) { |
| 843 |
char c = buffer[i]; |
| 844 |
switch (state) { |
| 845 |
case NORMAL: |
| 846 |
switch (c) { |
| 847 |
case '#': state = COMMENT; break; |
| 848 |
case '(': |
| 849 |
if (depth == 0 && sawClose) { |
| 850 |
// We already got one complete message. This is the start of the next message. |
| 851 |
// Stop here. |
| 852 |
chars.addAll(buffer.slice(0, i)); |
| 853 |
chars.add('\0'); |
| 854 |
input.skip(i); |
| 855 |
return kj::String(chars.releaseAsArray()); |
| 856 |
} |
| 857 |
++depth; |
| 858 |
break; |
| 859 |
case ')': |
| 860 |
if (depth > 0) { |
| 861 |
if (--depth == 0) { |
| 862 |
sawClose = true; |
| 863 |
} |
| 864 |
} |
| 865 |
break; |
| 866 |
default: break; |
| 867 |
} |
| 868 |
break; |
| 869 |
case COMMENT: |
| 870 |
switch (c) { |
| 871 |
case '\n': state = NORMAL; break; |
| 872 |
default: break; |
| 873 |
} |
| 874 |
break; |
| 875 |
case QUOTE: |
| 876 |
switch (c) { |
| 877 |
case '\'': state = NORMAL; break; |
| 878 |
case '\\': state = QUOTE_ESCAPE; break; |
| 879 |
default: break; |
| 880 |
} |
| 881 |
break; |
| 882 |
case QUOTE_ESCAPE: |
| 883 |
break; |
| 884 |
case DQUOTE: |
| 885 |
switch (c) { |
| 886 |
case '\"': state = NORMAL; break; |
| 887 |
case '\\': state = DQUOTE_ESCAPE; break; |
| 888 |
default: break; |
| 889 |
} |
| 890 |
break; |
| 891 |
case DQUOTE_ESCAPE: |
| 892 |
break; |
| 893 |
} |
| 894 |
} |
| 895 |
|
| 896 |
chars.addAll(buffer); |
| 897 |
input.skip(buffer.size()); |
| 898 |
} |
| 899 |
} |
| 900 |
|
| 901 |
kj::String readOneJson(kj::BufferedInputStreamWrapper& input) { |
| 902 |
// Consume and return one brace-delimited message from the input. |
| 903 |
// |
| 904 |
// Accounts for nested braces, string literals, and comments starting with # or //. Technically |
| 905 |
// JSON does not permit comments but this code is lenient in case we change things later. |
| 906 |
|
| 907 |
enum { |
| 908 |
NORMAL, |
| 909 |
SLASH, |
| 910 |
COMMENT, |
| 911 |
QUOTE, |
| 912 |
QUOTE_ESCAPE, |
| 913 |
DQUOTE, |
| 914 |
DQUOTE_ESCAPE |
| 915 |
} state = NORMAL; |
| 916 |
uint depth = 0; |
| 917 |
bool sawClose = false; |
| 918 |
|
| 919 |
kj::Vector<char> chars; |
| 920 |
|
| 921 |
for (;;) { |
| 922 |
auto buffer = input.tryGetReadBuffer(); |
| 923 |
|
| 924 |
if (buffer == nullptr) { |
| 925 |
// EOF |
| 926 |
chars.add('\0'); |
| 927 |
return kj::String(chars.releaseAsArray()); |
| 928 |
} |
| 929 |
|
| 930 |
for (auto i: kj::indices(buffer)) { |
| 931 |
char c = buffer[i]; |
| 932 |
switch (state) { |
| 933 |
case SLASH: |
| 934 |
if (c == '/') { |
| 935 |
state = COMMENT; |
| 936 |
break; |
| 937 |
} |
| 938 |
KJ_FALLTHROUGH; |
| 939 |
case NORMAL: |
| 940 |
switch (c) { |
| 941 |
case '#': state = COMMENT; break; |
| 942 |
case '/': state = SLASH; break; |
| 943 |
case '{': |
| 944 |
if (depth == 0 && sawClose) { |
| 945 |
// We already got one complete message. This is the start of the next message. |
| 946 |
// Stop here. |
| 947 |
chars.addAll(buffer.slice(0, i)); |
| 948 |
chars.add('\0'); |
| 949 |
input.skip(i); |
| 950 |
return kj::String(chars.releaseAsArray()); |
| 951 |
} |
| 952 |
++depth; |
| 953 |
break; |
| 954 |
case '}': |
| 955 |
if (depth > 0) { |
| 956 |
if (--depth == 0) { |
| 957 |
sawClose = true; |
| 958 |
} |
| 959 |
} |
| 960 |
break; |
| 961 |
default: break; |
| 962 |
} |
| 963 |
break; |
| 964 |
case COMMENT: |
| 965 |
switch (c) { |
| 966 |
case '\n': state = NORMAL; break; |
| 967 |
default: break; |
| 968 |
} |
| 969 |
break; |
| 970 |
case QUOTE: |
| 971 |
switch (c) { |
| 972 |
case '\'': state = NORMAL; break; |
| 973 |
case '\\': state = QUOTE_ESCAPE; break; |
| 974 |
default: break; |
| 975 |
} |
| 976 |
break; |
| 977 |
case QUOTE_ESCAPE: |
| 978 |
break; |
| 979 |
case DQUOTE: |
| 980 |
switch (c) { |
| 981 |
case '\"': state = NORMAL; break; |
| 982 |
case '\\': state = DQUOTE_ESCAPE; break; |
| 983 |
default: break; |
| 984 |
} |
| 985 |
break; |
| 986 |
case DQUOTE_ESCAPE: |
| 987 |
break; |
| 988 |
} |
| 989 |
} |
| 990 |
|
| 991 |
chars.addAll(buffer); |
| 992 |
input.skip(buffer.size()); |
| 993 |
} |
| 994 |
} |
| 995 |
|
| 996 |
class ParseErrorCatcher: public kj::ExceptionCallback { |
| 997 |
public: |
| 998 |
ParseErrorCatcher(kj::ProcessContext& context): context(context) {} |
| 999 |
~ParseErrorCatcher() noexcept(false) { |
| 1000 |
if (!unwindDetector.isUnwinding()) { |
| 1001 |
KJ_IF_MAYBE(e, exception) { |
| 1002 |
context.error(kj::str( |
| 1003 |
"*** ERROR CONVERTING PREVIOUS MESSAGE ***\n" |
| 1004 |
"The following error occurred while converting the message above.\n" |
| 1005 |
"This probably means the input data is invalid/corrupted.\n", |
| 1006 |
"Exception description: ", e->getDescription(), "\n" |
| 1007 |
"Code location: ", e->getFile(), ":", e->getLine(), "\n" |
| 1008 |
"*** END ERROR ***")); |
| 1009 |
} |
| 1010 |
} |
| 1011 |
} |
| 1012 |
|
| 1013 |
void onRecoverableException(kj::Exception&& e) { |
| 1014 |
// Only capture the first exception, on the assumption that later exceptions are probably |
| 1015 |
// just cascading problems. |
| 1016 |
if (exception == nullptr) { |
| 1017 |
exception = kj::mv(e); |
| 1018 |
} |
| 1019 |
} |
| 1020 |
|
| 1021 |
private: |
| 1022 |
kj::ProcessContext& context; |
| 1023 |
kj::Maybe<kj::Exception> exception; |
| 1024 |
kj::UnwindDetector unwindDetector; |
| 1025 |
}; |
| 1026 |
|
| 1027 |
void readOneAndConvert(kj::BufferedInputStreamWrapper& input, kj::OutputStream& output) { |
| 1028 |
// Since this is a debug tool, lift the usual security limits. Worse case is the process |
| 1029 |
// crashes or has to be killed. |
| 1030 |
ReaderOptions options; |
| 1031 |
options.nestingLimit = kj::maxValue; |
| 1032 |
options.traversalLimitInWords = kj::maxValue; |
| 1033 |
|
| 1034 |
ParseErrorCatcher parseErrorCatcher(context); |
| 1035 |
|
| 1036 |
switch (convertFrom) { |
| 1037 |
case Format::BINARY: { |
| 1038 |
capnp::InputStreamMessageReader message(input, options); |
| 1039 |
return writeConversion(message.getRoot<AnyStruct>(), output); |
| 1040 |
} |
| 1041 |
case Format::PACKED: { |
| 1042 |
capnp::PackedMessageReader message(input, options); |
| 1043 |
return writeConversion(message.getRoot<AnyStruct>(), output); |
| 1044 |
} |
| 1045 |
case Format::FLAT: |
| 1046 |
case Format::CANONICAL: { |
| 1047 |
auto allBytes = readAll(input); |
| 1048 |
|
| 1049 |
// Technically we don't know if the bytes are aligned so we'd better copy them to a new |
| 1050 |
// array. Note that if we have a non-whole number of words we chop off the straggler |
| 1051 |
// bytes. This is fine because if those bytes are actually part of the message we will |
| 1052 |
// hit an error later and if they are not then who cares? |
| 1053 |
auto words = kj::heapArray<word>(allBytes.size() / sizeof(word)); |
| 1054 |
memcpy(words.begin(), allBytes.begin(), words.size() * sizeof(word)); |
| 1055 |
|
| 1056 |
kj::ArrayPtr<const word> segments[1] = { words }; |
| 1057 |
SegmentArrayMessageReader message(segments, options); |
| 1058 |
if (convertFrom == Format::CANONICAL) { |
| 1059 |
KJ_REQUIRE(message.isCanonical()); |
| 1060 |
} |
| 1061 |
return writeConversion(message.getRoot<AnyStruct>(), output); |
| 1062 |
} |
| 1063 |
case Format::FLAT_PACKED: { |
| 1064 |
auto allBytes = readAll(input); |
| 1065 |
|
| 1066 |
auto words = kj::heapArray<word>(computeUnpackedSizeInWords(allBytes)); |
| 1067 |
kj::ArrayInputStream input(allBytes); |
| 1068 |
capnp::_::PackedInputStream unpacker(input); |
| 1069 |
unpacker.read(words.asBytes().begin(), words.asBytes().size()); |
| 1070 |
word dummy; |
| 1071 |
KJ_ASSERT(unpacker.tryRead(&dummy, sizeof(dummy), sizeof(dummy)) == 0); |
| 1072 |
|
| 1073 |
kj::ArrayPtr<const word> segments[1] = { words }; |
| 1074 |
SegmentArrayMessageReader message(segments, options); |
| 1075 |
return writeConversion(message.getRoot<AnyStruct>(), output); |
| 1076 |
} |
| 1077 |
case Format::TEXT: { |
| 1078 |
auto text = readOneText(input); |
| 1079 |
MallocMessageBuilder message; |
| 1080 |
TextCodec codec; |
| 1081 |
codec.setPrettyPrint(pretty); |
| 1082 |
auto root = message.initRoot<DynamicStruct>(rootType); |
| 1083 |
codec.decode(text, root); |
| 1084 |
return writeConversion(root.asReader(), output); |
| 1085 |
} |
| 1086 |
case Format::JSON: { |
| 1087 |
auto text = readOneJson(input); |
| 1088 |
MallocMessageBuilder message; |
| 1089 |
JsonCodec codec; |
| 1090 |
codec.setPrettyPrint(pretty); |
| 1091 |
codec.handleByAnnotation(rootType); |
| 1092 |
auto root = message.initRoot<DynamicStruct>(rootType); |
| 1093 |
codec.decode(text, root); |
| 1094 |
return writeConversion(root.asReader(), output); |
| 1095 |
} |
| 1096 |
} |
| 1097 |
|
| 1098 |
KJ_UNREACHABLE; |
| 1099 |
} |
| 1100 |
|
| 1101 |
void writeConversion(AnyStruct::Reader reader, kj::OutputStream& output) { |
| 1102 |
switch (convertTo) { |
| 1103 |
case Format::BINARY: { |
| 1104 |
MallocMessageBuilder message( |
| 1105 |
segmentSize == 0 ? SUGGESTED_FIRST_SEGMENT_WORDS : segmentSize, |
| 1106 |
segmentSize == 0 ? SUGGESTED_ALLOCATION_STRATEGY : AllocationStrategy::FIXED_SIZE); |
| 1107 |
message.setRoot(reader); |
| 1108 |
capnp::writeMessage(output, message); |
| 1109 |
return; |
| 1110 |
} |
| 1111 |
case Format::PACKED: { |
| 1112 |
MallocMessageBuilder message( |
| 1113 |
segmentSize == 0 ? SUGGESTED_FIRST_SEGMENT_WORDS : segmentSize, |
| 1114 |
segmentSize == 0 ? SUGGESTED_ALLOCATION_STRATEGY : AllocationStrategy::FIXED_SIZE); |
| 1115 |
message.setRoot(reader); |
| 1116 |
capnp::writePackedMessage(output, message); |
| 1117 |
return; |
| 1118 |
} |
| 1119 |
case Format::FLAT: { |
| 1120 |
auto words = kj::heapArray<word>(reader.totalSize().wordCount + 1); |
| 1121 |
memset(words.begin(), 0, words.asBytes().size()); |
| 1122 |
copyToUnchecked(reader, words); |
| 1123 |
output.write(words.begin(), words.asBytes().size()); |
| 1124 |
return; |
| 1125 |
} |
| 1126 |
case Format::FLAT_PACKED: { |
| 1127 |
auto words = kj::heapArray<word>(reader.totalSize().wordCount + 1); |
| 1128 |
memset(words.begin(), 0, words.asBytes().size()); |
| 1129 |
copyToUnchecked(reader, words); |
| 1130 |
kj::BufferedOutputStreamWrapper buffered(output); |
| 1131 |
capnp::_::PackedOutputStream packed(buffered); |
| 1132 |
packed.write(words.begin(), words.asBytes().size()); |
| 1133 |
return; |
| 1134 |
} |
| 1135 |
case Format::CANONICAL: { |
| 1136 |
auto words = reader.canonicalize(); |
| 1137 |
output.write(words.begin(), words.asBytes().size()); |
| 1138 |
return; |
| 1139 |
} |
| 1140 |
case Format::TEXT: { |
| 1141 |
TextCodec codec; |
| 1142 |
codec.setPrettyPrint(pretty); |
| 1143 |
auto text = codec.encode(reader.as<DynamicStruct>(rootType)); |
| 1144 |
output.write({text.asBytes(), kj::StringPtr("\n").asBytes()}); |
| 1145 |
return; |
| 1146 |
} |
| 1147 |
case Format::JSON: { |
| 1148 |
JsonCodec codec; |
| 1149 |
codec.setPrettyPrint(pretty); |
| 1150 |
codec.handleByAnnotation(rootType); |
| 1151 |
auto text = codec.encode(reader.as<DynamicStruct>(rootType)); |
| 1152 |
output.write({text.asBytes(), kj::StringPtr("\n").asBytes()}); |
| 1153 |
return; |
| 1154 |
} |
| 1155 |
} |
| 1156 |
|
| 1157 |
KJ_UNREACHABLE; |
| 1158 |
} |
| 1159 |
|
| 1160 |
public: |
| 1161 |
|
| 1162 |
// ===================================================================================== |
| 1163 |
// "decode" command |
| 1164 |
|
| 1165 |
kj::MainBuilder::Validity codeBinary() { |
| 1166 |
if (packed) return "cannot be used with --packed"; |
| 1167 |
if (flat) return "cannot be used with --flat"; |
| 1168 |
binary = true; |
| 1169 |
return true; |
| 1170 |
} |
| 1171 |
kj::MainBuilder::Validity codeFlat() { |
| 1172 |
if (binary) return "cannot be used with --binary"; |
| 1173 |
flat = true; |
| 1174 |
return true; |
| 1175 |
} |
| 1176 |
kj::MainBuilder::Validity codePacked() { |
| 1177 |
if (binary) return "cannot be used with --binary"; |
| 1178 |
packed = true; |
| 1179 |
return true; |
| 1180 |
} |
| 1181 |
kj::MainBuilder::Validity printShort() { |
| 1182 |
pretty = false; |
| 1183 |
return true; |
| 1184 |
} |
| 1185 |
kj::MainBuilder::Validity setQuiet() { |
| 1186 |
quiet = true; |
| 1187 |
return true; |
| 1188 |
} |
| 1189 |
kj::MainBuilder::Validity setSegmentSize(kj::StringPtr size) { |
| 1190 |
if (flat) return "cannot be used with --flat"; |
| 1191 |
char* end; |
| 1192 |
segmentSize = strtol(size.cStr(), &end, 0); |
| 1193 |
if (size.size() == 0 || *end != '\0') { |
| 1194 |
return "not an integer"; |
| 1195 |
} |
| 1196 |
return true; |
| 1197 |
} |
| 1198 |
|
| 1199 |
kj::MainBuilder::Validity setRootType(kj::StringPtr input) { |
| 1200 |
KJ_ASSERT(sourceFiles.size() == 1); |
| 1201 |
|
| 1202 |
class CliArgumentErrorReporter: public ErrorReporter { |
| 1203 |
public: |
| 1204 |
void addError(uint32_t startByte, uint32_t endByte, kj::StringPtr message) override { |
| 1205 |
if (startByte < endByte) { |
| 1206 |
error = kj::str(startByte + 1, "-", endByte, ": ", message); |
| 1207 |
} else if (startByte > 0) { |
| 1208 |
error = kj::str(startByte + 1, ": ", message); |
| 1209 |
} else { |
| 1210 |
error = kj::str(message); |
| 1211 |
} |
| 1212 |
} |
| 1213 |
|
| 1214 |
bool hadErrors() override { |
| 1215 |
return error != nullptr; |
| 1216 |
} |
| 1217 |
|
| 1218 |
kj::MainBuilder::Validity getValidity() { |
| 1219 |
KJ_IF_MAYBE(e, error) { |
| 1220 |
return kj::mv(*e); |
| 1221 |
} else { |
| 1222 |
return true; |
| 1223 |
} |
| 1224 |
} |
| 1225 |
|
| 1226 |
private: |
| 1227 |
kj::Maybe<kj::String> error; |
| 1228 |
}; |
| 1229 |
|
| 1230 |
CliArgumentErrorReporter errorReporter; |
| 1231 |
|
| 1232 |
capnp::MallocMessageBuilder tokenArena; |
| 1233 |
auto lexedTokens = tokenArena.initRoot<capnp::compiler::LexedTokens>(); |
| 1234 |
lex(input, lexedTokens, errorReporter); |
| 1235 |
|
| 1236 |
CapnpParser parser(tokenArena.getOrphanage(), errorReporter); |
| 1237 |
auto tokens = lexedTokens.asReader().getTokens(); |
| 1238 |
CapnpParser::ParserInput parserInput(tokens.begin(), tokens.end()); |
| 1239 |
|
| 1240 |
bool success = false; |
| 1241 |
|
| 1242 |
if (parserInput.getPosition() == tokens.end()) { |
| 1243 |
// Empty argument? |
| 1244 |
errorReporter.addError(0, 0, "Couldn't parse type name."); |
| 1245 |
} else { |
| 1246 |
KJ_IF_MAYBE(expression, parser.getParsers().expression(parserInput)) { |
| 1247 |
// The input is expected to contain a *single* expression. |
| 1248 |
if (parserInput.getPosition() == tokens.end()) { |
| 1249 |
// Hooray, now parse it. |
| 1250 |
KJ_IF_MAYBE(compiledType, |
| 1251 |
sourceFiles[0].compiled.evalType(expression->getReader(), errorReporter)) { |
| 1252 |
KJ_IF_MAYBE(type, compiledType->getSchema()) { |
| 1253 |
if (type->isStruct()) { |
| 1254 |
rootType = type->asStruct(); |
| 1255 |
success = true; |
| 1256 |
} else { |
| 1257 |
errorReporter.addError(0, 0, "Type is not a struct."); |
| 1258 |
} |
| 1259 |
} else { |
| 1260 |
// Apparently named a file scope. |
| 1261 |
errorReporter.addError(0, 0, "Type is not a struct."); |
| 1262 |
} |
| 1263 |
} |
| 1264 |
} else { |
| 1265 |
errorReporter.addErrorOn(parserInput.current(), "Couldn't parse type name."); |
| 1266 |
} |
| 1267 |
} else { |
| 1268 |
auto best = parserInput.getBest(); |
| 1269 |
if (best == tokens.end()) { |
| 1270 |
errorReporter.addError(input.size(), input.size(), "Couldn't parse type name."); |
| 1271 |
} else { |
| 1272 |
errorReporter.addErrorOn(*best, "Couldn't parse type name."); |
| 1273 |
} |
| 1274 |
} |
| 1275 |
} |
| 1276 |
|
| 1277 |
KJ_ASSERT(success || errorReporter.hadErrors()); |
| 1278 |
return errorReporter.getValidity(); |
| 1279 |
} |
| 1280 |
|
| 1281 |
kj::MainBuilder::Validity decode() { |
| 1282 |
convertTo = Format::TEXT; |
| 1283 |
convertFrom = formatFromDeprecatedFlags(Format::BINARY); |
| 1284 |
return convert(); |
| 1285 |
} |
| 1286 |
|
| 1287 |
private: |
| 1288 |
enum Plausibility { |
| 1289 |
IMPOSSIBLE, |
| 1290 |
IMPLAUSIBLE, |
| 1291 |
WRONG_TYPE, |
| 1292 |
PLAUSIBLE |
| 1293 |
}; |
| 1294 |
|
| 1295 |
bool plausibleOrWrongType(Plausibility p) { |
| 1296 |
return p == PLAUSIBLE || p == WRONG_TYPE; |
| 1297 |
} |
| 1298 |
|
| 1299 |
Plausibility isPlausiblyFlat(kj::ArrayPtr<const byte> prefix, uint segmentCount = 1) { |
| 1300 |
if (prefix.size() < 8) { |
| 1301 |
// Not enough prefix to say. |
| 1302 |
return PLAUSIBLE; |
| 1303 |
} |
| 1304 |
|
| 1305 |
if ((prefix[0] & 3) == 2) { |
| 1306 |
// Far pointer. Verify the segment ID. |
| 1307 |
uint32_t segmentId = prefix[4] | (prefix[5] << 8) |
| 1308 |
| (prefix[6] << 16) | (prefix[7] << 24); |
| 1309 |
if (segmentId == 0 || segmentId >= segmentCount) { |
| 1310 |
return IMPOSSIBLE; |
| 1311 |
} else { |
| 1312 |
return PLAUSIBLE; |
| 1313 |
} |
| 1314 |
} |
| 1315 |
|
| 1316 |
if ((prefix[0] & 3) != 0) { |
| 1317 |
// Not a struct pointer. |
| 1318 |
return IMPOSSIBLE; |
| 1319 |
} |
| 1320 |
if ((prefix[3] & 0x80) != 0) { |
| 1321 |
if (prefix[0] == 0xff && prefix[1] == 0xff && prefix[2] == 0xff && prefix[3] == 0xff && |
| 1322 |
prefix[4] == 0 && prefix[5] == 0 && prefix[6] == 0 && prefix[7] == 0) { |
| 1323 |
// This is an empty struct with offset of -1. That's valid. |
| 1324 |
} else { |
| 1325 |
// Offset is negative (invalid). |
| 1326 |
return IMPOSSIBLE; |
| 1327 |
} |
| 1328 |
} |
| 1329 |
if ((prefix[3] & 0xe0) != 0) { |
| 1330 |
// Offset is over a gigabyte (implausible). |
| 1331 |
return IMPLAUSIBLE; |
| 1332 |
} |
| 1333 |
|
| 1334 |
uint data = prefix[4] | (prefix[5] << 8); |
| 1335 |
uint pointers = prefix[6] | (prefix[7] << 8); |
| 1336 |
|
| 1337 |
if (data + pointers > 2048) { |
| 1338 |
// Root struct is huge (over 16 KiB). |
| 1339 |
return IMPLAUSIBLE; |
| 1340 |
} |
| 1341 |
|
| 1342 |
auto structSchema = rootType.getProto().getStruct(); |
| 1343 |
if ((data < structSchema.getDataWordCount() && pointers > structSchema.getPointerCount()) || |
| 1344 |
(data > structSchema.getDataWordCount() && pointers < structSchema.getPointerCount())) { |
| 1345 |
// Struct is neither older nor newer than the schema. |
| 1346 |
return WRONG_TYPE; |
| 1347 |
} |
| 1348 |
|
| 1349 |
if (data > structSchema.getDataWordCount() && |
| 1350 |
data - structSchema.getDataWordCount() > 128) { |
| 1351 |
// Data section appears to have grown by 1k (128 words). This seems implausible. |
| 1352 |
return WRONG_TYPE; |
| 1353 |
} |
| 1354 |
if (pointers > structSchema.getPointerCount() && |
| 1355 |
pointers - structSchema.getPointerCount() > 128) { |
| 1356 |
// Pointer section appears to have grown by 1k (128 words). This seems implausible. |
| 1357 |
return WRONG_TYPE; |
| 1358 |
} |
| 1359 |
|
| 1360 |
return PLAUSIBLE; |
| 1361 |
} |
| 1362 |
|
| 1363 |
Plausibility isPlausiblyBinary(kj::ArrayPtr<const byte> prefix) { |
| 1364 |
if (prefix.size() < 8) { |
| 1365 |
// Not enough prefix to say. |
| 1366 |
return PLAUSIBLE; |
| 1367 |
} |
| 1368 |
|
| 1369 |
uint32_t segmentCount = prefix[0] | (prefix[1] << 8) |
| 1370 |
| (prefix[2] << 16) | (prefix[3] << 24); |
| 1371 |
|
| 1372 |
// Actually, the bytes store segmentCount - 1. |
| 1373 |
++segmentCount; |
| 1374 |
|
| 1375 |
if (segmentCount > 65536) { |
| 1376 |
// While technically possible, this is so implausible that we should mark it impossible. |
| 1377 |
// This helps to make sure we fail fast on packed input. |
| 1378 |
return IMPOSSIBLE; |
| 1379 |
} else if (segmentCount > 256) { |
| 1380 |
// Implausible segment count. |
| 1381 |
return IMPLAUSIBLE; |
| 1382 |
} |
| 1383 |
|
| 1384 |
uint32_t segment0Size = prefix[4] | (prefix[5] << 8) |
| 1385 |
| (prefix[6] << 16) | (prefix[7] << 24); |
| 1386 |
|
| 1387 |
if (segment0Size > (1 << 27)) { |
| 1388 |
// Segment larger than 1G seems implausible. |
| 1389 |
return IMPLAUSIBLE; |
| 1390 |
} |
| 1391 |
|
| 1392 |
uint32_t segment0Offset = 4 + segmentCount * 4; |
| 1393 |
if (segment0Offset % 8 != 0) { |
| 1394 |
segment0Offset += 4; |
| 1395 |
} |
| 1396 |
KJ_ASSERT(segment0Offset % 8 == 0); |
| 1397 |
|
| 1398 |
if (prefix.size() < segment0Offset + 8) { |
| 1399 |
// Segment 0 is past our prefix, so we can't check it. |
| 1400 |
return PLAUSIBLE; |
| 1401 |
} |
| 1402 |
|
| 1403 |
return isPlausiblyFlat(prefix.slice(segment0Offset, prefix.size()), segmentCount); |
| 1404 |
} |
| 1405 |
|
| 1406 |
Plausibility isPlausiblyPacked(kj::ArrayPtr<const byte> prefix, |
| 1407 |
kj::Function<Plausibility(kj::ArrayPtr<const byte>)> checkUnpacked) { |
| 1408 |
kj::Vector<byte> unpacked; |
| 1409 |
|
| 1410 |
// Try to unpack a prefix so that we can check it. |
| 1411 |
const byte* pos = prefix.begin(); |
| 1412 |
const byte* end = prefix.end(); |
| 1413 |
if (end - pos > 1024) { |
| 1414 |
// Don't bother unpacking more than 1k. |
| 1415 |
end = pos + 1024; |
| 1416 |
} |
| 1417 |
while (pos < end) { |
| 1418 |
byte tag = *pos++; |
| 1419 |
for (uint i = 0; i < 8 && pos < end; i++) { |
| 1420 |
if (tag & (1 << i)) { |
| 1421 |
byte b = *pos++; |
| 1422 |
if (b == 0) { |
| 1423 |
// A zero byte should have been deflated away. |
| 1424 |
return IMPOSSIBLE; |
| 1425 |
} |
| 1426 |
unpacked.add(b); |
| 1427 |
} else { |
| 1428 |
unpacked.add(0); |
| 1429 |
} |
| 1430 |
} |
| 1431 |
|
| 1432 |
if (pos == end) { |
| 1433 |
break; |
| 1434 |
} |
| 1435 |
|
| 1436 |
if (tag == 0) { |
| 1437 |
uint count = *pos++ * 8; |
| 1438 |
unpacked.addAll(kj::repeat(byte(0), count)); |
| 1439 |
} else if (tag == 0xff) { |
| 1440 |
uint count = *pos++ * 8; |
| 1441 |
size_t available = end - pos; |
| 1442 |
uint n = kj::min(count, available); |
| 1443 |
unpacked.addAll(pos, pos + n); |
| 1444 |
pos += n; |
| 1445 |
} |
| 1446 |
} |
| 1447 |
|
| 1448 |
return checkUnpacked(unpacked); |
| 1449 |
} |
| 1450 |
|
| 1451 |
Plausibility isPlausiblyPacked(kj::ArrayPtr<const byte> prefix) { |
| 1452 |
return isPlausiblyPacked(prefix, KJ_BIND_METHOD(*this, isPlausiblyBinary)); |
| 1453 |
} |
| 1454 |
|
| 1455 |
Plausibility isPlausiblyPackedFlat(kj::ArrayPtr<const byte> prefix) { |
| 1456 |
return isPlausiblyPacked(prefix, [this](kj::ArrayPtr<const byte> prefix) { |
| 1457 |
return isPlausiblyFlat(prefix); |
| 1458 |
}); |
| 1459 |
} |
| 1460 |
|
| 1461 |
Plausibility isPlausiblyText(kj::ArrayPtr<const byte> prefix) { |
| 1462 |
enum { PREAMBLE, COMMENT, BODY } state = PREAMBLE; |
| 1463 |
|
| 1464 |
for (char c: prefix.asChars()) { |
| 1465 |
switch (state) { |
| 1466 |
case PREAMBLE: |
| 1467 |
// Before opening parenthesis. |
| 1468 |
switch (c) { |
| 1469 |
case '(': state = BODY; continue; |
| 1470 |
case '#': state = COMMENT; continue; |
| 1471 |
case ' ': |
| 1472 |
case '\n': |
| 1473 |
case '\r': |
| 1474 |
case '\t': |
| 1475 |
case '\v': |
| 1476 |
// whitespace |
| 1477 |
break; |
| 1478 |
default: |
| 1479 |
// Not whitespace, not comment, not open parenthesis. Impossible! |
| 1480 |
return IMPOSSIBLE; |
| 1481 |
} |
| 1482 |
break; |
| 1483 |
case COMMENT: |
| 1484 |
switch (c) { |
| 1485 |
case '\n': state = PREAMBLE; continue; |
| 1486 |
default: break; |
| 1487 |
} |
| 1488 |
break; |
| 1489 |
case BODY: |
| 1490 |
switch (c) { |
| 1491 |
case '\"': |
| 1492 |
case '\'': |
| 1493 |
// String literal. Let's stop here before things get complicated. |
| 1494 |
return PLAUSIBLE; |
| 1495 |
default: |
| 1496 |
break; |
| 1497 |
} |
| 1498 |
break; |
| 1499 |
} |
| 1500 |
|
| 1501 |
if ((static_cast<uint8_t>(c) < 0x20 && c != '\n' && c != '\r' && c != '\t' && c != '\v') |
| 1502 |
|| c == 0x7f) { |
| 1503 |
// Unprintable character. |
| 1504 |
return IMPOSSIBLE; |
| 1505 |
} |
| 1506 |
} |
| 1507 |
|
| 1508 |
return PLAUSIBLE; |
| 1509 |
} |
| 1510 |
|
| 1511 |
Plausibility isPlausiblyJson(kj::ArrayPtr<const byte> prefix) { |
| 1512 |
enum { PREAMBLE, COMMENT, BODY } state = PREAMBLE; |
| 1513 |
|
| 1514 |
for (char c: prefix.asChars()) { |
| 1515 |
switch (state) { |
| 1516 |
case PREAMBLE: |
| 1517 |
// Before opening parenthesis. |
| 1518 |
switch (c) { |
| 1519 |
case '{': state = BODY; continue; |
| 1520 |
case '#': state = COMMENT; continue; |
| 1521 |
case '/': state = COMMENT; continue; |
| 1522 |
case ' ': |
| 1523 |
case '\n': |
| 1524 |
case '\r': |
| 1525 |
case '\t': |
| 1526 |
case '\v': |
| 1527 |
// whitespace |
| 1528 |
break; |
| 1529 |
default: |
| 1530 |
// Not whitespace, not comment, not open brace. Impossible! |
| 1531 |
return IMPOSSIBLE; |
| 1532 |
} |
| 1533 |
break; |
| 1534 |
case COMMENT: |
| 1535 |
switch (c) { |
| 1536 |
case '\n': state = PREAMBLE; continue; |
| 1537 |
default: break; |
| 1538 |
} |
| 1539 |
break; |
| 1540 |
case BODY: |
| 1541 |
switch (c) { |
| 1542 |
case '\"': |
| 1543 |
// String literal. Let's stop here before things get complicated. |
| 1544 |
return PLAUSIBLE; |
| 1545 |
default: |
| 1546 |
break; |
| 1547 |
} |
| 1548 |
break; |
| 1549 |
} |
| 1550 |
|
| 1551 |
if ((c > 0 && c < ' ' && c != '\n' && c != '\r' && c != '\t' && c != '\v') || c == 0x7f) { |
| 1552 |
// Unprintable character. |
| 1553 |
return IMPOSSIBLE; |
| 1554 |
} |
| 1555 |
} |
| 1556 |
|
| 1557 |
return PLAUSIBLE; |
| 1558 |
} |
| 1559 |
|
| 1560 |
Plausibility isPlausibly(Format format, kj::ArrayPtr<const byte> prefix) { |
| 1561 |
switch (format) { |
| 1562 |
case Format::BINARY : return isPlausiblyBinary (prefix); |
| 1563 |
case Format::PACKED : return isPlausiblyPacked (prefix); |
| 1564 |
case Format::FLAT : return isPlausiblyFlat (prefix); |
| 1565 |
case Format::FLAT_PACKED: return isPlausiblyPackedFlat(prefix); |
| 1566 |
case Format::CANONICAL : return isPlausiblyFlat (prefix); |
| 1567 |
case Format::TEXT : return isPlausiblyText (prefix); |
| 1568 |
case Format::JSON : return isPlausiblyJson (prefix); |
| 1569 |
} |
| 1570 |
KJ_UNREACHABLE; |
| 1571 |
} |
| 1572 |
|
| 1573 |
kj::Maybe<Format> guessFormat(kj::ArrayPtr<const byte> prefix) { |
| 1574 |
Format candidates[] = { |
| 1575 |
Format::BINARY, |
| 1576 |
Format::TEXT, |
| 1577 |
Format::PACKED, |
| 1578 |
Format::JSON, |
| 1579 |
Format::FLAT, |
| 1580 |
Format::FLAT_PACKED |
| 1581 |
}; |
| 1582 |
|
| 1583 |
for (Format candidate: candidates) { |
| 1584 |
if (plausibleOrWrongType(isPlausibly(candidate, prefix))) { |
| 1585 |
return candidate; |
| 1586 |
} |
| 1587 |
} |
| 1588 |
|
| 1589 |
return nullptr; |
| 1590 |
} |
| 1591 |
|
| 1592 |
kj::MainBuilder::Validity checkPlausibility(Format format, kj::ArrayPtr<const byte> prefix) { |
| 1593 |
switch (isPlausibly(format, prefix)) { |
| 1594 |
case PLAUSIBLE: |
| 1595 |
return true; |
| 1596 |
|
| 1597 |
case IMPOSSIBLE: |
| 1598 |
KJ_IF_MAYBE(guess, guessFormat(prefix)) { |
| 1599 |
return kj::str( |
| 1600 |
"The input is not in \"", toString(format), "\" format. It looks like it is in \"", |
| 1601 |
toString(*guess), "\" format. Try that instead."); |
| 1602 |
} else { |
| 1603 |
return kj::str( |
| 1604 |
"The input is not in \"", toString(format), "\" format."); |
| 1605 |
} |
| 1606 |
|
| 1607 |
case IMPLAUSIBLE: |
| 1608 |
KJ_IF_MAYBE(guess, guessFormat(prefix)) { |
| 1609 |
context.warning(kj::str( |
| 1610 |
"*** WARNING ***\n" |
| 1611 |
"The input data does not appear to be in \"", toString(format), "\" format. It\n" |
| 1612 |
"looks like it may be in \"", toString(*guess), "\" format. I'll try to parse\n" |
| 1613 |
"it in \"", toString(format), "\" format as you requested, but if it doesn't work,\n" |
| 1614 |
"try \"", toString(format), "\" instead. Use --quiet to suppress this warning.\n" |
| 1615 |
"*** END WARNING ***\n")); |
| 1616 |
} else { |
| 1617 |
context.warning(kj::str( |
| 1618 |
"*** WARNING ***\n" |
| 1619 |
"The input data does not appear to be in \"", toString(format), "\" format, nor\n" |
| 1620 |
"in any other known format. I'll try to parse it in \"", toString(format), "\"\n" |
| 1621 |
"format anyway, as you requested. Use --quiet to suppress this warning.\n" |
| 1622 |
"*** END WARNING ***\n")); |
| 1623 |
} |
| 1624 |
return true; |
| 1625 |
|
| 1626 |
case WRONG_TYPE: |
| 1627 |
if (format == Format::FLAT && plausibleOrWrongType(isPlausiblyBinary(prefix))) { |
| 1628 |
context.warning( |
| 1629 |
"*** WARNING ***\n" |
| 1630 |
"The input data does not appear to match the schema that you specified. I'll try\n" |
| 1631 |
"to parse it anyway, but if it doesn't look right, please verify that you\n" |
| 1632 |
"have the right schema. This could also be because the input is not in \"flat\"\n" |
| 1633 |
"format; indeed, it looks like this input may be in regular binary format,\n" |
| 1634 |
"so you might want to try \"binary\" instead. Use --quiet to suppress this\n" |
| 1635 |
"warning.\n" |
| 1636 |
"*** END WARNING ***\n"); |
| 1637 |
} else if (format == Format::FLAT_PACKED && |
| 1638 |
plausibleOrWrongType(isPlausiblyPacked(prefix))) { |
| 1639 |
context.warning( |
| 1640 |
"*** WARNING ***\n" |
| 1641 |
"The input data does not appear to match the schema that you specified. I'll try\n" |
| 1642 |
"to parse it anyway, but if it doesn't look right, please verify that you\n" |
| 1643 |
"have the right schema. This could also be because the input is not in \"flat-packed\"\n" |
| 1644 |
"format; indeed, it looks like this input may be in regular packed format,\n" |
| 1645 |
"so you might want to try \"packed\" instead. Use --quiet to suppress this\n" |
| 1646 |
"warning.\n" |
| 1647 |
"*** END WARNING ***\n"); |
| 1648 |
} else { |
| 1649 |
context.warning( |
| 1650 |
"*** WARNING ***\n" |
| 1651 |
"The input data does not appear to be the type that you specified. I'll try\n" |
| 1652 |
"to parse it anyway, but if it doesn't look right, please verify that you\n" |
| 1653 |
"have the right type. Use --quiet to suppress this warning.\n" |
| 1654 |
"*** END WARNING ***\n"); |
| 1655 |
} |
| 1656 |
return true; |
| 1657 |
} |
| 1658 |
|
| 1659 |
KJ_UNREACHABLE; |
| 1660 |
} |
| 1661 |
|
| 1662 |
public: |
| 1663 |
// ----------------------------------------------------------------- |
| 1664 |
|
| 1665 |
kj::MainBuilder::Validity encode() { |
| 1666 |
convertFrom = Format::TEXT; |
| 1667 |
convertTo = formatFromDeprecatedFlags(Format::BINARY); |
| 1668 |
return convert(); |
| 1669 |
} |
| 1670 |
|
| 1671 |
kj::MainBuilder::Validity setEvalOutputFormat(kj::StringPtr format) { |
| 1672 |
KJ_IF_MAYBE(f, parseFormatName(format)) { |
| 1673 |
convertTo = *f; |
| 1674 |
return true; |
| 1675 |
} else { |
| 1676 |
return kj::str("unknown format: ", format); |
| 1677 |
} |
| 1678 |
} |
| 1679 |
|
| 1680 |
kj::MainBuilder::Validity evalConst(kj::StringPtr name) { |
| 1681 |
convertTo = formatFromDeprecatedFlags(convertTo); |
| 1682 |
|
| 1683 |
KJ_ASSERT(sourceFiles.size() == 1); |
| 1684 |
|
| 1685 |
auto parser = kj::parse::sequence( |
| 1686 |
kj::parse::many( |
| 1687 |
kj::parse::sequence( |
| 1688 |
kj::parse::identifier, |
| 1689 |
kj::parse::many( |
| 1690 |
kj::parse::sequence( |
| 1691 |
kj::parse::exactChar<'['>(), |
| 1692 |
kj::parse::integer, |
| 1693 |
kj::parse::exactChar<']'>())), |
| 1694 |
kj::parse::oneOf( |
| 1695 |
kj::parse::endOfInput, |
| 1696 |
kj::parse::sequence( |
| 1697 |
kj::parse::exactChar<'.'>(), |
| 1698 |
kj::parse::notLookingAt(kj::parse::endOfInput))))), |
| 1699 |
kj::parse::endOfInput); |
| 1700 |
|
| 1701 |
kj::parse::IteratorInput<char, const char*> input(name.begin(), name.end()); |
| 1702 |
|
| 1703 |
kj::Array<kj::Tuple<kj::String, kj::Array<uint64_t>>> nameParts; |
| 1704 |
KJ_IF_MAYBE(p, parser(input)) { |
| 1705 |
nameParts = kj::mv(*p); |
| 1706 |
} else { |
| 1707 |
return "invalid syntax"; |
| 1708 |
} |
| 1709 |
|
| 1710 |
auto pos = nameParts.begin(); |
| 1711 |
|
| 1712 |
// Traverse the path to find a schema. |
| 1713 |
uint64_t scopeId = sourceFiles[0].id; |
| 1714 |
bool stoppedAtSubscript = false; |
| 1715 |
for (; pos != nameParts.end(); ++pos) { |
| 1716 |
kj::StringPtr part = kj::get<0>(*pos); |
| 1717 |
|
| 1718 |
KJ_IF_MAYBE(childId, compiler->lookup(scopeId, part)) { |
| 1719 |
scopeId = *childId; |
| 1720 |
|
| 1721 |
if (kj::get<1>(*pos).size() > 0) { |
| 1722 |
stoppedAtSubscript = true; |
| 1723 |
break; |
| 1724 |
} |
| 1725 |
} else { |
| 1726 |
break; |
| 1727 |
} |
| 1728 |
} |
| 1729 |
Schema schema = compiler->getLoader().get(scopeId); |
| 1730 |
|
| 1731 |
// Evaluate this schema to a DynamicValue. |
| 1732 |
DynamicValue::Reader value; |
| 1733 |
word zeroWord[1]; |
| 1734 |
memset(&zeroWord, 0, sizeof(zeroWord)); |
| 1735 |
kj::ArrayPtr<const word> segments[1] = { kj::arrayPtr(zeroWord, 1) }; |
| 1736 |
SegmentArrayMessageReader emptyMessage(segments); |
| 1737 |
switch (schema.getProto().which()) { |
| 1738 |
case schema::Node::CONST: |
| 1739 |
value = schema.asConst(); |
| 1740 |
break; |
| 1741 |
|
| 1742 |
case schema::Node::STRUCT: |
| 1743 |
if (pos == nameParts.end()) { |
| 1744 |
return kj::str("'", schema.getShortDisplayName(), "' cannot be evaluated."); |
| 1745 |
} |
| 1746 |
|
| 1747 |
// Use the struct's default value. |
| 1748 |
value = emptyMessage.getRoot<DynamicStruct>(schema.asStruct()); |
| 1749 |
break; |
| 1750 |
|
| 1751 |
default: |
| 1752 |
if (stoppedAtSubscript) { |
| 1753 |
return kj::str("'", schema.getShortDisplayName(), "' is not a list."); |
| 1754 |
} else if (pos != nameParts.end()) { |
| 1755 |
return kj::str("'", kj::get<0>(*pos), "' is not defined."); |
| 1756 |
} else { |
| 1757 |
return kj::str("'", schema.getShortDisplayName(), "' cannot be evaluated."); |
| 1758 |
} |
| 1759 |
} |
| 1760 |
|
| 1761 |
// Traverse the rest of the path as struct fields. |
| 1762 |
for (; pos != nameParts.end(); ++pos) { |
| 1763 |
kj::StringPtr partName = kj::get<0>(*pos); |
| 1764 |
|
| 1765 |
if (!stoppedAtSubscript) { |
| 1766 |
if (value.getType() == DynamicValue::STRUCT) { |
| 1767 |
auto structValue = value.as<DynamicStruct>(); |
| 1768 |
KJ_IF_MAYBE(field, structValue.getSchema().findFieldByName(partName)) { |
| 1769 |
value = structValue.get(*field); |
| 1770 |
} else { |
| 1771 |
return kj::str("'", kj::get<0>(pos[-1]), "' has no member '", partName, "'."); |
| 1772 |
} |
| 1773 |
} else { |
| 1774 |
return kj::str("'", kj::get<0>(pos[-1]), "' is not a struct."); |
| 1775 |
} |
| 1776 |
} |
| 1777 |
|
| 1778 |
auto& subscripts = kj::get<1>(*pos); |
| 1779 |
for (uint i = 0; i < subscripts.size(); i++) { |
| 1780 |
uint64_t subscript = subscripts[i]; |
| 1781 |
if (value.getType() == DynamicValue::LIST) { |
| 1782 |
auto listValue = value.as<DynamicList>(); |
| 1783 |
if (subscript < listValue.size()) { |
| 1784 |
value = listValue[subscript]; |
| 1785 |
} else { |
| 1786 |
return kj::str("'", partName, "[", kj::strArray(subscripts.slice(0, i + 1), "]["), |
| 1787 |
"]' is out-of-bounds."); |
| 1788 |
} |
| 1789 |
} else { |
| 1790 |
if (i > 0) { |
| 1791 |
return kj::str("'", partName, "[", kj::strArray(subscripts.slice(0, i), "]["), |
| 1792 |
"]' is not a list."); |
| 1793 |
} else { |
| 1794 |
return kj::str("'", partName, "' is not a list."); |
| 1795 |
} |
| 1796 |
} |
| 1797 |
} |
| 1798 |
|
| 1799 |
stoppedAtSubscript = false; |
| 1800 |
} |
| 1801 |
|
| 1802 |
// OK, we have a value. Print it. |
| 1803 |
if (convertTo != Format::TEXT) { |
| 1804 |
if (value.getType() != DynamicValue::STRUCT) { |
| 1805 |
return "not a struct; binary output is only available on structs"; |
| 1806 |
} |
| 1807 |
|
| 1808 |
auto structValue = value.as<DynamicStruct>(); |
| 1809 |
rootType = structValue.getSchema(); |
| 1810 |
kj::FdOutputStream output(STDOUT_FILENO); |
| 1811 |
writeConversion(structValue, output); |
| 1812 |
context.exit(); |
| 1813 |
} else { |
| 1814 |
if (pretty && value.getType() == DynamicValue::STRUCT) { |
| 1815 |
context.exitInfo(prettyPrint(value.as<DynamicStruct>()).flatten()); |
| 1816 |
} else if (pretty && value.getType() == DynamicValue::LIST) { |
| 1817 |
context.exitInfo(prettyPrint(value.as<DynamicList>()).flatten()); |
| 1818 |
} else { |
| 1819 |
context.exitInfo(kj::str(value)); |
| 1820 |
} |
| 1821 |
} |
| 1822 |
|
| 1823 |
KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT; |
| 1824 |
} |
| 1825 |
|
| 1826 |
public: |
| 1827 |
// ===================================================================================== |
| 1828 |
|
| 1829 |
void addError(const kj::ReadableDirectory& directory, kj::PathPtr path, |
| 1830 |
SourcePos start, SourcePos end, |
| 1831 |
kj::StringPtr message) override { |
| 1832 |
auto file = getDisplayName(directory, path); |
| 1833 |
|
| 1834 |
kj::String wholeMessage; |
| 1835 |
if (end.line == start.line) { |
| 1836 |
if (end.column == start.column) { |
| 1837 |
wholeMessage = kj::str(file, ":", start.line + 1, ":", start.column + 1, |
| 1838 |
": error: ", message, "\n"); |
| 1839 |
} else { |
| 1840 |
wholeMessage = kj::str(file, ":", start.line + 1, ":", start.column + 1, |
| 1841 |
"-", end.column + 1, ": error: ", message, "\n"); |
| 1842 |
} |
| 1843 |
} else { |
| 1844 |
// The error spans multiple lines, so just report it on the first such line. |
| 1845 |
wholeMessage = kj::str(file, ":", start.line + 1, ": error: ", message, "\n"); |
| 1846 |
} |
| 1847 |
|
| 1848 |
context.error(wholeMessage); |
| 1849 |
hadErrors_ = true; |
| 1850 |
} |
| 1851 |
|
| 1852 |
bool hadErrors() override { |
| 1853 |
return hadErrors_; |
| 1854 |
} |
| 1855 |
|
| 1856 |
private: |
| 1857 |
kj::ProcessContext& context; |
| 1858 |
kj::Own<kj::Filesystem> disk; |
| 1859 |
ModuleLoader loader; |
| 1860 |
kj::SpaceFor<Compiler> compilerSpace; |
| 1861 |
bool compilerConstructed = false; |
| 1862 |
kj::Own<Compiler> compiler; |
| 1863 |
|
| 1864 |
Compiler::AnnotationFlag annotationFlag = Compiler::COMPILE_ANNOTATIONS; |
| 1865 |
|
| 1866 |
uint compileEagerness = Compiler::NODE | Compiler::CHILDREN | |
| 1867 |
Compiler::DEPENDENCIES | Compiler::DEPENDENCY_PARENTS; |
| 1868 |
// By default we compile each explicitly listed schema in full, plus first-level dependencies |
| 1869 |
// of those schemas, plus the parent nodes of any dependencies. This is what most code generators |
| 1870 |
// require to function. |
| 1871 |
|
| 1872 |
struct SourceDirectory { |
| 1873 |
kj::Own<const kj::ReadableDirectory> dir; |
| 1874 |
bool isSourcePrefix; |
| 1875 |
}; |
| 1876 |
|
| 1877 |
kj::HashMap<kj::Path, SourceDirectory> sourceDirectories; |
| 1878 |
// For each import path and source prefix, tracks the directory object we opened for it. |
| 1879 |
// |
| 1880 |
// Use via getSourceDirectory(). |
| 1881 |
|
| 1882 |
kj::HashMap<const kj::ReadableDirectory*, kj::String> dirPrefixes; |
| 1883 |
// For each open directory object, maps to a path prefix to add when displaying this path in |
| 1884 |
// error messages. This keeps track of the original directory name as given by the user, before |
| 1885 |
// canonicalization. |
| 1886 |
// |
| 1887 |
// Use via getDisplayName(). |
| 1888 |
|
| 1889 |
bool addStandardImportPaths = true; |
| 1890 |
|
| 1891 |
Format convertFrom = Format::BINARY; |
| 1892 |
Format convertTo = Format::BINARY; |
| 1893 |
// For the "convert" command. |
| 1894 |
|
| 1895 |
bool binary = false; |
| 1896 |
bool flat = false; |
| 1897 |
bool packed = false; |
| 1898 |
bool pretty = true; |
| 1899 |
bool quiet = false; |
| 1900 |
uint segmentSize = 0; |
| 1901 |
StructSchema rootType; |
| 1902 |
// For the "decode" and "encode" commands. |
| 1903 |
|
| 1904 |
struct SourceFile { |
| 1905 |
uint64_t id; |
| 1906 |
Compiler::ModuleScope compiled; |
| 1907 |
kj::StringPtr name; |
| 1908 |
Module* module; |
| 1909 |
}; |
| 1910 |
|
| 1911 |
kj::Vector<SourceFile> sourceFiles; |
| 1912 |
|
| 1913 |
struct OutputDirective { |
| 1914 |
kj::ArrayPtr<const char> name; |
| 1915 |
kj::Maybe<kj::Path> dir; |
| 1916 |
|
| 1917 |
KJ_DISALLOW_COPY(OutputDirective); |
| 1918 |
OutputDirective(OutputDirective&&) = default; |
| 1919 |
OutputDirective(kj::ArrayPtr<const char> name, kj::Maybe<kj::Path> dir) |
| 1920 |
: name(name), dir(kj::mv(dir)) {} |
| 1921 |
}; |
| 1922 |
kj::Vector<OutputDirective> outputs; |
| 1923 |
|
| 1924 |
bool hadErrors_ = false; |
| 1925 |
|
| 1926 |
kj::Maybe<const kj::ReadableDirectory&> getSourceDirectory( |
| 1927 |
kj::StringPtr pathStr, bool isSourcePrefix) { |
| 1928 |
auto cwd = disk->getCurrentPath(); |
| 1929 |
auto path = cwd.evalNative(pathStr); |
| 1930 |
|
| 1931 |
if (path.size() == 0) return disk->getRoot(); |
| 1932 |
|
| 1933 |
KJ_IF_MAYBE(sdir, sourceDirectories.find(path)) { |
| 1934 |
sdir->isSourcePrefix = sdir->isSourcePrefix || isSourcePrefix; |
| 1935 |
return *sdir->dir; |
| 1936 |
} |
| 1937 |
|
| 1938 |
if (path == cwd) { |
| 1939 |
// Slight hack if the working directory is explicitly specified: |
| 1940 |
// - We want to avoid opening a new copy of the working directory, as tryOpenSubdir() would |
| 1941 |
// do. |
| 1942 |
// - If isSourcePrefix is true, we need to add it to sourceDirectories to track that. |
| 1943 |
// Otherwise we don't need to add it at all. |
| 1944 |
// - We do not need to add it to dirPrefixes since the cwd is already handled in |
| 1945 |
// getDisplayName(). |
| 1946 |
auto& result = disk->getCurrent(); |
| 1947 |
if (isSourcePrefix) { |
| 1948 |
kj::Own<const kj::ReadableDirectory> fakeOwn(&result, kj::NullDisposer::instance); |
| 1949 |
sourceDirectories.insert(kj::mv(path), { kj::mv(fakeOwn), isSourcePrefix }); |
| 1950 |
} |
| 1951 |
return result; |
| 1952 |
} |
| 1953 |
|
| 1954 |
KJ_IF_MAYBE(dir, disk->getRoot().tryOpenSubdir(path)) { |
| 1955 |
auto& result = *dir->get(); |
| 1956 |
sourceDirectories.insert(kj::mv(path), { kj::mv(*dir), isSourcePrefix }); |
| 1957 |
#if _WIN32 |
| 1958 |
kj::String prefix = pathStr.endsWith("/") || pathStr.endsWith("\\") |
| 1959 |
? kj::str(pathStr) : kj::str(pathStr, '\\'); |
| 1960 |
#else |
| 1961 |
kj::String prefix = pathStr.endsWith("/") ? kj::str(pathStr) : kj::str(pathStr, '/'); |
| 1962 |
#endif |
| 1963 |
dirPrefixes.insert(&result, kj::mv(prefix)); |
| 1964 |
return result; |
| 1965 |
} else { |
| 1966 |
return nullptr; |
| 1967 |
} |
| 1968 |
} |
| 1969 |
|
| 1970 |
struct DirPathPair { |
| 1971 |
const kj::ReadableDirectory& dir; |
| 1972 |
kj::Path path; |
| 1973 |
}; |
| 1974 |
|
| 1975 |
DirPathPair interpretSourceFile(kj::StringPtr pathStr) { |
| 1976 |
auto cwd = disk->getCurrentPath(); |
| 1977 |
auto path = cwd.evalNative(pathStr); |
| 1978 |
|
| 1979 |
KJ_REQUIRE(path.size() > 0); |
| 1980 |
for (size_t i = path.size() - 1; i > 0; i--) { |
| 1981 |
auto prefix = path.slice(0, i); |
| 1982 |
auto remainder = path.slice(i, path.size()); |
| 1983 |
|
| 1984 |
KJ_IF_MAYBE(sdir, sourceDirectories.find(prefix)) { |
| 1985 |
if (sdir->isSourcePrefix) { |
| 1986 |
return { *sdir->dir, remainder.clone() }; |
| 1987 |
} |
| 1988 |
} |
| 1989 |
} |
| 1990 |
|
| 1991 |
// No source prefix matched. Fall back to heuristic: try stripping the current directory, |
| 1992 |
// otherwise don't strip anything. |
| 1993 |
if (path.startsWith(cwd)) { |
| 1994 |
return { disk->getCurrent(), path.slice(cwd.size(), path.size()).clone() }; |
| 1995 |
} else { |
| 1996 |
// Hmm, no src-prefix matched and the file isn't even in the current directory. This might |
| 1997 |
// be OK if we aren't generating any output anyway, but otherwise the results will almost |
| 1998 |
// certainly not be what the user wanted. Let's print a warning, unless the output directives |
| 1999 |
// are ones which we know do not produce output files. This is a hack. |
| 2000 |
for (auto& output: outputs) { |
| 2001 |
auto name = kj::str(output.name); |
| 2002 |
if (name != "-" && name != "capnp") { |
| 2003 |
context.warning(kj::str(pathStr, |
| 2004 |
": File is not in the current directory and does not match any prefix defined with " |
| 2005 |
"--src-prefix. Please pass an appropriate --src-prefix so I can figure out where to " |
| 2006 |
"write the output for this file.")); |
| 2007 |
break; |
| 2008 |
} |
| 2009 |
} |
| 2010 |
|
| 2011 |
return { disk->getRoot(), kj::mv(path) }; |
| 2012 |
} |
| 2013 |
} |
| 2014 |
|
| 2015 |
kj::String getDisplayName(const kj::ReadableDirectory& dir, kj::PathPtr path) { |
| 2016 |
KJ_IF_MAYBE(prefix, dirPrefixes.find(&dir)) { |
| 2017 |
return kj::str(*prefix, path.toNativeString()); |
| 2018 |
} else if (&dir == &disk->getRoot()) { |
| 2019 |
return path.toNativeString(true); |
| 2020 |
} else if (&dir == &disk->getCurrent()) { |
| 2021 |
return path.toNativeString(false); |
| 2022 |
} else { |
| 2023 |
KJ_FAIL_ASSERT("unrecognized directory"); |
| 2024 |
} |
| 2025 |
} |
| 2026 |
}; |
| 2027 |
|
| 2028 |
} // namespace compiler |
| 2029 |
} // namespace capnp |
| 2030 |
|
| 2031 |
KJ_MAIN(capnp::compiler::CompilerMain); |