forked from hhvm/hack-codegen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodegenFunctionish.hack
More file actions
341 lines (296 loc) · 9.26 KB
/
CodegenFunctionish.hack
File metadata and controls
341 lines (296 loc) · 9.26 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
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
namespace Facebook\HackCodegen;
use namespace HH\Lib\{Keyset, Str, Vec};
/**
* Base class to generate a function or a method.
*/
abstract class CodegenFunctionish implements ICodeBuilderRenderer {
use HackBuilderRenderer;
use CodegenWithAttributes;
protected string $name;
protected ?string $body = null;
protected ?string $docBlock = null;
protected ?keyset<string> $contexts = null;
protected ?string $returnType = null;
private ?string $fixme = null;
protected bool $isAsync = false;
protected bool $isOverride = false;
protected bool $isManualBody = false;
protected bool $isMemoized = false;
protected vec<string> $parameters = vec[];
protected ?CodegenGeneratedFrom $generatedFrom;
public function __construct(
protected IHackCodegenConfig $config,
string $name,
) {
$this->name = $name;
}
public function setName(string $name): this {
$this->name = $name;
return $this;
}
public function setIsAsync(bool $value = true): this {
$this->isAsync = $value;
return $this;
}
public function setIsMemoized(bool $value = true): this {
$this->isMemoized = $value;
return $this;
}
public function addContext(
string $context,
): this {
if($this->contexts === null) {
$this->contexts = keyset<string>[$context];
} else {
$this->contexts[] = $context;
}
return $this;
}
public function addContexts(
Traversable<string> $contexts,
): this {
$contexts = keyset($contexts);
if (C\is_empty($contexts)) {
// Don't accidentally convert `foo(): void` to `foo()[]: void`;
// `addContexts()` should only make things *more* permissive
return $this;
}
if ($this->contexts is null || C\is_empty($this->contexts)) {
$this->contexts = $contexts;
} else {
$this->contexts = Keyset\union($this->contexts, $contexts);
}
return $this;
}
/** Set or remove the contexts.
*
* - if passed `null`, the function or method will not contain a contexts
* declaration, e.g. `function foo(): void {}`; this is equivalent to
* `function foo()[defaults]: void {}`
* - if passed the empty set (e.g. `keyset[]`), the function will have an
* empty contexts declaration, e.g. `function foo()[]: void {}`. This is
* considered to be an approximation of declaration pure functions.
*/
public function setContexts(
?Container<string> $contexts,
): this {
$this->contexts = ($contexts is null) ? null : keyset($contexts);
return $this;
}
public function setReturnType(string $type): this {
return $this->setReturnTypef('%s', $type);
}
public function setReturnTypef(
Str\SprintfFormatString $type,
mixed ...$args
): this {
$type = \vsprintf($type, $args);
if ($type) {
$this->returnType = $type;
}
return $this;
}
public function addParameter(string $param): this {
return $this->addParameterf('%s', $param);
}
public function addParameterf(
Str\SprintfFormatString $param,
mixed ...$args
): this {
$param = \vsprintf($param, $args);
$this->parameters[] = $param;
return $this;
}
public function addParameters(Traversable<string> $params): this {
foreach ($params as $param) {
$this->addParameter($param);
}
return $this;
}
public function setBody(string $body): this {
return $this->setBodyf('%s', $body);
}
public function setBodyf(
Str\SprintfFormatString $body,
mixed ...$args
): this {
$this->body = \vsprintf($body, $args);
return $this;
}
public function setManualBody(bool $val = true): this {
if ($val) {
if ($this->body === null) {
$this->body = "throw new ViolationException('Unimplemented');";
}
}
$this->isManualBody = $val;
return $this;
}
public function setDocBlock(string $comment): this {
$this->docBlock = $comment;
return $this;
}
public function setGeneratedFrom(CodegenGeneratedFrom $from): this {
$this->generatedFrom = $from;
return $this;
}
public function getName(): string {
return $this->name;
}
public function getParameters(): vec<string> {
return $this->parameters;
}
public function getContexts(): ?keyset<string> {
return $this->contexts;
}
public function getReturnType(): ?string {
return $this->returnType;
}
public function isManualBody(): bool {
return $this->isManualBody;
}
/**
* Break lines for function declaration. First calculate the string length as
* if there were no line break. If the string exceeds one line, try break
* by having each parameter per line.
*
* $is_abstract - only valid for CodegenMethodX for code reuse purposes
*/
protected function getFunctionDeclarationBase(
string $keywords,
bool $is_abstract = false,
): string {
$builder = (new HackBuilder($this->config))
->add($keywords)
->addf('%s(%s)', $this->name, Str\join($this->parameters, ', '))
->addIf($this->contexts !== null, '[' . Str\join($this->contexts ?? keyset[], ', ') . ']')
->addIf($this->returnType !== null, ': '.($this->returnType ?? ''));
$code = $builder->getCode();
// If the total length is longer than max len, try to break it. Otherwise
// return Total length = 2 (indent) + codelength + 2 or 1 (" {" or ";")
// If the function/method is abstract, the ";" will be appended later
// Therefore it has one char less than non-abstract functions, which has "{"
if (
Str\length($code) <=
$this->config->getMaxLineLength() - 4 + (int)$is_abstract ||
$this->fixme !== null
) {
return (new HackBuilder($this->config))->add($code)->getCode();
} else {
$parameter_lines = Vec\map(
$this->parameters,
$line ==> {
if (Str\search($line, '...$') !== null) {
return $line;
}
return $line.',';
},
);
$multi_line_builder = (new HackBuilder($this->config))
->add($keywords)
->addLine($this->name.'(')
->indent()
->addLines($parameter_lines)
->unindent()
->add(')')
->addIf($this->contexts !== null, '[' . Str\join($this->contexts ?? keyset[], ', ') . ']')
->addIf($this->returnType !== null, ': '.($this->returnType ?? ''));
return $multi_line_builder->getCode();
}
}
protected function getMaxCodeLength(): int {
$max_length = $this->config->getMaxLineLength();
if ($this is CodegenMethodish) {
$max_length -= $this->config->getSpacesPerIndentation();
}
return $max_length;
}
public function addHHFixMe(int $code, string $why): this {
$max_length = $this->getMaxCodeLength() - 6;
$str = \sprintf('HH_FIXME[%d] %s', $code, $why);
invariant(
\strlen($str) <= $max_length,
'ERROR: Your fixme has to fit on one line, with indentation '.
'and comments. So you need to shorten your message by %d '.
'characters.',
\strlen($str) - $max_length,
);
$this->fixme = $str;
return $this;
}
/**
* $is_abstract and $containing_class_name
* only valid for CodegenMethodX for code reuse purposes
*/
protected function appendToBuilderBase(
HackBuilder $builder,
string $func_declaration,
bool $is_abstract = false,
string $containing_class_name = '',
): HackBuilder {
if ($this->docBlock !== null && $this->docBlock !== '') {
if ($this->generatedFrom) {
$builder->addDocBlock(
$this->docBlock."\n(".$this->generatedFrom->render().')',
);
} else {
$builder->addDocBlock($this->docBlock);
}
} else {
if ($this->generatedFrom) {
$builder->addInlineComment($this->generatedFrom->render());
}
}
if ($this->hasAttributes()) {
$builder->ensureNewLine()->addLine($this->renderAttributes());
}
if ($this->fixme !== null) {
$builder->addInlineCommentWithStars($this->fixme);
}
$builder->add($func_declaration);
if ($is_abstract) {
$builder->addLine(';');
return $builder;
}
$builder->openBrace();
if ($this->isManualBody) {
$builder->startManualSection($containing_class_name.$this->name);
$builder->add($this->body);
$builder->endManualSection();
} else {
$builder->add($this->body);
}
$builder->closeBrace();
return $builder;
}
protected function getExtraAttributes(): dict<string, vec<string>> {
$attributes = dict[];
if ($this->isOverride) {
$attributes['__Override'] = vec[];
}
if ($this->isMemoized) {
$attributes['__Memoize'] = vec[];
}
return $attributes;
}
private function getFunctionDeclaration(): string {
// $keywords is shared by both single and multi line declaration
$keywords = (new HackBuilder($this->config))
->addIf($this->isAsync, 'async ')
->add('function ')
->getCode();
return $this->getFunctionDeclarationBase($keywords);
}
public function appendToBuilder(HackBuilder $builder): HackBuilder {
$func_declaration = $this->getFunctionDeclaration();
return $this->appendToBuilderBase($builder, $func_declaration);
}
}