001    /*
002     * Copyright 2010-2013 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.k2js.translate.utils;
018    
019    import com.google.dart.compiler.backend.js.ast.*;
020    import com.intellij.util.SmartList;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.annotations.Nullable;
023    import org.jetbrains.jet.lang.types.expressions.OperatorConventions;
024    import org.jetbrains.k2js.translate.context.Namer;
025    import org.jetbrains.k2js.translate.context.TranslationContext;
026    
027    import java.util.Arrays;
028    import java.util.Collections;
029    import java.util.List;
030    
031    public final class JsAstUtils {
032        private static final JsNameRef DEFINE_PROPERTY = new JsNameRef("defineProperty");
033        public static final JsNameRef CREATE_OBJECT = new JsNameRef("create");
034    
035        private static final JsNameRef VALUE = new JsNameRef("value");
036        private static final JsPropertyInitializer WRITABLE = new JsPropertyInitializer(new JsNameRef("writable"), JsLiteral.TRUE);
037        private static final JsPropertyInitializer ENUMERABLE = new JsPropertyInitializer(new JsNameRef("enumerable"), JsLiteral.TRUE);
038    
039        public static final String LENDS_JS_DOC_TAG = "lends";
040    
041        static {
042            JsNameRef globalObjectReference = new JsNameRef("Object");
043            DEFINE_PROPERTY.setQualifier(globalObjectReference);
044            CREATE_OBJECT.setQualifier(globalObjectReference);
045        }
046    
047        private JsAstUtils() {
048        }
049    
050        @NotNull
051        public static JsStatement convertToStatement(@NotNull JsNode jsNode) {
052            assert (jsNode instanceof JsExpression) || (jsNode instanceof JsStatement)
053                    : "Unexpected node of type: " + jsNode.getClass().toString();
054            if (jsNode instanceof JsExpression) {
055                return ((JsExpression) jsNode).makeStmt();
056            }
057            return (JsStatement) jsNode;
058        }
059    
060        @NotNull
061        public static JsBlock convertToBlock(@NotNull JsNode jsNode) {
062            if (jsNode instanceof JsBlock) {
063                return (JsBlock) jsNode;
064            }
065            JsBlock block = new JsBlock();
066            block.getStatements().add(convertToStatement(jsNode));
067            return block;
068        }
069    
070        @NotNull
071        private static JsStatement deBlockIfPossible(@NotNull JsStatement statement) {
072            if (statement instanceof JsBlock && ((JsBlock)statement).getStatements().size() == 1) {
073                return ((JsBlock)statement).getStatements().get(0);
074            }
075            else {
076                return statement;
077            }
078        }
079    
080        @NotNull
081        public static JsIf newJsIf(
082                @NotNull JsExpression ifExpression,
083                @NotNull JsStatement thenStatement,
084                @Nullable JsStatement elseStatement
085        ) {
086            elseStatement = elseStatement != null ? deBlockIfPossible(elseStatement) : null;
087            return new JsIf(ifExpression, deBlockIfPossible(thenStatement), elseStatement);
088        }
089    
090        @NotNull
091        public static JsIf newJsIf(@NotNull JsExpression ifExpression, @NotNull JsStatement thenStatement) {
092            return newJsIf(ifExpression, thenStatement, null);
093        }
094    
095        @Nullable
096        public static JsExpression extractExpressionFromStatement(@Nullable JsStatement statement) {
097            return statement instanceof JsExpressionStatement ? ((JsExpressionStatement) statement).getExpression() : null;
098        }
099    
100        @NotNull
101        public static JsStatement mergeStatementInBlockIfNeeded(@NotNull JsStatement statement, @NotNull JsBlock block) {
102            if (block.isEmpty()) {
103                return statement;
104            } else {
105                if (isEmptyStatement(statement)) {
106                    return deBlockIfPossible(block);
107                }
108                block.getStatements().add(statement);
109                return block;
110            }
111        }
112    
113        public static boolean isEmptyStatement(@NotNull JsStatement statement) {
114            return statement instanceof JsEmpty;
115        }
116    
117        public static boolean isEmptyExpression(@NotNull JsExpression expression) {
118            return expression instanceof JsEmptyExpression;
119        }
120    
121        @NotNull
122        public static JsInvocation invokeKotlinFunction(@NotNull String name, @NotNull JsExpression... argument) {
123            return new JsInvocation(new JsNameRef(name, Namer.KOTLIN_OBJECT_REF), argument);
124        }
125    
126        @NotNull
127        public static JsInvocation invokeMethod(@NotNull JsExpression thisObject, @NotNull String name, @NotNull JsExpression... arguments) {
128            return new JsInvocation(new JsNameRef(name, thisObject), arguments);
129        }
130    
131        @NotNull
132        public static JsExpression toInt32(@NotNull JsExpression expression) {
133            return new JsBinaryOperation(JsBinaryOperator.BIT_OR, expression, JsNumberLiteral.ZERO);
134        }
135    
136        @NotNull
137        public static JsExpression charToInt(@NotNull JsExpression expression) {
138            return invokeMethod(expression, "charCodeAt", JsNumberLiteral.ZERO);
139        }
140    
141        @NotNull
142        public static JsExpression toShort(@NotNull JsExpression expression) {
143            return invokeKotlinFunction(OperatorConventions.SHORT.getIdentifier(), expression);
144        }
145    
146        @NotNull
147        public static JsExpression toByte(@NotNull JsExpression expression) {
148            return invokeKotlinFunction(OperatorConventions.BYTE.getIdentifier(), expression);
149        }
150    
151        @NotNull
152        public static JsExpression toLong(@NotNull JsExpression expression) {
153            return invokeKotlinFunction(OperatorConventions.LONG.getIdentifier(), expression);
154        }
155    
156        @NotNull
157        public static JsExpression toChar(@NotNull JsExpression expression) {
158            return invokeKotlinFunction(OperatorConventions.CHAR.getIdentifier(), expression);
159        }
160    
161        @NotNull
162        public static JsExpression compareTo(@NotNull JsExpression left, @NotNull JsExpression right) {
163            return invokeKotlinFunction(OperatorConventions.COMPARE_TO.getIdentifier(), left, right);
164        }
165    
166        @NotNull
167        public static JsExpression primitiveCompareTo(@NotNull JsExpression left, @NotNull JsExpression right) {
168            return invokeKotlinFunction(Namer.PRIMITIVE_COMPARE_TO, left, right);
169        }
170    
171        @NotNull
172        public static JsExpression isNumber(@NotNull JsExpression expression) {
173            return invokeKotlinFunction(Namer.IS_NUMBER, expression);
174        }
175    
176        @NotNull
177        public static JsExpression isChar(@NotNull JsExpression expression) {
178            return invokeKotlinFunction(Namer.IS_CHAR, expression);
179        }
180    
181        @NotNull
182        private static JsExpression rangeTo(@NotNull String rangeClassName, @NotNull JsExpression rangeStart, @NotNull JsExpression rangeEnd) {
183            JsNameRef expr = new JsNameRef(rangeClassName, Namer.KOTLIN_NAME);
184            JsNew numberRangeConstructorInvocation = new JsNew(expr);
185            setArguments(numberRangeConstructorInvocation, rangeStart, rangeEnd);
186            return numberRangeConstructorInvocation;
187        }
188    
189        @NotNull
190        public static JsExpression numberRangeTo(@NotNull JsExpression rangeStart, @NotNull JsExpression rangeEnd) {
191            return rangeTo(Namer.NUMBER_RANGE, rangeStart, rangeEnd);
192        }
193    
194        @NotNull
195        public static JsExpression charRangeTo(@NotNull JsExpression rangeStart, @NotNull JsExpression rangeEnd) {
196            return rangeTo(Namer.CHAR_RANGE, rangeStart, rangeEnd);
197        }
198    
199        @NotNull
200        public static final JsNameRef kotlinLongNameRef = new JsNameRef("Long", Namer.KOTLIN_OBJECT_REF);
201    
202        @NotNull
203        public static JsExpression isLong(@NotNull JsExpression expression) {
204            return instanceOf(expression, kotlinLongNameRef);
205        }
206    
207        public static JsExpression newLong(long value, @NotNull TranslationContext context) {
208            if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
209                int low = (int) value;
210                int high = (int) (value >> 32);
211                List<JsExpression> args = new SmartList<JsExpression>();
212                args.add(context.program().getNumberLiteral(low));
213                args.add(context.program().getNumberLiteral(high));
214                return new JsNew(kotlinLongNameRef, args);
215            }
216            else {
217                return longFromInt(context.program().getNumberLiteral((int) value));
218            }
219        }
220    
221        @NotNull
222        public static JsExpression longFromInt(@NotNull JsExpression expression) {
223            return invokeMethod(kotlinLongNameRef, Namer.LONG_FROM_INT, expression);
224        }
225    
226        @NotNull
227        public static JsExpression longFromNumber(@NotNull JsExpression expression) {
228            return invokeMethod(kotlinLongNameRef, Namer.LONG_FROM_NUMBER, expression);
229        }
230    
231        @NotNull
232        public static JsExpression equalsForObject(@NotNull JsExpression left, @NotNull JsExpression right) {
233            return invokeMethod(left, Namer.EQUALS_METHOD_NAME, right);
234        }
235    
236        @NotNull
237        public static JsExpression compareForObject(@NotNull JsExpression left, @NotNull JsExpression right) {
238            return invokeMethod(left, Namer.COMPARE_TO_METHOD_NAME, right);
239        }
240    
241        @NotNull
242        public static JsPrefixOperation negated(@NotNull JsExpression expression) {
243            return new JsPrefixOperation(JsUnaryOperator.NOT, expression);
244        }
245    
246        @NotNull
247        public static JsBinaryOperation and(@NotNull JsExpression op1, @NotNull JsExpression op2) {
248            return new JsBinaryOperation(JsBinaryOperator.AND, op1, op2);
249        }
250    
251        @NotNull
252        public static JsBinaryOperation or(@NotNull JsExpression op1, @NotNull JsExpression op2) {
253            return new JsBinaryOperation(JsBinaryOperator.OR, op1, op2);
254        }
255    
256        @NotNull
257        public static JsBinaryOperation instanceOf(@NotNull JsExpression op1, @NotNull JsExpression op2) {
258            return new JsBinaryOperation(JsBinaryOperator.INSTANCEOF, op1, op2);
259        }
260    
261        public static void setQualifier(@NotNull JsExpression selector, @Nullable JsExpression receiver) {
262            assert (selector instanceof JsInvocation || selector instanceof JsNameRef);
263            if (selector instanceof JsInvocation) {
264                setQualifier(((JsInvocation) selector).getQualifier(), receiver);
265                return;
266            }
267            setQualifierForNameRef((JsNameRef) selector, receiver);
268        }
269    
270        private static void setQualifierForNameRef(@NotNull JsNameRef selector, @Nullable JsExpression receiver) {
271            JsExpression qualifier = selector.getQualifier();
272            if (qualifier == null) {
273                selector.setQualifier(receiver);
274            }
275            else {
276                setQualifier(qualifier, receiver);
277            }
278        }
279    
280        @NotNull
281        public static JsBinaryOperation equality(@NotNull JsExpression arg1, @NotNull JsExpression arg2) {
282            return new JsBinaryOperation(JsBinaryOperator.REF_EQ, arg1, arg2);
283        }
284    
285        @NotNull
286        public static JsBinaryOperation inequality(@NotNull JsExpression arg1, @NotNull JsExpression arg2) {
287            return new JsBinaryOperation(JsBinaryOperator.REF_NEQ, arg1, arg2);
288        }
289    
290        @NotNull
291        public static JsBinaryOperation lessThanEq(@NotNull JsExpression arg1, @NotNull JsExpression arg2) {
292            return new JsBinaryOperation(JsBinaryOperator.LTE, arg1, arg2);
293        }
294    
295        @NotNull
296        public static JsBinaryOperation lessThan(@NotNull JsExpression arg1, @NotNull JsExpression arg2) {
297            return new JsBinaryOperation(JsBinaryOperator.LT, arg1, arg2);
298        }
299    
300        @NotNull
301        public static JsBinaryOperation greaterThan(@NotNull JsExpression arg1, @NotNull JsExpression arg2) {
302            return new JsBinaryOperation(JsBinaryOperator.GT, arg1, arg2);
303        }
304    
305        @NotNull
306        public static JsExpression assignment(@NotNull JsExpression left, @NotNull JsExpression right) {
307            return new JsBinaryOperation(JsBinaryOperator.ASG, left, right);
308        }
309    
310        @NotNull
311        public static JsBinaryOperation sum(@NotNull JsExpression left, @NotNull JsExpression right) {
312            return new JsBinaryOperation(JsBinaryOperator.ADD, left, right);
313        }
314    
315        @NotNull
316        public static JsBinaryOperation addAssign(@NotNull JsExpression left, @NotNull JsExpression right) {
317            return new JsBinaryOperation(JsBinaryOperator.ASG_ADD, left, right);
318        }
319    
320        @NotNull
321        public static JsBinaryOperation subtract(@NotNull JsExpression left, @NotNull JsExpression right) {
322            return new JsBinaryOperation(JsBinaryOperator.SUB, left, right);
323        }
324    
325        @NotNull
326        public static JsBinaryOperation mul(@NotNull JsExpression left, @NotNull JsExpression right) {
327            return new JsBinaryOperation(JsBinaryOperator.MUL, left, right);
328        }
329    
330        @NotNull
331        public static JsBinaryOperation div(@NotNull JsExpression left, @NotNull JsExpression right) {
332            return new JsBinaryOperation(JsBinaryOperator.DIV, left, right);
333        }
334    
335        @NotNull
336        public static JsBinaryOperation mod(@NotNull JsExpression left, @NotNull JsExpression right) {
337            return new JsBinaryOperation(JsBinaryOperator.MOD, left, right);
338        }
339    
340        @NotNull
341        public static JsPrefixOperation not(@NotNull JsExpression expression) {
342            return new JsPrefixOperation(JsUnaryOperator.NOT, expression);
343        }
344    
345        @NotNull
346        public static JsBinaryOperation typeof(@NotNull JsExpression expression, @NotNull JsStringLiteral string) {
347            return equality(new JsPrefixOperation(JsUnaryOperator.TYPEOF, expression), string);
348        }
349    
350        @NotNull
351        public static JsVars newVar(@NotNull JsName name, @Nullable JsExpression expr) {
352            return new JsVars(new JsVars.JsVar(name, expr));
353        }
354    
355        public static void setArguments(@NotNull HasArguments invocation, @NotNull List<JsExpression> newArgs) {
356            List<JsExpression> arguments = invocation.getArguments();
357            assert arguments.isEmpty() : "Arguments already set.";
358            arguments.addAll(newArgs);
359        }
360    
361        public static void setArguments(@NotNull HasArguments invocation, JsExpression... arguments) {
362            setArguments(invocation, Arrays.asList(arguments));
363        }
364    
365        public static void setParameters(@NotNull JsFunction function, @NotNull List<JsParameter> newParams) {
366            List<JsParameter> parameters = function.getParameters();
367            assert parameters.isEmpty() : "Arguments already set.";
368            parameters.addAll(newParams);
369        }
370    
371        @NotNull
372        public static JsExpression newSequence(@NotNull List<JsExpression> expressions) {
373            assert !expressions.isEmpty();
374            if (expressions.size() == 1) {
375                return expressions.get(0);
376            }
377            JsExpression result = expressions.get(expressions.size() - 1);
378            for (int i = expressions.size() - 2; i >= 0; i--) {
379                result = new JsBinaryOperation(JsBinaryOperator.COMMA, expressions.get(i), result);
380            }
381            return result;
382        }
383    
384        @NotNull
385        public static JsFunction createFunctionWithEmptyBody(@NotNull JsScope parent) {
386            return new JsFunction(parent, new JsBlock(), "<anonymous>");
387        }
388    
389        @NotNull
390        public static List<JsExpression> toStringLiteralList(@NotNull List<String> strings, @NotNull JsProgram program) {
391            if (strings.isEmpty()) {
392                return Collections.emptyList();
393            }
394    
395            List<JsExpression> result = new SmartList<JsExpression>();
396            for (String str : strings) {
397                result.add(program.getStringLiteral(str));
398            }
399            return result;
400        }
401    
402        @NotNull
403        public static JsInvocation defineProperty(
404                @NotNull String name,
405                @NotNull JsObjectLiteral value,
406                @NotNull TranslationContext context
407        ) {
408            return new JsInvocation(DEFINE_PROPERTY, JsLiteral.THIS, context.program().getStringLiteral(name), value);
409        }
410    
411        @NotNull
412        public static JsStatement defineSimpleProperty(@NotNull String name, @NotNull JsExpression value) {
413            return assignment(new JsNameRef(name, JsLiteral.THIS), value).makeStmt();
414        }
415    
416        @NotNull
417        public static JsObjectLiteral createDataDescriptor(@NotNull JsExpression value, boolean writable, boolean enumerable) {
418            JsObjectLiteral dataDescriptor = new JsObjectLiteral();
419            dataDescriptor.getPropertyInitializers().add(new JsPropertyInitializer(VALUE, value));
420            if (writable) {
421                dataDescriptor.getPropertyInitializers().add(WRITABLE);
422            }
423            if (enumerable) {
424                dataDescriptor.getPropertyInitializers().add(ENUMERABLE);
425            }
426            return dataDescriptor;
427        }
428    
429        @NotNull
430        public static JsFunction createPackage(@NotNull List<JsStatement> to, @NotNull JsObjectScope scope) {
431            JsFunction packageBlockFunction = createFunctionWithEmptyBody(scope);
432    
433            JsName kotlinObjectAsParameter = packageBlockFunction.getScope().declareNameUnsafe(Namer.KOTLIN_NAME);
434            packageBlockFunction.getParameters().add(new JsParameter(kotlinObjectAsParameter));
435    
436            to.add(new JsInvocation(packageBlockFunction, Namer.KOTLIN_OBJECT_REF).makeStmt());
437    
438            return packageBlockFunction;
439        }
440    
441        @NotNull
442        public static JsObjectLiteral wrapValue(@NotNull JsExpression label, @NotNull JsExpression value) {
443            return new JsObjectLiteral(Collections.singletonList(new JsPropertyInitializer(label, value)));
444        }
445    
446        public static void replaceRootReference(@NotNull JsNameRef fullQualifier, @NotNull JsExpression newQualifier) {
447            JsNameRef qualifier = fullQualifier;
448            while (true) {
449                JsExpression parent = qualifier.getQualifier();
450                assert parent instanceof JsNameRef : "unexpected qualifier: " + parent + ", original: " + fullQualifier;
451                if (((JsNameRef) parent).getQualifier() == null) {
452                    assert Namer.getRootPackageName().equals(((JsNameRef) parent).getIdent());
453                    qualifier.setQualifier(newQualifier);
454                    return;
455                }
456                qualifier = (JsNameRef) parent;
457            }
458        }
459    }