forked from hhvm/hack-codegen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodegenFunctionBase.php
More file actions
284 lines (249 loc) · 8.02 KB
/
CodegenFunctionBase.php
File metadata and controls
284 lines (249 loc) · 8.02 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
<?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.
*/
/**
* Base class to generate a function or a method.
*/
abstract class CodegenFunctionBase
implements ICodeBuilderRenderer {
use HackBuilderRenderer;
protected string $name;
protected ?string $body = null;
protected ?string $docBlock = 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 Map<string, ImmVector<Stringish>> $userAttributes = Map {};
protected Vector<string> $parameters = Vector {};
protected ?CodegenGeneratedFrom $generatedFrom;
public function __construct(
protected IHackCodegenConfig $config,
string $name,
) {
$this->name = $name;
}
public function setIsAsync(bool $value = true): this {
$this->isAsync = $value;
return $this;
}
public function setIsOverride(bool $value = true): this {
$this->isOverride = $value;
return $this;
}
public function setIsMemoized(bool $value = true): this {
$this->isMemoized = $value;
return $this;
}
/* HH_FIXME[4033] variadic params with type constraints are not supported */
public function setUserAttribute(string $attribute_name, ...$args): this {
$this->userAttributes[$attribute_name] = new ImmVector($args);
return $this;
}
/* HH_FIXME[4033] variadic params with type constraints are not supported */
public function setReturnType(string $type, ...$args): this {
$type = vsprintf($type, $args);
if ($type) {
$this->returnType = $type;
}
return $this;
}
/* HH_FIXME[4033] variadic params with type constraints are not supported */
public function addParameter(string $param, ...$args): this {
$param = vsprintf($param, $args);
$this->parameters->add($param);
return $this;
}
public function setParameters(Vector<string> $params): this {
$this->parameters = $params;
return $this;
}
/* HH_FIXME[4033] variadic params with type constraints are not supported */
public function setBody(string $body, ...$args): this {
if (count($args)) {
$this->body = vsprintf($body, $args);
} else {
$this->body = $body;
}
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(): Vector<string> {
return $this->parameters;
}
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 = hack_builder()
->add($keywords)
->add(
'%s(%s)',
$this->name,
implode(', ', $this->parameters->toArray())
)
->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::len($code) <=
$this->config->getMaxLineLength() - 4 + (int)$is_abstract ||
$this->fixme !== null) {
return hack_builder()
->add($code)
->getCode();
} else {
$parameter_lines = $this->parameters
->map(function(string $line) { return $line.","; });
$multi_line_builder = hack_builder()
->add($keywords)
->addLine("$this->name(")
->indent()
->addLines($parameter_lines)
->unindent()
->add(')')
->addIf($this->returnType !== null, ': ' . $this->returnType);
return $multi_line_builder->getCode();
}
}
protected function getMaxCodeLength(): int {
$max_length = $this->config->getMaxLineLength();
if ($this instanceof CodegenMethodBase) {
$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->hasFunctionAnnotation()) {
$builder->ensureNewLine()->addLine($this->getFunctionAnnotation());
}
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->beginManualSection($containing_class_name. $this->name);
$builder->add($this->body);
$builder->endManualSection();
} else {
$builder->add($this->body);
}
$builder->closeBrace();
return $builder;
}
private function hasFunctionAnnotation(): bool {
return $this->getFunctionAnnotation() !== null;
}
private function getFunctionAnnotation(): ?string {
$annotations = Vector {};
if ($this->isOverride) {
$annotations->add('__Override');
}
if ($this->isMemoized) {
$annotations->add('__Memoize');
}
foreach ($this->userAttributes as $attribute_name => $arguments) {
$annotations->add($arguments
? $attribute_name.'('.implode(',', $arguments).')'
: $attribute_name,
);
}
return $annotations ?
'<<'.implode(', ', $annotations).'>>' :
null;
}
private function getFunctionDeclaration(): string {
// $keywords is shared by both single and multi line declaration
$keywords = hack_builder()
->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);
}
}