forked from hhvm/hack-codegen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodegenFile.php
More file actions
401 lines (345 loc) · 10.6 KB
/
CodegenFile.php
File metadata and controls
401 lines (345 loc) · 10.6 KB
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
<?hh // strict
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
enum CodegenFileResult: int {
NONE = 0;
UPDATE = 1;
CREATE = 2;
}
/**
* File of generated code. The file is composed by classes.
* The file will be signed, either as autogenerated or partially generated,
* depending on whether there are manual sections.
*/
final class CodegenFile {
private bool $isStrict = false;
private ?string $docBlock;
private string $fileName;
private string $relativeFileName;
private Vector<string> $otherFileNames = Vector {};
private Vector<CodegenClassBase> $classes = Vector {};
private Vector<CodegenTrait> $traits = Vector {};
private Vector<CodegenFunction> $functions = Vector {};
private Vector<CodegenType> $beforeTypes = Vector {};
private Vector<CodegenType> $afterTypes = Vector {};
private bool $doClobber = false;
protected ?CodegenGeneratedFrom $generatedFrom;
private bool $isSignedFile = true;
private ?Map<string, Vector<string>> $rekey = null;
private bool $createOnly = false;
private ?ICodegenFormatter $formatter;
public function __construct(
private IHackCodegenConfig $config,
string $file_name,
) {
$root = $config->getRootDir();
if (!Str::startsWith($file_name, '/')) {
$this->relativeFileName = $file_name;
$file_name = $root.'/'.$file_name;
} else if (Str::startsWith($file_name, $root)) {
$this->relativeFileName = substr(
$file_name,
Str::len($root) + 1,
);
} else {
$this->relativeFileName = $file_name;
}
$this->fileName = $file_name;
}
/**
* Use this when refactoring generated code. Say you're renaming a class, but
* want to pull the manual code sections from the old file. Use this.
*/
public function addOriginalFile(string $file_name): this {
$this->otherFileNames[] = $file_name;
return $this;
}
public function addClasses(ConstVector<CodegenClassBase> $classes): this {
foreach ($classes as $class) {
$this->addClass($class);
}
return $this;
}
public function addClass(CodegenClassBase $class): this {
$this->classes[] = $class;
return $this;
}
public function getClasses(): Vector<CodegenClassBase> {
return $this->classes;
}
public function addTrait(CodegenTrait $trait): this {
$this->traits[] = $trait;
return $this;
}
public function addFunctions(ConstVector<CodegenFunction> $functions): this {
foreach ($functions as $function) {
$this->addFunction($function);
}
return $this;
}
public function addFunction(CodegenFunction $function): this {
$this->functions[] = $function;
return $this;
}
public function getFunctions(): Vector<CodegenFunction> {
return $this->functions;
}
public function addBeforeTypes(Vector<CodegenType> $types): this {
foreach ($types as $type) {
$this->addBeforeType($type);
}
return $this;
}
public function addBeforeType(CodegenType $type): this {
$this->beforeTypes[] = $type;
return $this;
}
public function getBeforeTypes(): Vector<CodegenType> {
return $this->beforeTypes;
}
public function addAfterTypes(Vector<CodegenType> $types): this {
foreach ($types as $type) {
$this->addAfterType($type);
}
return $this;
}
public function addAfterType(CodegenType $type): this {
$this->afterTypes[] = $type;
return $this;
}
public function getAfterTypes(): Vector<CodegenType> {
return $this->afterTypes;
}
/**
* The absolute path.
*/
public function getFileName(): string {
return $this->fileName;
}
public function getRelativeFileName(): string {
return $this->relativeFileName;
}
public function exists(): bool {
return file_exists($this->fileName);
}
/**
* Use this to pull manual code from a section keyed by $old_key and
* place it in a section keyed by $new_key.
* Note that $old_key could even be in a separate file, if you use
* addOriginalFile.
*/
public function rekeyManualSection(string $old_key, string $new_key): this {
if ($this->rekey === null) {
$this->rekey = Map {};
}
$rekey = $this->rekey;
if (!$rekey->containsKey($new_key)) {
$rekey[$new_key] = Vector { $old_key };
} else {
$rekey[$new_key][] = $old_key;
}
return $this;
}
/**
* Whether the generated file will be Hack strict mode
*/
public function setIsStrict(bool $value): this {
$this->isStrict = $value;
return $this;
}
public function setDocBlock(string $comment): this {
$this->docBlock = $comment;
return $this;
}
public function setIsSignedFile(bool $value): this {
$this->isSignedFile = $value;
return $this;
}
public function setFormatter(ICodegenFormatter $formatter): this {
$this->formatter = $formatter;
return $this;
}
public function getFormatter(): ?ICodegenFormatter {
return $this->formatter;
}
public function render(): string {
$builder = hack_builder();
$first_line = '<?hh';
if ($this->isStrict) {
$first_line .= ' // strict';
}
$builder->addLine($first_line);
$header = $this->config->getFileHeader();
if ($header) {
foreach ($header as $line) {
$builder->addInlineComment($line);
}
}
$content = $this->getContent();
if ($this->formatter !== null) {
$content = $this->formatter->format($content, $this->getFileName());
}
if (!$this->isSignedFile) {
$builder->add($content);
return $builder->getCode();
}
$old_content = $this->loadExistingFiles();
$doc_block = $this->docBlock;
if ($this->generatedFrom !== null) {
$doc_block = $doc_block. $this->generatedFrom->render() ."\n";
}
if (PartiallyGeneratedCode::containsManualSection($content)) {
$builder->addDocBlock(
PartiallyGeneratedSignedSource::getDocBlock($doc_block)
);
$builder->add($content);
$code = $builder->getCode();
$partial = new PartiallyGeneratedCode($code);
if ($old_content !== null) {
$code = $partial->merge($old_content, $this->rekey);
} else {
$partial->assertValidManualSections();
}
return PartiallyGeneratedSignedSource::signFile($code);
} else {
$builder->addDocBlock(SignedSource::getDocBlock($doc_block));
$builder->add($content);
return SignedSource::signFile($builder->getCode());
}
}
/**
* Use this to skip reading in the existing file.
* Only use when you're sure you're okay with blowing away the previous file.
*/
public function setDoClobber(bool $do_force): this {
$this->doClobber = $do_force;
return $this;
}
private function getContent(): string {
$builder = hack_builder();
foreach ($this->beforeTypes as $type) {
$builder->ensureNewLine()->newLine();
$builder->add($type->render());
}
foreach ($this->functions as $function) {
$builder->ensureNewLine()->newLine();
$builder->add($function->render());
}
foreach ($this->classes as $class) {
$builder->ensureNewLine()->newLine();
$builder->add($class->render());
}
foreach ($this->traits as $trait) {
$builder->ensureNewLine()->newLine();
$builder->add($trait->render());
}
foreach ($this->afterTypes as $type) {
$builder->ensureNewLine()->newLine();
$builder->add($type->render());
}
return $builder->getCode();
}
private function loadExistingFiles(): ?string {
$file_names = $this->otherFileNames;
$file_names[] = $this->fileName;
$all_content = array();
foreach ($file_names as $file_name) {
if (file_exists($file_name)) {
$content = Filesystem::readFile($file_name);
if ($content) {
$root_dir = $this->config->getRootDir();
$relative_path = Str::startsWith($file_name, $root_dir)
? Str::substr($file_name, Str::len($root_dir) + 1)
: $file_name;
if (!$this->doClobber) {
if (!SignedSourceBase::isSignedByAnySigner($content)) {
throw new CodegenFileNoSignatureException($relative_path);
}
if (!SignedSourceBase::hasValidSignatureFromAnySigner($content)) {
throw new CodegenFileBadSignatureException($relative_path);
}
}
}
$all_content[] = $content;
}
}
return implode('', $all_content);
}
public function setGeneratedFrom(
CodegenGeneratedFrom $from
): this {
$this->generatedFrom = $from;
return $this;
}
/**
* If called, save() will only write the file if it doesn't exist
*/
public function createOnly(): this {
$this->createOnly = true;
return $this;
}
/**
* Saves the generated file.
*
* @return CodegenFileResultType
*/
public function save(): CodegenFileResult {
Filesystem::createDirectory(
substr($this->fileName, 0, strrpos($this->fileName, '/')),
0777,
);
$is_creating = !file_exists($this->fileName);
if (!$is_creating && $this->createOnly) {
return CodegenFileResult::NONE;
}
$changed = Filesystem::writeFileIfChanged(
$this->fileName,
$this->render(),
);
return $is_creating
? CodegenFileResult::CREATE
: ($changed ? CodegenFileResult::UPDATE : CodegenFileResult::NONE);
}
}
/* HH_FIXME[4033] variadic params with type constraints are not supported */
function codegen_file(string $file_name, ...$args): CodegenFile {
$file_name = vsprintf($file_name, $args);
return new CodegenFile(HackCodegenConfig::getInstance(), $file_name);
}
abstract class CodegenFileSignatureException extends Exception {
public function __construct(
string $message,
private string $fileName,
) {
parent::__construct($message);
}
public function getFileName(): string {
return $this->fileName;
}
}
final class CodegenFileBadSignatureException
extends CodegenFileSignatureException {
public function __construct(string $file_name) {
$message = sprintf(
'The signature of the existing generated file \'%s\' is invalid',
$file_name,
);
parent::__construct($message, $file_name);
}
}
final class CodegenFileNoSignatureException
extends CodegenFileSignatureException {
public function __construct(string $file_name) {
$message = sprintf(
'The existing generated file \'%s\' does not have a signature',
$file_name,
);
parent::__construct($message, $file_name);
}
}