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

The following examples show how to use com.intellij.lang.javascript.psi.JSFunction. 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: BlazeJavascriptTestLocator.java    From intellij with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private static List<Location> findClosureTestCase(
    Project project, File file, @Nullable String testName) {
  VirtualFile virtualFile = VfsUtils.resolveVirtualFile(file, /* refreshIfNeeded= */ false);
  if (virtualFile == null) {
    return ImmutableList.of();
  }
  PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
  if (!(psiFile instanceof JSFile)) {
    return ImmutableList.of();
  }
  if (testName != null) {
    for (JSFunction function : PsiTreeUtil.findChildrenOfType(psiFile, JSFunction.class)) {
      if (Objects.equals(function.getName(), testName)) {
        return ImmutableList.of(new PsiLocation<>(function));
      }
    }
  }
  return ImmutableList.of(new PsiLocation<>(psiFile));
}
 
Example #2
Source File: BlazeJavaScriptTestRunLineMarkerContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static Icon getClosureTestIcon(
    Project project, Collection<Label> labels, JSFile file, JSFunction function) {
  WorkspaceRoot root = WorkspaceRoot.fromProject(project);
  WorkspacePath path = root.workspacePathFor(file.getVirtualFile());
  String relativePath = root.directory().getName() + '/' + path.relativePath();
  if (relativePath.endsWith(".js")) {
    relativePath = relativePath.substring(0, relativePath.lastIndexOf(".js"));
  }
  String urlSuffix =
      relativePath
          + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
          + function.getName()
          + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
          + relativePath; // redundant class name
  return labels.stream()
      .map(
          label ->
              SmRunnerUtils.GENERIC_TEST_PROTOCOL
                  + URLUtil.SCHEME_SEPARATOR
                  + label
                  + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
                  + urlSuffix)
      .map(url -> getTestStateIcon(url, project, /* isClass = */ false))
      .max(Comparator.comparingInt(iconPriorities::get))
      .orElse(TestState.Run);
}
 
Example #3
Source File: UnityScriptEventFunctionLineMarkerProvider.java    From consulo-unity3d with Apache License 2.0 6 votes vote down vote up
private static boolean isEqualParameters(Map<String, String> funcParameters, JSFunction function)
{
	JSParameter[] parameters = function.getParameterList().getParameters();
	if(parameters.length == 0)
	{
		return true;
	}
	if(parameters.length != funcParameters.size())
	{
		return false;
	}

	/*int i = 0;
	for(DotNetTypeRef expectedTypeRef : funcParameters.values())
	{
		JSParameter parameter = parameters[i++];

		if(!CSharpTypeUtil.isTypeEqual(parameter.toTypeRef(true), expectedTypeRef, parameter))
		{
			return false;
		}
	}   */
	return true;
}
 
Example #4
Source File: JavascriptTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
/** jsunit_test can just be top level functions with a test prefix. */
private static boolean hasTopLevelTests(JSFile file) {
  return Arrays.stream(file.getChildren())
      .filter(JSFunction.class::isInstance)
      .map(JSFunction.class::cast)
      .map(JSFunction::getName)
      .filter(Objects::nonNull)
      .anyMatch(name -> name.startsWith("test"));
}
 
Example #5
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<PsiElement> resolveToJs(
    ExecutionRootPathResolver pathResolver,
    LocalFileSystem lfs,
    PsiManager psiManager,
    boolean isConstructor,
    PsiElement dtsElement) {
  dtsElement = PsiTreeUtil.getParentOfType(dtsElement, JSQualifiedNamedElement.class, false);
  if (dtsElement == null) {
    return ImmutableList.of();
  }
  if (!TypeScriptUtil.isDefinitionFile(dtsElement.getContainingFile())) {
    return ImmutableList.of();
  }
  String qualifiedName = getDtsQualifiedName((JSQualifiedNamedElement) dtsElement);
  if (qualifiedName == null) {
    return ImmutableList.of();
  }
  ImmutableList<JSFile> jsFiles = jsFilesFromDtsSymbol(pathResolver, lfs, psiManager, dtsElement);
  if (jsFiles.isEmpty()) {
    return ImmutableList.of();
  }
  if (dtsElement instanceof TypeScriptModule) {
    String moduleName = getModuleName(qualifiedName);
    return isConstructor
        ? findChildrenOfType(jsFiles, JSFunction.class).stream()
            .filter(e -> isConstructorWithName(e, moduleName))
            .collect(toImmutableList())
        : getModuleDeclarations(jsFiles).stream()
            .filter(a -> Objects.equals(a.getStringValue(), moduleName))
            .collect(toImmutableList());
  }
  return getResolveCandidates(dtsElement, jsFiles).stream()
      .filter(e -> Objects.equals(getJsQualifiedName(e), qualifiedName))
      .collect(toImmutableList());
}
 
Example #6
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<? extends JSQualifiedNamedElement> getResolveCandidates(
    PsiElement dtsElement, ImmutableList<JSFile> jsFiles) {
  if (dtsElement instanceof TypeScriptClass) {
    return Stream.concat(
            findChildrenOfType(jsFiles, JSClass.class).stream(),
            // Apparently you can declare a JS class with just a constructor function and
            // attach some properties to it.
            findChildrenOfType(jsFiles, JSFunction.class).stream())
        .collect(toImmutableList());
  } else if (dtsElement instanceof TypeScriptFunction) {
    TypeScriptFunction dtsFunction = (TypeScriptFunction) dtsElement;
    return findChildrenOfType(jsFiles, JSFunction.class).stream()
        .filter(f -> staticModifierEquals(f, dtsFunction))
        .collect(toImmutableList());
  } else if (dtsElement instanceof TypeScriptEnum) {
    return findChildrenOfType(jsFiles, JSObjectLiteralExpression.class).stream()
        .map(PsiElement::getParent)
        .filter(JSAssignmentExpression.class::isInstance)
        .map(PsiElement::getFirstChild)
        .filter(JSDefinitionExpression.class::isInstance)
        .map(JSDefinitionExpression.class::cast)
        .collect(toImmutableList());
  } else if (dtsElement instanceof TypeScriptEnumField) {
    return findChildrenOfType(jsFiles, JSProperty.class);
  }
  return ImmutableList.of();
}
 
Example #7
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static boolean isConstructorWithName(JSFunction jsFunction, String moduleName) {
  // Prototype-based and ES6 classes will have isConstructor() return true.
  // goog.defineClass() constructors aren't recognized by isConstructor(), so must check name.
  if (!jsFunction.isConstructor() && !Objects.equals(jsFunction.getName(), "constructor")) {
    return false;
  }
  // Prototype-based constructor will have same name as module.
  // ES6 and goog.defineClass() constructors will have their own name.
  String jsQualifiedName = getJsQualifiedName(jsFunction);
  return Objects.equals(jsQualifiedName, moduleName)
      || Objects.equals(jsQualifiedName, moduleName + ".constructor");
}
 
Example #8
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static boolean staticModifierEquals(
    JSFunction jsFunction, TypeScriptFunction dtsFunction) {
  boolean dtsIsStatic =
      Optional.of(dtsFunction)
          .map(JSAttributeListOwner::getAttributeList)
          .filter(a -> a.hasModifier(ModifierType.STATIC))
          .isPresent();
  return dtsIsStatic == jsIsStatic(jsFunction);
}
 
Example #9
Source File: UnityScriptEventFunctionLineMarkerProvider.java    From consulo-unity3d with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@Nonnull PsiElement element)
{
	if(element.getNode().getElementType() == JSTokenTypes.IDENTIFIER && element.getParent() instanceof JSReferenceExpression && element.getParent().getParent() instanceof JSFunction)
	{
		UnityFunctionManager functionManager = UnityFunctionManager.getInstance();
		Map<String, UnityFunctionManager.FunctionInfo> map = functionManager.getFunctionsByType().get(Unity3dTypes.UnityEngine.MonoBehaviour);
		if(map == null)
		{
			return null;
		}
		UnityFunctionManager.FunctionInfo functionInfo = map.get(element.getText());
		if(functionInfo == null)
		{
			return null;
		}
		Unity3dModuleExtension extension = ModuleUtilCore.getExtension(element, Unity3dModuleExtension.class);
		if(extension == null)
		{
			return null;
		}
		JSFunction jsFunction = (JSFunction) element.getParent().getParent();
		if(jsFunction.getParent() instanceof JSFile)
		{
			if(!isEqualParameters(functionInfo.getParameters(), jsFunction))
			{
				return null;
			}

			return new LineMarkerInfo<>(element, element.getTextRange(), Unity3dIcons.EventMethod, Pass.LINE_MARKERS, new ConstantFunction<>(functionInfo.getDescription()), null,
					GutterIconRenderer.Alignment.LEFT);
		}
	}
	return null;
}
 
Example #10
Source File: BlazeJavaScriptTestRunLineMarkerContributor.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public Info getInfo(PsiElement element) {
  if (!enableJavascriptRunLineMarkers.getValue()) {
    return null;
  }
  JSFile file =
      Optional.of(element)
          .filter(PsiElement::isValid)
          .filter(LeafPsiElement.class::isInstance)
          .map(LeafPsiElement.class::cast)
          .filter(e -> e.getElementType().equals(JSTokenTypes.IDENTIFIER))
          .map(PsiElement::getContainingFile)
          .filter(JSFile.class::isInstance)
          .map(JSFile.class::cast)
          .orElse(null);
  if (file == null) {
    return null;
  }
  Collection<Label> labels = getWrapperTests(file);
  if (labels.isEmpty()) {
    return null;
  }
  JsTestElementPath jasmineTestElement =
      CachedValuesManager.getCachedValue(
              file,
              () ->
                  Result.create(
                      JasmineFileStructureBuilder.getInstance().buildTestFileStructure(file),
                      file))
          .findTestElementPath(element);
  if (jasmineTestElement != null) {
    return new Info(
        getJasmineTestIcon(file.getProject(), labels, jasmineTestElement),
        null,
        ExecutorAction.getActions());
  }
  PsiElement parent = element.getParent();
  if (parent instanceof JSFunction && element.getText().startsWith("test")) {
    return new Info(
        getClosureTestIcon(file.getProject(), labels, file, (JSFunction) parent),
        null,
        ExecutorAction.getActions());
  }
  return null;
}
 
Example #11
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 4 votes vote down vote up
private static boolean jsIsStatic(JSFunction jsFunction) {
  if (jsFunction.getParent() instanceof JSAssignmentExpression) {
    // pre-ES6 prototype assignment based classes
    // Class.foo = function() {};           <- static
    // Class.prototype.bar = function() {}; <- non-static
    return Optional.of(jsFunction)
        .map(PsiElement::getParent)
        .map(PsiElement::getFirstChild)
        .filter(JSDefinitionExpression.class::isInstance)
        .filter(d -> !d.getText().contains(".prototype."))
        .isPresent();
  } else if (jsFunction.getParent() instanceof JSProperty) {
    // goog.defineClass(..., {
    //   foo: function() {}, <--- JSFunction (non-static)
    //   v----------------------- JSProperty
    //   statics: { <------------ JSObjectLiteralExpression
    //     v--------------------- JSProperty
    //     bar: function() {}, <- JSFunction (static)
    //   },
    // })
    return Optional.of(jsFunction)
        .map(PsiElement::getParent)
        .map(PsiElement::getParent)
        .filter(JSObjectLiteralExpression.class::isInstance)
        .map(PsiElement::getParent)
        .filter(JSProperty.class::isInstance)
        .map(JSProperty.class::cast)
        .filter(p -> Objects.equals(p.getName(), "statics"))
        .isPresent();
  } else if (jsFunction.getParent() instanceof JSClass) {
    // ES6 classes
    return Optional.of(jsFunction)
        .map(JSAttributeListOwner::getAttributeList)
        .filter(a -> a.hasModifier(ModifierType.STATIC))
        .isPresent();
  }
  // Shouldn't happen unless it's a standalone function.
  // Probably makes sense to call it static.
  // It wouldn't match any class-qualified TS function by name anyway.
  return true;
}
 
Example #12
Source File: BlazeTypescriptGotoDeclarationHandlerTest.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Test
public void testGotoConstructors() {
  configureUserTs(
      "import ESFiveClass from 'goog:foo.bar.ESFiveClass';",
      "import ESSixClass from 'goog:foo.bar.ESSixClass';",
      "import ClosureClass from 'goog:foo.bar.ClosureClass';",
      "new E<caret>SFiveClass();",
      "new ESFiveClass.N<caret>estedClass();",
      "new E<caret>SSixClass();",
      "new C<caret>losureClass();");

  PsiElement esFiveClassConstructor = getElementUnderCaret(0);
  assertThat(esFiveClassConstructor).isInstanceOf(JSFunctionExpression.class);
  assertThat(esFiveClassConstructor.getParent().getText())
      .isEqualTo("foo.bar.ESFiveClass = function() {}");

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

  PsiElement esSixClassConstructor = getElementUnderCaret(2);
  assertThat(esSixClassConstructor).isInstanceOf(JSFunction.class);
  assertThat(esSixClassConstructor.getText()).isEqualTo("constructor() {}");
  assertThat(esSixClassConstructor.getParent().getParent().getText())
      .isEqualTo(
          String.join(
              "\n",
              "foo.bar.ESSixClass = class {",
              "  constructor() {}",
              "  /** @public */",
              "  static foo() {}",
              "  /** @public */",
              "  foo() {}",
              "}"));

  PsiElement closureClassConstructor = getElementUnderCaret(3);
  assertThat(closureClassConstructor).isInstanceOf(JSFunctionExpression.class);
  assertThat(closureClassConstructor.getParent().getText())
      .isEqualTo("constructor: function() {}");
}
 
Example #13
Source File: BlazeTypescriptGotoDeclarationHandlerTest.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Test
public void testGotoStaticMethods() {
  configureUserTs(
      "import ESFiveClass from 'goog:foo.bar.ESFiveClass';",
      "import ESSixClass from 'goog:foo.bar.ESSixClass';",
      "import ClosureClass from 'goog:foo.bar.ClosureClass';",
      "ESFiveClass.f<caret>oo();",
      "ESFiveClass.NestedClass.f<caret>oo();",
      "ESSixClass.f<caret>oo();",
      "ESSixClass.b<caret>ar();",
      "ClosureClass.f<caret>oo();",
      "ClosureClass.b<caret>ar();");

  // Broken due to upstream bug: https://youtrack.jetbrains.com/issue/WEB-41611
  //
  // PsiElement esFiveClassFoo = getElementUnderCaret(0);
  // assertThat(esFiveClassFoo).isInstanceOf(JSFunctionExpression.class);
  // assertThat(esFiveClassFoo.getParent().getText())
  //     .isEqualTo("foo.bar.ESFiveClass.foo = function() {}");
  //
  // PsiElement nestedClassFoo = getElementUnderCaret(1);
  // assertThat(nestedClassFoo).isInstanceOf(JSFunction.class);
  // assertThat(nestedClassFoo.getText())
  //     .isEqualTo(
  //         String.join(
  //             "\n", //
  //             "/** @public */",
  //             "  static foo() {}"));
  // assertThat(nestedClassFoo.getParent().getParent().getText())
  //     .isEqualTo(
  //         String.join(
  //             "\n",
  //             "foo.bar.ESFiveClass.NestedClass = class {",
  //             "  /** @public */",
  //             "  static foo() {}",
  //             "  /** @public */",
  //             "  foo() {}",
  //             "}"));

  PsiElement esSixClassFoo = getElementUnderCaret(2); // in class definition
  assertThat(esSixClassFoo).isInstanceOf(JSFunction.class);
  assertThat(esSixClassFoo.getText())
      .isEqualTo(
          String.join(
              "\n", //
              "/** @public */",
              "  static foo() {}"));
  assertThat(esSixClassFoo.getParent().getParent().getText())
      .isEqualTo(
          String.join(
              "\n",
              "foo.bar.ESSixClass = class {",
              "  constructor() {}",
              "  /** @public */",
              "  static foo() {}",
              "  /** @public */",
              "  foo() {}",
              "}"));

  PsiElement esSixClassBar = getElementUnderCaret(3); // attached afterwards
  assertThat(esSixClassBar).isInstanceOf(JSFunctionExpression.class);
  assertThat(esSixClassBar.getParent().getText())
      .isEqualTo("foo.bar.ESSixClass.bar = function() {}");

  PsiElement closureClassFoo = getElementUnderCaret(4); // in class definition
  assertThat(closureClassFoo).isInstanceOf(JSFunctionExpression.class);
  assertThat(closureClassFoo.getParent().getParent().getParent().getText())
      .isEqualTo("statics: {foo: function() {}}");

  PsiElement closureClassBar = getElementUnderCaret(5); // attached afterwards
  assertThat(closureClassBar).isInstanceOf(JSFunctionExpression.class);
  assertThat(closureClassBar.getParent().getText()).isEqualTo("exports.bar = function() {}");
}
 
Example #14
Source File: BlazeTypescriptGotoDeclarationHandlerTest.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Test
public void testGotoNonStaticMethods() {
  configureUserTs(
      "import ESFiveClass from 'goog:foo.bar.ESFiveClass';",
      "import ESSixClass from 'goog:foo.bar.ESSixClass';",
      "import ClosureClass from 'goog:foo.bar.ClosureClass';",
      "new ESFiveClass().f<caret>oo();",
      "new ESFiveClass.NestedClass().f<caret>oo();",
      "new ESSixClass().f<caret>oo();",
      "new ESSixClass().b<caret>ar();",
      "new ClosureClass().f<caret>oo();",
      "new ClosureClass().b<caret>ar();");

  // Broken due to upstream bug: https://youtrack.jetbrains.com/issue/WEB-41611
  //
  // PsiElement esFiveClassFoo = getElementUnderCaret(0);
  // assertThat(esFiveClassFoo).isInstanceOf(JSFunctionExpression.class);
  // assertThat(esFiveClassFoo.getParent().getText())
  //     .isEqualTo("foo.bar.ESFiveClass.prototype.foo = function() {}");
  //
  // PsiElement nestedClassFoo = getElementUnderCaret(1);
  // assertThat(nestedClassFoo).isInstanceOf(JSFunction.class);
  // assertThat(nestedClassFoo.getText())
  //     .isEqualTo(
  //         String.join(
  //             "\n", //
  //             "/** @public */",
  //             "  foo() {}"));
  // assertThat(nestedClassFoo.getParent().getParent().getText())
  //     .isEqualTo(
  //         String.join(
  //             "\n",
  //             "foo.bar.ESFiveClass.NestedClass = class {",
  //             "  /** @public */",
  //             "  static foo() {}",
  //             "  /** @public */",
  //             "  foo() {}",
  //             "}"));

  PsiElement esSixClassFoo = getElementUnderCaret(2); // in class definition
  assertThat(esSixClassFoo).isInstanceOf(JSFunction.class);
  assertThat(esSixClassFoo.getText())
      .isEqualTo(
          String.join(
              "\n", //
              "/** @public */",
              "  foo() {}"));
  assertThat(esSixClassFoo.getParent().getParent().getText())
      .isEqualTo(
          String.join(
              "\n",
              "foo.bar.ESSixClass = class {",
              "  constructor() {}",
              "  /** @public */",
              "  static foo() {}",
              "  /** @public */",
              "  foo() {}",
              "}"));

  PsiElement esSixClassBar = getElementUnderCaret(3); // attached afterwards
  assertThat(esSixClassBar).isInstanceOf(JSFunctionExpression.class);
  assertThat(esSixClassBar.getParent().getText())
      .isEqualTo("foo.bar.ESSixClass.prototype.bar = function() {}");

  PsiElement closureClassFoo = getElementUnderCaret(4); // in class definition
  assertThat(closureClassFoo).isInstanceOf(JSFunctionExpression.class);
  assertThat(closureClassFoo.getParent().getText()).isEqualTo("foo: function() {}");
  assertThat(closureClassFoo.getParent().getParent().getText())
      .isEqualTo(
          String.join(
              "\n",
              "{",
              "  constructor: function() {},",
              "  statics: {foo: function() {}},",
              "  foo: function() {},",
              "}"));

  PsiElement closureClassBar = getElementUnderCaret(5); // attached afterwards
  assertThat(closureClassBar).isInstanceOf(JSFunctionExpression.class);
  assertThat(closureClassBar.getParent().getText())
      .isEqualTo("exports.prototype.bar = function() {}");
}
 
Example #15
Source File: UnityScriptToNativeElementTransformer.java    From consulo-unity3d with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public PsiElement transform(@Nonnull PsiElement psiElement)
{
	if(psiElement instanceof UnityScriptDotNetTypeDeclaration)
	{
		CSharpLightTypeDeclarationBuilder builder = new CSharpLightTypeDeclarationBuilder(psiElement)
		{
			@Nonnull
			@Override
			public Language getLanguage()
			{
				return JavaScriptLanguage.INSTANCE;
			}
		};
		PsiElement navigationElement = psiElement.getNavigationElement();

		builder.withName(((UnityScriptDotNetTypeDeclaration) psiElement).getName());
		builder.setNavigationElement(navigationElement);
		builder.addModifier(DotNetModifier.PUBLIC);
		builder.putUserData(JS_MARKER, Boolean.TRUE);
		builder.addExtendType(new CSharpTypeRefByQName(psiElement, Unity3dTypes.UnityEngine.MonoBehaviour));

		if(navigationElement instanceof JSFile)
		{
			for(JSSourceElement jsSourceElement : ((JSFile) navigationElement).getStatements())
			{
				if(jsSourceElement instanceof JSFunction)
				{
					String funcName = jsSourceElement.getName();
					if(funcName == null)
					{
						continue;
					}
					CSharpLightMethodDeclarationBuilder methodDeclarationBuilder = new CSharpLightMethodDeclarationBuilder(psiElement.getProject());
					methodDeclarationBuilder.addModifier(DotNetModifier.PUBLIC);
					methodDeclarationBuilder.withReturnType(new CSharpTypeRefByQName(psiElement, DotNetTypes.System.Void));
					methodDeclarationBuilder.withName(funcName);
					methodDeclarationBuilder.setNavigationElement(jsSourceElement);
					builder.addMember(methodDeclarationBuilder);
				}
			}
		}
		return builder;
	}
	return null;
}