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

The following examples show how to use com.intellij.lang.javascript.psi.JSCallExpression. 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: RequirejsPsiReferenceProvider.java    From WebStormRequireJsPlugin with MIT License 6 votes vote down vote up
public boolean isRequireCall(PsiElement element) {
    PsiElement prevEl = element.getParent();
    if (prevEl != null) {
        prevEl = prevEl.getParent();
    }

    if (prevEl instanceof JSCallExpression) {
        if (prevEl.getChildren().length > 1) {
            String requireFunctionName = Settings.REQUIREJS_REQUIRE_FUNCTION_NAME;
            if (prevEl.getChildren()[0].getText().toLowerCase().equals(requireFunctionName)) {
                return true;
            }
        }
    }

    return false;
}
 
Example #2
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 #3
Source File: TestDeclareResolver.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@Test
public void testWhenMixinArrayIsNull()
{
    Map<String, String> propertyMap = new HashMap<String, String>();
    propertyMap.put("property 1", "value");

    JSExpression[] arguments = new JSExpression[] {
            new MockJSLiteralExpression("test class"),
            new MockJSLiteralExpression("null"),
            new MockJSObjectLiteralExpression(propertyMap)
    };

    JSCallExpression callExpression = new MockJSCallExpression(arguments);
    Object[] statements = new Object[] {callExpression, null};

    DeclareStatementItems result = resolver.getDeclareStatementFromParsedStatement(statements);
    assertNotNull(result);
}
 
Example #4
Source File: TestDeclareResolver.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@Test
public void testWhenFirstArgumentIsAClassName()
{
    Map<String, String> propertyMap = new HashMap<String, String>();
    propertyMap.put("property 1", "value");

    JSExpression[] arguments = new JSExpression[] {
            new MockJSLiteralExpression("test class"),
            new MockJSArrayLiteralExpression(new String[] { "define 1", "define 2"}),
            new MockJSObjectLiteralExpression(propertyMap)
    };

    JSCallExpression callExpression = new MockJSCallExpression(arguments);
    Object[] statements = new Object[] {callExpression, null};

    DeclareStatementItems result = resolver.getDeclareStatementFromParsedStatement(statements);
    assertEquals(2, result.getExpressionsToMixin().length);
    assertEquals(1, result.getMethodsToConvert().length);
}
 
Example #5
Source File: MismatchedImportsInspection.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, boolean isOnTheFly)
{
    if(!isEnabled(file.getProject()))
    {
        return new ProblemDescriptor[0];
    }

    DefineResolver resolver = new DefineResolver();
    final List<ProblemDescriptor> descriptors = new ArrayList<ProblemDescriptor>();

    Set<JSCallExpression> expressions = resolver.getAllImportBlocks(file);
    for(JSCallExpression expression : expressions)
    {
        addProblemsForBlock(expression, descriptors, file, manager);
    }

    return descriptors.toArray(new ProblemDescriptor[0]);
}
 
Example #6
Source File: TestDeclareResolver.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@Test
public void classNameIsRetrieved()
{
    Map<String, String> propertyMap = new HashMap<String, String>();
    propertyMap.put("property 1", "value");

    JSExpression[] arguments = new JSExpression[] {
            new MockJSLiteralExpression("test class"),
            new MockJSArrayLiteralExpression(new String[] { "define 1", "define 2"}),
            new MockJSObjectLiteralExpression(propertyMap)
    };

    JSCallExpression callExpression = new MockJSCallExpression(arguments);
    Object[] statements = new Object[] {callExpression, null};

    DeclareStatementItems result = resolver.getDeclareStatementFromParsedStatement(statements);
    assertEquals("test class", result.getClassName().getText());
}
 
Example #7
Source File: TestDeclareResolver.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@Test
public void testWhenFirstArgumentIsNull()
{
    Map<String, String> propertyMap = new HashMap<String, String>();
    propertyMap.put("property 1", "value");

    JSExpression[] arguments = new JSExpression[] {
            BasicPsiElements.Null(),
            new MockJSObjectLiteralExpression(propertyMap)
    };

    JSCallExpression callExpression = new MockJSCallExpression(arguments);
    Object[] statements = new Object[] {callExpression, null};

    DeclareStatementItems result = resolver.getDeclareStatementFromParsedStatement(statements);
    assertEquals(0, result.getExpressionsToMixin().length);
    assertEquals(1, result.getMethodsToConvert().length);
}
 
Example #8
Source File: TestDeclareResolver.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@Test
public void testTheBasicHappyPath()
{
    Map<String, String> propertyMap = new HashMap<String, String>();
    propertyMap.put("property 1", "value");

    JSExpression[] arguments = new JSExpression[] {
            new MockJSArrayLiteralExpression(new String[] { "mixin1", "mixin2"}),
            new MockJSObjectLiteralExpression(propertyMap)
    };

    JSCallExpression callExpression = new MockJSCallExpression(arguments);
    Object[] statements = new Object[] {callExpression, null};

    DeclareStatementItems result = resolver.getDeclareStatementFromParsedStatement(statements);
    assertEquals(2, result.getExpressionsToMixin().length);
    assertEquals(1, result.getMethodsToConvert().length);
}
 
Example #9
Source File: AMDValidator.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
public static boolean elementIsAttachPoint(PsiElement element)
{
    /*
        It's hard to detect when an element is an attach point, because of the use of this inside other functions

        this.attachpoint
        that.attachpoint

        ideally we would parse the template file in the beginning and cache all of the attach points,
        maybe that's a todo item...
     */
    if(element == null || element.getParent() == null || !(element.getParent() instanceof JSReferenceExpression))
    {
        return false;
    }

    // we can exclude JSCallExpressions at least because you will never reference an attach point like
    // this.attachpoint(...)
    if(element.getParent().getParent() instanceof JSCallExpression)
    {
        return false;
    }

    return true;
}
 
Example #10
Source File: ModuleImporter.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
/**
 * takes an existing AMD import and updates it. Used when a module changes locations
 *
 * @param index the index of the import
 * @param currentModule the module that is being updated
 * @param quote the quote symbol to use for imports
 * @param path the new module's path
 * @param newModule the new module
 */
public void reimportModule(int index, PsiFile currentModule, char quote, String path, PsiFile newModule, String pluginPostfix, boolean updateReferences, PsiFile pluginResourceFile, JSCallExpression callExpression)
{
    DefineStatement defineStatement = new DefineResolver().getDefineStatementItemsFromArguments(callExpression.getArguments(), callExpression);

    String newModuleName = newModule.getName().substring(0, newModule.getName().indexOf('.'));
    LinkedHashMap<String, PsiFile> results = new ImportResolver().getChoicesFromFiles(new PsiFile[] { newModule }, libraries, newModuleName, currentModule, false, true);

    // check if the original used a relative syntax or absolute syntax, and prefer that
    String[] possibleImports = results.keySet().toArray(new String[0]);
    String chosenImport = chooseImportToReplaceAnImport(path, possibleImports);

    pluginPostfix = getUpdatedPluginResource(pluginResourceFile, pluginPostfix, currentModule);

    PsiElement defineLiteral = defineStatement.getArguments().getExpressions()[index];
    PsiElement newImport = JSUtil.createExpression(defineLiteral.getParent(), quote + chosenImport + pluginPostfix + quote);

    MatchResult match = new MatchResult(currentModule, index, path, quote, pluginPostfix, pluginResourceFile, callExpression);
    importUpdater.updateModuleReference(currentModule, match, defineStatement, newImport, updateReferences);
}
 
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: MatchResult.java    From needsmoredojo with Apache License 2.0 5 votes vote down vote up
public MatchResult(PsiFile module, int index, String path, char quote, String pluginResourceId, PsiFile pluginResourceFile, JSCallExpression callExpression) {
    this.index = index;
    this.path = path;
    this.quote = quote;
    this.module = module;
    this.pluginResourceId = pluginResourceId;
    this.pluginResourceFile = pluginResourceFile;
    this.callExpression = callExpression;
}
 
Example #13
Source File: DefineStatement.java    From needsmoredojo with Apache License 2.0 5 votes vote down vote up
public JSCallExpression getCallExpression() {
    if(callExpression == null)
    {
        throw new RuntimeException("callExpression was not set but is being accessed");
    }

    return callExpression;
}
 
Example #14
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 #15
Source File: JavascriptTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static boolean isTestSuiteCalled(PsiElement testSuite, PsiElement element) {
  if (!(element instanceof JSExpressionStatement)) {
    return false;
  }
  JSCallExpression call = PsiTreeUtil.getChildOfType(element, JSCallExpression.class);
  if (call == null) {
    return false;
  }
  PsiReference reference = call.getMethodExpression().getReference();
  if (reference == null) {
    return false;
  }
  return reference.resolve() == testSuite;
}
 
Example #16
Source File: UnusedImportBlockEntry.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
public JSCallExpression getBlock() {
    return block;
}
 
Example #17
Source File: MatchResult.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
public JSCallExpression getCallExpression() {
    return callExpression;
}
 
Example #18
Source File: UnusedImportBlockEntry.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
public UnusedImportBlockEntry(boolean isDefine, JSCallExpression block, List<PsiElement> defines, List<PsiElement> parameters) {
    this.block = block;
    this.defines = defines;
    this.parameters = parameters;
    this.isDefine = isDefine;
}
 
Example #19
Source File: DefineStatement.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
public DefineStatement(JSArrayLiteralExpression arguments, JSFunctionExpression function, String className, JSCallExpression originalParent) {
    this.arguments = arguments;
    this.function = function;
    this.className = className;
    this.callExpression = originalParent;
}
 
Example #20
Source File: DojoModuleFileResolver.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
public Set<String> getDojoModulesInHtmlFile(PsiFile file)
{
    final Set<String> modules = new HashSet<String>();

    file.acceptChildren(new JSRecursiveElementVisitor() {
        @Override
        public void visitJSCallExpression(JSCallExpression node) {
            if(!node.getText().startsWith("require"))
            {
                super.visitJSCallExpression(node);
                return;
            }

            if(node.getArguments().length > 0 && node.getArguments()[0] instanceof JSArrayLiteralExpression)
            {
                JSArrayLiteralExpression arguments = (JSArrayLiteralExpression) node.getArguments()[0];
                for(JSExpression literal : arguments.getExpressions())
                {
                    String literalText = literal.getText().replaceAll("'", "").replaceAll("\"", "");

                    if(!isDojoModule(literalText))
                    {
                        modules.add(literalText);
                    }
                }
            }

            super.visitJSCallExpression(node);
        }
    });

    file.acceptChildren(new XmlRecursiveElementVisitor() {
        @Override
        public void visitXmlTag(XmlTag tag) {
            super.visitXmlTag(tag);
        }

        @Override
        public void visitXmlAttribute(XmlAttribute attribute) {
            if(attribute.getName().equals("data-dojo-type"))
            {
                if(!isDojoModule(attribute.getValue()))
                {
                    modules.add(attribute.getValue());
                }
            }

            super.visitXmlAttribute(attribute);
        }
    });

    return modules;
}
 
Example #21
Source File: OrganizeAMDImportsAction.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e)
{
    final PsiFile psiFile = PsiFileUtil.getPsiFileInCurrentEditor(e.getProject());
    final AMDImportOrganizer organizer = new AMDImportOrganizer();

    CommandProcessor.getInstance().executeCommand(psiFile.getProject(), new Runnable() {
        @Override
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                @Override
                public void run() {
                    int totalSize = 0;

                    DefineResolver resolver = new DefineResolver();
                    Set<JSCallExpression> expressions = resolver.getAllImportBlocks(psiFile);
                    for(JSCallExpression expression : expressions)
                    {
                        List<PsiElement> blockDefines = new ArrayList<PsiElement>();
                        List<PsiElement> blockParameters = new ArrayList<PsiElement>();

                        try {
                            resolver.addDefinesAndParametersOfImportBlock(expression, blockDefines, blockParameters);
                        } catch (InvalidDefineException e1) {}

                        if(blockDefines.size() == 0 || blockParameters.size() == 0)
                        {
                            continue;
                        }

                        SortingResult result = organizer.sortDefinesAndParameters(blockDefines, blockParameters);
                        totalSize += blockDefines.size();

                        organizer.reorder(blockDefines.toArray(new PsiElement[]{}), result.getDefines(), true, result);
                        organizer.reorder(blockParameters.toArray(new PsiElement[]{}), result.getParameters(), false, result);
                    }

                    if(totalSize == 0)
                    {
                        Notifications.Bus.notify(new Notification("needsmoredojo", "Organize AMD Imports", "There were no AMD imports", NotificationType.WARNING));
                        return;
                    }
                    else
                    {
                        Notifications.Bus.notify(new Notification("needsmoredojo", "Organize AMD Imports", "Completed", NotificationType.INFORMATION));
                    }
                }
            });
        }
    },
    "Organize AMD Imports",
    "Organize AMD Imports");
}