com.intellij.lang.javascript.psi.JSLiteralExpression Java Examples

The following examples show how to use com.intellij.lang.javascript.psi.JSLiteralExpression. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static ImmutableList<JSLiteralExpression> getModuleDeclarations(
    ImmutableList<JSFile> jsFiles) {
  return findChildrenOfType(jsFiles, JSCallExpression.class).stream()
      .filter(
          call -> {
            JSExpression method = call.getMethodExpression();
            return method != null
                && (Objects.equals(method.getText(), "goog.provide")
                    || Objects.equals(method.getText(), "goog.module"));
          })
      .map(JSCallExpression::getArguments)
      .filter(a -> a.length == 1)
      .map(a -> a[0])
      .filter(JSLiteralExpression.class::isInstance)
      .map(JSLiteralExpression.class::cast)
      .filter(JSLiteralExpression::isQuotedLiteral)
      .collect(toImmutableList());
}
 
Example #2
Source File: ExtJsGoToDeclarationHandler.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
private void attachSnippets(@NotNull PsiElement sourceElement, @NotNull List<PsiElement> targets) {
    PsiElement parent = sourceElement.getParent();
    if(!(parent instanceof JSLiteralExpression)) {
        return;
    }

    Object value = ((JSLiteralExpression) parent).getValue();
    if(!(value instanceof String) || StringUtils.isBlank((String) value) || !((String) value).startsWith("{s")) {
        return;
    }

    String name = ExtJsUtil.getAttributeTagValueFromSmartyString("s", "name", (String) value);
    if(name == null) {
        return;
    }

    String namespace = ExtJsUtil.getNamespaceFromStringLiteral((JSLiteralExpression) parent);
    if(namespace == null) {
        return;
    }

    targets.addAll(SnippetUtil.getSnippetNameTargets(parent.getProject(), namespace, name));
}
 
Example #3
Source File: JavascriptTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private static PsiElement findTestSuiteReference(PsiElement element) {
  if (element instanceof JSVarStatement) {
    // variable assignment might be
    // testSuite = goog.require('goog.testing.testSuite')
    JSVariable variable = PsiTreeUtil.getChildOfType(element, JSVariable.class);
    if (variable != null && isImportingTestSuite(variable)) {
      return variable;
    }
  } else if (element instanceof JSExpressionStatement) {
    // expression statement might be
    // goog.require('goog.testing.testSuite')
    if (isImportingTestSuite(element)) {
      JSLiteralExpression literal =
          PsiTreeUtil.findChildOfType(element, JSLiteralExpression.class);
      // this should be 'goog.testing.testSuite'
      if (literal == null) {
        return null;
      }
      for (PsiReference reference : literal.getReferences()) {
        if (reference instanceof JSGclModuleReference) {
          // this should be testSuite, and should resolve to the function
          return reference.resolve();
        }
      }
    }
  }
  return null;
}
 
Example #4
Source File: NearestAMDImportLocator.java    From needsmoredojo with Apache License 2.0 5 votes vote down vote up
protected @Nullable JSElement getDefineLiteral(PsiElement elementAtCaretPosition, DefineStatement defineStatement)
{
    iterations += 1;

    if(elementAtCaretPosition == null || iterations > 10)
    {
        return null;
    }

    if(elementAtCaretPosition.getParent() instanceof JSLiteralExpression)
    {
        return (JSElement) elementAtCaretPosition.getParent();
    }

    if(elementAtCaretPosition.getPrevSibling() instanceof JSLiteralExpression)
    {
        return (JSElement) elementAtCaretPosition.getPrevSibling();
    }

    // I know I know ... but this accounts for the case where the cursor is right after the comma so it's a special case
    if(elementAtCaretPosition.getPrevSibling() != null && elementAtCaretPosition.getPrevSibling().getPrevSibling() instanceof JSLiteralExpression)
    {
        return (JSElement) elementAtCaretPosition.getPrevSibling().getPrevSibling();
    }

    // if none of the above cases work, we assume this is a parameter and find its corresponding literal
    JSElement parameter = getParameter(elementAtCaretPosition, defineStatement);
    if(parameter == null)
    {
        return null;
    }

    int parameterIndex = getIndexOfParameter(defineStatement, parameter);
    if(parameterIndex >= defineStatement.getArguments().getExpressions().length)
    {
        return null;
    }

    return defineStatement.getArguments().getExpressions()[parameterIndex];
}
 
Example #5
Source File: ExtJsUtilTest.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
/**
 * @see ExtJsUtil#getNamespaceFromStringLiteral
 */
public void testGetNamespaceFromStringLiteral() {
    myFixture.configureByText(
        JavaScriptFileType.INSTANCE,
        "var foo = { foo: \"{s name=backend/inde<caret>x/view/widgets namespace='foobar'}\"}"
    );

    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset()).getParent();

    assertEquals("foobar", ExtJsUtil.getNamespaceFromStringLiteral((JSLiteralExpression) psiElement));
}
 
Example #6
Source File: ExtJsUtil.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
/**
 * {header: '{s name=swag-last-registrations/date}{/s}'}
 */
@Nullable
public static String getNamespaceFromStringLiteral(@NotNull JSLiteralExpression element) {
    Object contents = element.getValue();
    if(!(contents instanceof String) || StringUtils.isBlank((String) contents)) {
        return null;
    }

    String namespace = getAttributeTagValueFromSmartyString("s", "namespace", (String) contents);
    if(namespace != null) {
        return namespace;
    }

    return getSnippetNamespaceFromFile(element.getContainingFile());
}
 
Example #7
Source File: ShopwareJavaScriptCompletion.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
/**
 * String must start with "{s"
 */
private PsiElementPattern.Capture<PsiElement> getSnippetPattern() {
    return PlatformPatterns.psiElement()
        .withParent(PlatformPatterns.psiElement(JSLiteralExpression.class)
            .with(new PatternCondition<JSLiteralExpression>("Snippet Start") {
                @Override
                public boolean accepts(@NotNull JSLiteralExpression jsLiteralExpression, ProcessingContext processingContext) {
                    Object value = jsLiteralExpression.getValue();
                    return value instanceof String && (((String) value).startsWith("{s"));
                }
            }));
}
 
Example #8
Source File: BlazeTypescriptGotoDeclarationHandlerTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Test
public void testGotoImportStatements() {
  configureUserTs(
      "import E<caret>SFiveClass from 'goog:foo.bar.ESFiveClass';",
      "import E<caret>SSixClass from 'goog:foo.bar.ESSixClass';",
      "import C<caret>losureClass from 'goog:foo.bar.ClosureClass';");

  PsiElement esFiveClass = getElementUnderCaret(0);
  assertThat(esFiveClass).isInstanceOf(JSLiteralExpression.class);
  assertThat(((JSLiteralExpression) esFiveClass).getStringValue())
      .isEqualTo("foo.bar.ESFiveClass");
  assertThat(esFiveClass.getParent().getParent().getText())
      .isEqualTo("goog.provide('foo.bar.ESFiveClass')");

  PsiElement esSixClass = getElementUnderCaret(1);
  assertThat(esSixClass).isInstanceOf(JSLiteralExpression.class);
  assertThat(((JSLiteralExpression) esSixClass).getStringValue()).isEqualTo("foo.bar.ESSixClass");
  assertThat(esSixClass.getParent().getParent().getText())
      .isEqualTo("goog.provide('foo.bar.ESSixClass')");

  PsiElement closureClass = getElementUnderCaret(2);
  assertThat(closureClass).isInstanceOf(JSLiteralExpression.class);
  assertThat(((JSLiteralExpression) closureClass).getStringValue())
      .isEqualTo("foo.bar.ClosureClass");
  assertThat(closureClass.getParent().getParent().getText())
      .isEqualTo("goog.module('foo.bar.ClosureClass')");
}
 
Example #9
Source File: BlazeJavaScriptTestRunLineMarkerContributorTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
private Subject assertThatJasmineElement(LeafPsiElement element) {
  Info info = markerContributor.getInfo(element);
  assertThat(info).isNotNull();
  return new Subject() {
    @Override
    public Subject isTestSuite() {
      assertThat(element.getText()).isEqualTo("describe");
      return this;
    }

    @Override
    public Subject isTestCase() {
      assertThat(element.getText()).isEqualTo("it");
      return this;
    }

    @Override
    public Subject hasName(String name) {
      PsiElement grandParent = element.getParent().getParent();
      assertThat(grandParent).isInstanceOf(JSCallExpression.class);
      JSCallExpression call = (JSCallExpression) grandParent;
      assertThat(call.getArguments()[0]).isInstanceOf(JSLiteralExpression.class);
      JSLiteralExpression literal = (JSLiteralExpression) call.getArguments()[0];
      assertThat(literal.getStringValue()).isEqualTo(name);
      return this;
    }

    @Override
    public Subject hasIcon(Icon icon) {
      assertThat(info.icon).isEqualTo(icon);
      return this;
    }
  };
}
 
Example #10
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Usually, we can just compare {@link JSQualifiedNamedElement#getQualifiedName()}, but in
 * goog.module()s, the name "exports" replaces the actual exported symbol. E.g.,
 *
 * <pre>
 * goog.module('Foo');
 * exports.bar = goog.defineClass(null, { foo: function() {}});
 * </pre>
 *
 * creates a function with the qualified name of Foo.bar.foo.
 */
@Nullable
private static String getJsQualifiedName(JSQualifiedNamedElement jsElement) {
  String exportedName =
      Optional.ofNullable(
              PsiTreeUtil.getTopmostParentOfType(jsElement, JSAssignmentExpression.class))
          .map(JSAssignmentExpression::getDefinitionExpression)
          .map(JSQualifiedNamedElement::getQualifiedName)
          .filter(name -> name.equals("exports") || name.startsWith("exports."))
          .orElse(null);
  String qualifiedName = jsElement.getQualifiedName();
  if (qualifiedName == null || exportedName == null) {
    return qualifiedName;
  }
  String moduleName =
      Stream.of(jsElement)
          .map(PsiElement::getContainingFile)
          .map(JSFile.class::cast)
          .map(ImmutableList::of)
          // should be only one goog.module()
          .map(BlazeTypescriptGotoDeclarationHandler::getModuleDeclarations)
          .flatMap(Collection::stream)
          .findFirst()
          .map(JSLiteralExpression::getStringValue)
          .orElse(null);
  // if exports is already part of the element's qualified name, then the exported name is already
  // included, otherwise we have to include the exported name
  return qualifiedName.startsWith("exports")
      ? moduleName + qualifiedName.substring("exports".length())
      : moduleName + exportedName.substring("exports".length()) + '.' + qualifiedName;
}
 
Example #11
Source File: JavascriptTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static boolean isImportingTestSuite(PsiElement element) {
  JSCallExpression call = PsiTreeUtil.getChildOfType(element, JSCallExpression.class);
  if (call == null || !Objects.equals(call.getMethodExpression().getText(), "goog.require")) {
    return false;
  }
  JSExpression[] arguments = call.getArguments();
  if (arguments.length != 1) {
    return false;
  }
  if (!(arguments[0] instanceof JSLiteralExpression)) {
    return false;
  }
  JSLiteralExpression literal = (JSLiteralExpression) arguments[0];
  return Objects.equals(literal.getStringValue(), "goog.testing.testSuite");
}
 
Example #12
Source File: MissingModuleJSInspection.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildRealVisitor(@NotNull ProblemsHolder problemsHolder, @NotNull LocalInspectionToolSession localInspectionToolSession) {
    return new JSElementVisitor() {
        @Override
        public void visitJSLiteralExpression(JSLiteralExpression node) {
            PsiReference[] references = node.getReferences();
            for (PsiReference reference : references) {
                if (!(reference instanceof JSResolvableModuleReference)) {
                    continue;
                }

                JSResolvableModuleReference moduleReference = (JSResolvableModuleReference) reference;

                String canonicalText = moduleReference.getCanonicalText();
                if (!canonicalText.startsWith(JavaScriptUtil.MODULE_PREFIX)) {
                    super.visitJSLiteralExpression(node);

                    return;
                }

                if (JavaScriptUtil.getModuleMap(node.getProject()).containsKey(canonicalText)) {
                    super.visitJSLiteralExpression(node);

                    return;
                }

                problemsHolder.registerProblem(node, String.format("Unknown JavaScript module \"%s\"", canonicalText));

                return;
            }

            super.visitJSLiteralExpression(node);
        }
    };
}
 
Example #13
Source File: BlazeTypescriptGotoDeclarationHandlerTest.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Test
public void testGotoClasses() {
  configureUserTs(
      "import ESFiveClass from 'goog:foo.bar.ESFiveClass';",
      "import ESSixClass from 'goog:foo.bar.ESSixClass';",
      "import ClosureClass from 'goog:foo.bar.ClosureClass';",
      "var a: E<caret>SFiveClass;",
      "var b: ESFiveClass.N<caret>estedClass;",
      "var c: E<caret>SSixClass;",
      "var d: C<caret>losureClass;");

  PsiElement esFiveClass = getElementUnderCaret(0);
  assertThat(esFiveClass).isInstanceOf(JSLiteralExpression.class);
  assertThat(((JSLiteralExpression) esFiveClass).getStringValue())
      .isEqualTo("foo.bar.ESFiveClass");
  assertThat(esFiveClass.getParent().getParent().getText())
      .isEqualTo("goog.provide('foo.bar.ESFiveClass')");

  PsiElement nestedClass = getElementUnderCaret(1);
  assertThat(nestedClass).isInstanceOf(ES6ClassExpression.class);
  assertThat(nestedClass.getParent().getText())
      .isEqualTo(
          String.join(
              "\n",
              "foo.bar.ESFiveClass.NestedClass = class {",
              "  /** @public */",
              "  static foo() {}",
              "  /** @public */",
              "  foo() {}",
              "}"));

  PsiElement esSixClass = getElementUnderCaret(2);
  assertThat(esSixClass).isInstanceOf(JSLiteralExpression.class);
  assertThat(((JSLiteralExpression) esSixClass).getStringValue()).isEqualTo("foo.bar.ESSixClass");
  assertThat(esSixClass.getParent().getParent().getText())
      .isEqualTo("goog.provide('foo.bar.ESSixClass')");

  PsiElement closureClass = getElementUnderCaret(3);
  assertThat(closureClass).isInstanceOf(JSLiteralExpression.class);
  assertThat(((JSLiteralExpression) closureClass).getStringValue())
      .isEqualTo("foo.bar.ClosureClass");
  assertThat(closureClass.getParent().getParent().getText())
      .isEqualTo("goog.module('foo.bar.ClosureClass')");
}
 
Example #14
Source File: TemplatedWidgetUtil.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
@Nullable
public PsiFile findTemplateFromDeclare(@Nullable DeclareStatementItems statement)
{
    if(statement == null)
    {
        return null;
    }

    for(JSProperty property : statement.getMethodsToConvert())
    {
        // just continue if this property is invalid for some reason
        if(property == null || property.getName() == null || property.getValue() == null)
        {
            continue;
        }

        /**
         * have to account for these scenarios
         * templateString: <reference to an imported template>
         * templateString: 'inline template'
         * templateString: 'inline template ' +
         *                  ' spanning multiple lines '
         */
        if(property.getName().equals("templateString"))
        {
            String template = property.getValue().getText();

            if(property.getValue() instanceof JSLiteralExpression || property.getValue() instanceof JSBinaryExpression)
            {
                return property.getContainingFile();
            }
            else
            {
                // find the parameter and define that matches the template parameter
                PsiElement relevantDefine = AMDPsiUtil.getDefineForVariable(file, template);

                if(relevantDefine == null)
                {
                    // we couldn't find the module that templateString reference for whatever reason
                    // (it could be an invalid reference to a module)
                    return null;
                }

                String templatePath = relevantDefine.getText().substring(relevantDefine.getText().lastIndexOf('!') + 1);
                // now open the file and find the reference in it
                VirtualFile htmlFile = SourcesLocator.getAMDImportFile(relevantDefine.getProject(), templatePath, relevantDefine.getContainingFile().getContainingDirectory());

                // if we can't resolve it return null for now TODO
                if(htmlFile == null)
                {
                    return null;
                }

                PsiFile templateFile = PsiManager.getInstance(file.getProject()).findFile(htmlFile);
                return templateFile;
            }
        }
    }

    return null;
}
 
Example #15
Source File: DeclareStatementItems.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
public DeclareStatementItems(JSLiteralExpression className, JSExpression[] expressionsToMixin, JSProperty[] methodsToConvert, JSElement declareContainingStatement) {
    this(expressionsToMixin, methodsToConvert, declareContainingStatement);

    this.className = className;
}
 
Example #16
Source File: DeclareStatementItems.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
@Nullable
public JSLiteralExpression getClassName() {
    return className;
}
 
Example #17
Source File: BasicPsiElements.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
public static JSLiteralExpression Null()
{
    return new MockJSLiteralExpression("null");
}
 
Example #18
Source File: RequirejsPsiReferenceContributor.java    From WebStormRequireJsPlugin with MIT License 4 votes vote down vote up
@Override
public void registerReferenceProviders(PsiReferenceRegistrar psiReferenceRegistrar) {
    RequirejsPsiReferenceProvider provider = new RequirejsPsiReferenceProvider();

    psiReferenceRegistrar.registerReferenceProvider(StandardPatterns.instanceOf(JSLiteralExpression.class), provider);
}