-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathJsFunctionsScanner.php
More file actions
395 lines (330 loc) · 11.8 KB
/
JsFunctionsScanner.php
File metadata and controls
395 lines (330 loc) · 11.8 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
<?php
namespace WP_CLI\I18n;
use Gettext\Utils\JsFunctionsScanner as GettextJsFunctionsScanner;
use Gettext\Utils\ParsedComment;
use Peast\Peast;
use Peast\Syntax\Node;
use Peast\Traverser;
final class JsFunctionsScanner extends GettextJsFunctionsScanner {
/**
* If not false, comments will be extracted.
*
* @var string|false|array
*/
private $extract_comments = false;
/**
* Holds a list of source code comments already added to a string.
*
* Prevents associating the same comment to multiple strings.
*
* @var Node\Comment[] $comments_cache
*/
private $comments_cache = [];
/**
* Enable extracting comments that start with a tag (if $tag is empty all the comments will be extracted).
*
* @param mixed $tag
*/
public function enableCommentsExtraction( $tag = '' ) {
$this->extract_comments = $tag;
}
/**
* Disable comments extraction.
*/
public function disableCommentsExtraction() {
$this->extract_comments = false;
}
/**
* {@inheritdoc}
*/
public function saveGettextFunctions( $translations, array $options ) {
// Ignore multiple translations for now.
// @todo Add proper support for multiple translations.
if ( is_array( $translations ) ) {
$translations = $translations[0];
}
$peast_options = [
'sourceType' => Peast::SOURCE_TYPE_MODULE,
'comments' => false !== $this->extract_comments,
'jsx' => true,
];
$ast = Peast::latest( $this->code, $peast_options )->parse();
$traverser = new Traverser();
$all_comments = [];
/**
* Traverse through JS code to find and extract gettext functions.
*
* Make sure translator comments in front of variable declarations
* and inside nested call expressions are available when parsing the function call.
*/
$traverser->addFunction(
function ( $node ) use ( &$translations, $options, &$all_comments ) {
$functions = $options['functions'];
$file = $options['file'];
$add_reference = ! empty( $options['addReferences'] );
/** @var Node\Node $node */
foreach ( $node->getLeadingComments() as $comment ) {
$all_comments[] = $comment;
}
/** @var Node\CallExpression $node */
if ( 'CallExpression' !== $node->getType() ) {
return;
}
$callee = $this->resolveExpressionCallee( $node );
if ( ! $callee || ! isset( $functions[ $callee['name'] ] ) ) {
return;
}
/** @var Node\CallExpression $node */
foreach ( $node->getArguments() as $argument ) {
// Support nested function calls.
$argument->setLeadingComments( $argument->getLeadingComments() + $node->getLeadingComments() );
}
foreach ( $callee['comments'] as $comment ) {
$all_comments[] = $comment;
}
$domain = null;
$original = null;
$context = null;
$plural = null;
$args = [];
/** @var Node\Node $argument */
foreach ( $node->getArguments() as $argument ) {
foreach ( $argument->getLeadingComments() as $comment ) {
$all_comments[] = $comment;
}
if (
'Identifier' === $argument->getType() ||
'Expression' === substr( $argument->getType(), -strlen( 'Expression' ) )
) {
$args[] = ''; // The value doesn't matter as it's unused.
continue;
}
if ( 'Literal' === $argument->getType() ) {
/** @var Node\Literal $argument */
$args[] = $argument->getValue();
continue;
}
if ( 'TemplateLiteral' === $argument->getType() && 0 === count( $argument->getExpressions() ) ) {
/** @var Node\TemplateLiteral $argument */
/** @var Node\TemplateElement[] $parts */
// Since there are no expressions within the TemplateLiteral, there is only one TemplateElement.
$parts = $argument->getParts();
$args[] = $parts[0]->getValue();
continue;
}
// If we reach this, an unsupported argument type has been encountered.
// Do not try to parse this function call at all.
return;
}
switch ( $functions[ $callee['name'] ] ) {
case 'text_domain':
case 'gettext':
list( $original, $domain ) = array_pad( $args, 2, null );
break;
case 'text_context_domain':
list( $original, $context, $domain ) = array_pad( $args, 3, null );
break;
case 'single_plural_number_domain':
list( $original, $plural, $number, $domain ) = array_pad( $args, 4, null );
break;
case 'single_plural_number_context_domain':
list( $original, $plural, $number, $context, $domain ) = array_pad( $args, 5, null );
break;
}
if ( '' === (string) $original ) {
return;
}
if ( $domain !== $translations->getDomain() && null !== $translations->getDomain() ) {
return;
}
if ( isset( $options['line'] ) ) {
$line = $options['line'];
} else {
$line = $node->getLocation()->getStart()->getLine();
}
$translation = $translations->insert( $context, $original, $plural );
if ( $add_reference ) {
$translation->addReference( $file, $line );
}
if (
1 === preg_match( MakePotCommand::SPRINTF_PLACEHOLDER_REGEX, $original ) ||
1 === preg_match( MakePotCommand::UNORDERED_SPRINTF_PLACEHOLDER_REGEX, $original )
) {
$translation->addFlag( 'js-format' );
}
/** @var Node\Comment $comment */
foreach ( $all_comments as $comment ) {
// Comments should be before the translation.
if ( ! $this->commentPrecedesNode( $comment, $node ) ) {
continue;
}
if ( in_array( $comment, $this->comments_cache, true ) ) {
continue;
}
$parsed_comment = ParsedComment::create( $comment->getRawText(), $comment->getLocation()->getStart()->getLine() );
$prefixes = array_filter( (array) $this->extract_comments );
if ( $parsed_comment->checkPrefixes( $prefixes ) ) {
$translation->addExtractedComment( $parsed_comment->getComment() );
$this->comments_cache[] = $comment;
}
}
if ( isset( $parsed_comment ) ) {
$all_comments = [];
}
}
);
/**
* Traverse through JS code contained within eval() to find and extract gettext functions.
*/
$scanner = $this;
$traverser->addFunction(
function ( $node ) use ( &$translations, $options, $scanner ) {
/** @var Node\CallExpression $node */
if ( 'CallExpression' !== $node->getType() ) {
return;
}
$callee = $this->resolveExpressionCallee( $node );
if ( ! $callee || 'eval' !== $callee['name'] ) {
return;
}
$eval_contents = '';
/** @var Node\Node $argument */
foreach ( $node->getArguments() as $argument ) {
if ( 'Literal' === $argument->getType() ) {
/** @var Node\Literal $argument */
$eval_contents = $argument->getValue();
break;
}
}
if ( ! $eval_contents ) {
return;
}
// Override the line location to be that of the eval().
$options['line'] = $node->getLocation()->getStart()->getLine();
$class = get_class( $scanner );
$evals = new $class( $eval_contents );
$evals->enableCommentsExtraction( $options['extractComments'] );
$evals->saveGettextFunctions( $translations, $options );
}
);
$traverser->traverse( $ast );
}
/**
* Resolve the callee of a call expression using known formats.
*
* @param Node\CallExpression $node The call expression whose callee to resolve.
*
* @return array|bool Array containing the name and comments of the identifier if resolved. False if not.
*/
private function resolveExpressionCallee( Node\CallExpression $node ) {
$callee = $node->getCallee();
// If the callee is a simple identifier it can simply be returned.
// For example: __( "translation" ).
if ( 'Identifier' === $callee->getType() ) {
return [
'name' => $callee->getName(),
'comments' => $callee->getLeadingComments(),
];
}
// If the callee is a member expression resolve it to the property.
// For example: wp.i18n.__( "translation" ) or u.__( "translation" ).
if (
'MemberExpression' === $callee->getType() &&
'Identifier' === $callee->getProperty()->getType()
) {
// Make sure to unpack wp.i18n which is a nested MemberExpression.
$comments = 'MemberExpression' === $callee->getObject()->getType()
? $callee->getObject()->getObject()->getLeadingComments()
: $callee->getObject()->getLeadingComments();
return [
'name' => $callee->getProperty()->getName(),
'comments' => $comments,
];
}
// If the callee is a call expression as created by Webpack resolve it.
// For example: Object(u.__)( "translation" ).
if (
'CallExpression' === $callee->getType() &&
'Identifier' === $callee->getCallee()->getType() &&
'Object' === $callee->getCallee()->getName() &&
[] !== $callee->getArguments() &&
'MemberExpression' === $callee->getArguments()[0]->getType()
) {
$property = $callee->getArguments()[0]->getProperty();
// Matches minified webpack statements: Object(u.__)( "translation" ).
if ( 'Identifier' === $property->getType() ) {
return [
'name' => $property->getName(),
'comments' => $callee->getCallee()->getLeadingComments(),
];
}
// Matches unminified webpack statements:
// Object(_wordpress_i18n__WEBPACK_IMPORTED_MODULE_7__["__"])( "translation" );
if ( 'Literal' === $property->getType() ) {
$name = $property->getValue();
// Matches mangled webpack statement:
// Object(_wordpress_i18n__WEBPACK_IMPORTED_MODULE_7__[/* __ */ "a"])( "translation" );
$leading_property_comments = $property->getLeadingComments();
if ( count( $leading_property_comments ) === 1 && $leading_property_comments[0]->getKind() === 'multiline' ) {
$name = trim( $leading_property_comments[0]->getText() );
}
return [
'name' => $name,
'comments' => $callee->getCallee()->getLeadingComments(),
];
}
}
// If the callee is an indirect function call as created by babel, resolve it.
// For example: `(0, u.__)( "translation" )`.
if (
'ParenthesizedExpression' === $callee->getType()
&& 'SequenceExpression' === $callee->getExpression()->getType()
&& 2 === count( $callee->getExpression()->getExpressions() )
&& 'Literal' === $callee->getExpression()->getExpressions()[0]->getType()
&& [] !== $node->getArguments()
) {
// Matches any general indirect function call: `(0, __)( "translation" )`.
if ( 'Identifier' === $callee->getExpression()->getExpressions()[1]->getType() ) {
return [
'name' => $callee->getExpression()->getExpressions()[1]->getName(),
'comments' => $callee->getLeadingComments(),
];
}
// Matches indirect function calls used by babel for module imports: `(0, _i18n.__)( "translation" )`.
if ( 'MemberExpression' === $callee->getExpression()->getExpressions()[1]->getType() ) {
$property = $callee->getExpression()->getExpressions()[1]->getProperty();
if ( 'Identifier' === $property->getType() ) {
return [
'name' => $property->getName(),
'comments' => $callee->getLeadingComments(),
];
}
}
}
// Unknown format.
return false;
}
/**
* Returns whether or not a comment precedes a node.
* The comment must be before the node and on the same line or the one before.
*
* @param Node\Comment $comment The comment.
* @param Node\Node $node The node.
*
* @return bool Whether or not the comment precedes the node.
*/
private function commentPrecedesNode( Node\Comment $comment, Node\Node $node ) {
// Comments should be on the same or an earlier line than the translation.
if ( $node->getLocation()->getStart()->getLine() - $comment->getLocation()->getEnd()->getLine() > 1 ) {
return false;
}
// Comments on the same line should be before the translation.
if (
$node->getLocation()->getStart()->getLine() === $comment->getLocation()->getEnd()->getLine() &&
$node->getLocation()->getStart()->getColumn() < $comment->getLocation()->getStart()->getColumn()
) {
return false;
}
return true;
}
}