org.eclipse.jdt.core.dom.ASTParser Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser. 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: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static IBinding getHoveredNodeBinding(IJavaElement element, ITypeRoot typeRoot, IRegion region) {
	if (typeRoot == null || region == null) {
		return null;
	}
	IBinding binding;
	ASTNode node = getHoveredASTNode(typeRoot, region);
	if (node == null) {
		ASTParser p = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
		p.setProject(element.getJavaProject());
		p.setBindingsRecovery(true);
		try {
			binding = p.createBindings(new IJavaElement[] { element }, null)[0];
		} catch (OperationCanceledException e) {
			return null;
		}
	} else {
		binding = resolveBinding(node);
	}
	return binding;
}
 
Example #2
Source File: SarlClassPathDetector.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Visit the given Java compilation unit.
 *
 * @param jfile the compilation unit.
 */
protected void visitJavaCompilationUnit(IFile jfile) {
	final ICompilationUnit cu = JavaCore.createCompilationUnitFrom(jfile);
	if (cu != null) {
		final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		final CompilationUnit root = (CompilationUnit) parser.createAST(null);
		final PackageDeclaration packDecl = root.getPackage();

		final IPath packPath = jfile.getParent().getFullPath();
		final String cuName = jfile.getName();
		if (packDecl == null) {
			addToMap(this.sourceFolders, packPath, new Path(cuName));
		} else {
			final IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			final IPath folderPath = getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(this.sourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
Example #3
Source File: OverrideCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private CompilationUnit getRecoveredAST(IDocument document, int offset, Document recoveredDocument) {
	CompilationUnit ast= SharedASTProvider.getAST(fCompilationUnit, SharedASTProvider.WAIT_ACTIVE_ONLY, null);
	if (ast != null) {
		recoveredDocument.set(document.get());
		return ast;
	}

	char[] content= document.get().toCharArray();

	// clear prefix to avoid compile errors
	int index= offset - 1;
	while (index >= 0 && Character.isJavaIdentifierPart(content[index])) {
		content[index]= ' ';
		index--;
	}

	recoveredDocument.set(new String(content));

	final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);
	parser.setSource(content);
	parser.setUnitName(fCompilationUnit.getElementName());
	parser.setProject(fCompilationUnit.getJavaProject());
	return (CompilationUnit) parser.createAST(new NullProgressMonitor());
}
 
Example #4
Source File: SrcTreeGenerator.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
private static void parseAST(String[] srcFiles, Charset srcCharset,
        String[] classPathEntries, FileASTRequestor requestor) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    Map<String, String> options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setEnvironment(classPathEntries, null, null, true);
    String[] srcEncodings = new String[srcFiles.length];
    for (int i = 0; i < srcEncodings.length; i++) {
        srcEncodings[i] = srcCharset.name();
    }
    parser.createASTs(
            srcFiles, srcEncodings, new String[]{}, requestor, null);
}
 
Example #5
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isValidVarargsExpression(String string) {
	String trimmed= string.trim();
	if ("".equals(trimmed)) //speed up for a common case //$NON-NLS-1$
		return true;
	StringBuffer cuBuff= new StringBuffer();
	cuBuff.append("class A{ {m("); //$NON-NLS-1$
	int offset= cuBuff.length();
	cuBuff.append(trimmed)
		  .append(");}}"); //$NON-NLS-1$
	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(cuBuff.toString().toCharArray());
	CompilationUnit cu= (CompilationUnit) p.createAST(null);
	Selection selection= Selection.createFromStartLength(offset, trimmed.length());
	SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
	cu.accept(analyzer);
	ASTNode[] selectedNodes= analyzer.getSelectedNodes();
	if (selectedNodes.length == 0)
		return false;
	for (int i= 0; i < selectedNodes.length; i++) {
		if (! (selectedNodes[i] instanceof Expression))
			return false;
	}
	return true;
}
 
Example #6
Source File: JavaConverter.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param unitName some CU name e.g. Clazz. If unitName is null, a body declaration content is considered.<br>
 * 			See org.eclipse.jdt.core.dom.ASTParser.setUnitName(String)
 * @param javaSrc Java source code as String
 * @param imports Additional imports to add
 * @param parser ASTParser to use
 * @param conditionalExpressionsAllowed informs, if conditional aka ternary expressions like "cond? a : b" are allowed (by preference setting)
 */
private JavaConverter.ConversionResult internalToXtend(final String unitName, final String javaSrc, final String[] imports, final ASTParserFactory.ASTParserWrapper parser, final boolean conditionalExpressionsAllowed) {
  final StringBuilder javaSrcBuilder = new StringBuilder();
  if ((imports != null)) {
    final Consumer<String> _function = (String it) -> {
      javaSrcBuilder.append((("import " + it) + ";"));
    };
    ((List<String>)Conversions.doWrapArray(imports)).forEach(_function);
  }
  if ((unitName == null)) {
    parser.setUnitName("MISSING");
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("class MISSING { ");
    _builder.append(javaSrc);
    _builder.append(" }");
    javaSrcBuilder.append(_builder);
  } else {
    parser.setUnitName(unitName);
    javaSrcBuilder.append(javaSrc);
  }
  parser.setKind(ASTParser.K_COMPILATION_UNIT);
  final String preparedJavaSrc = javaSrcBuilder.toString();
  parser.setSource(preparedJavaSrc.toCharArray());
  final ASTNode result = parser.createAST();
  return this.executeAstFlattener(preparedJavaSrc, result, parser.getTargetLevel(), false, conditionalExpressionsAllowed);
}
 
Example #7
Source File: SourceCompiler.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static ASTParser createParser(String sourceVersion) {
		ASTParser parser = ASTParser.newParser(AST.JLS10);

		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setResolveBindings(true);
		//TODO
//		parser.setUnitName(unitName);
		parser.setBindingsRecovery(true);
		parser.setStatementsRecovery(true);

		Map options = JavaCore.getOptions();
		
		options.put(JavaCore.COMPILER_COMPLIANCE, sourceVersion);
		options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, sourceVersion);
		options.put(JavaCore.COMPILER_SOURCE, sourceVersion);

		parser.setCompilerOptions(options);

		return parser;
	}
 
Example #8
Source File: SORecommender.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private HashMap<String, HashSet<String>> parseKCUnit(String snippet) throws IOException {
	HashMap<String, HashSet<String>> tokens = new HashMap<String, HashSet<String>>();
	ASTParser parser = ASTParser.newParser(AST.JLS9);
	parser.setResolveBindings(true);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(snippet.toCharArray());
	parser.setResolveBindings(true);
	Hashtable<String, String> options = JavaCore.getOptions();
	options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	parser.setCompilerOptions(options);
	try {
		CompilationUnit cu = (CompilationUnit) parser.createAST(null);
		MyASTVisitor myVisitor = new MyASTVisitor();
		cu.accept(myVisitor);
		tokens = myVisitor.getTokens();
	} catch (Exception exc) {
		logger.error("JDT parsing error");
	}
	return tokens;
}
 
Example #9
Source File: TypeCheckingEvolution.java    From JDeodorant with MIT License 6 votes vote down vote up
private List<TypeCheckElimination> generateTypeCheckEliminationsWithinJavaProject(IJavaProject javaProject, TypeCheckElimination elimination) {
	List<TypeCheckElimination> typeCheckEliminations = new ArrayList<TypeCheckElimination>();
	try {
		IPackageFragmentRoot[] iPackageFragmentRoots = javaProject.getPackageFragmentRoots();
		for(IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
			IJavaElement[] children = iPackageFragmentRoot.getChildren();
			for(IJavaElement child : children) {
				if(child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
					IPackageFragment iPackageFragment = (IPackageFragment)child;
					ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
					for(ICompilationUnit iCompilationUnit : iCompilationUnits) {
						ASTParser parser = ASTParser.newParser(ASTReader.JLS);
				        parser.setKind(ASTParser.K_COMPILATION_UNIT);
				        parser.setSource(iCompilationUnit);
				        parser.setResolveBindings(true); // we need bindings later on
				        CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
						typeCheckEliminations.addAll(generateTypeCheckEliminationsWithinCompilationUnit(compilationUnit, elimination));
					}
				}
			}
		}
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	return typeCheckEliminations;
}
 
Example #10
Source File: EclipseASTParserFactory.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ASTParserFactory.ASTParserWrapper createJavaParser(final Object context) {
  if ((context instanceof IJavaElement)) {
    final IJavaProject project = ((IJavaElement)context).getJavaProject();
    final String projlevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
    final ASTParser parser = this.createDefaultJavaParser(projlevel);
    if ((context instanceof IJavaProject)) {
      parser.setProject(project);
      this.tweakOptions(parser, project);
    } else {
      if ((context instanceof ICompilationUnit)) {
        parser.setSource(((ICompilationUnit)context));
        this.tweakOptions(parser, ((ICompilationUnit)context).getJavaProject());
      }
    }
    return new ASTParserFactory.ASTParserWrapper(projlevel, parser);
  }
  return super.createJavaParser(context);
}
 
Example #11
Source File: ASTParserFactory.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected final ASTParser createDefaultJavaParser(final String javaVersion) {
  ASTParser parser = null;
  final Hashtable<String, String> options = JavaCore.getOptions();
  try {
    parser = ASTParser.newParser(ASTParserFactory.asJLS(javaVersion));
    JavaCore.setComplianceOptions(javaVersion, options);
  } catch (final Throwable _t) {
    if (_t instanceof IllegalArgumentException) {
      parser = ASTParser.newParser(ASTParserFactory.asJLS(this.minParserApiLevel));
      JavaCore.setComplianceOptions(this.minParserApiLevel, options);
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
  options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
  parser.setCompilerOptions(options);
  parser.setStatementsRecovery(true);
  parser.setResolveBindings(true);
  parser.setBindingsRecovery(true);
  return parser;
}
 
Example #12
Source File: OverrideCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private CompilationUnit getRecoveredAST(IDocument document, int offset, Document recoveredDocument) {
	CompilationUnit ast = CoreASTProvider.getInstance().getAST(fCompilationUnit, CoreASTProvider.WAIT_YES, null);
	if (ast != null) {
		recoveredDocument.set(document.get());
		return ast;
	}

	char[] content= document.get().toCharArray();

	// clear prefix to avoid compile errors
	int index= offset - 1;
	while (index >= 0 && Character.isJavaIdentifierPart(content[index])) {
		content[index]= ' ';
		index--;
	}

	recoveredDocument.set(new String(content));

	final ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);
	parser.setSource(content);
	parser.setUnitName(fCompilationUnit.getElementName());
	parser.setProject(fCompilationUnit.getJavaProject());
	return (CompilationUnit) parser.createAST(new NullProgressMonitor());
}
 
Example #13
Source File: CleanUpPostSaveListener.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private CompilationUnit createAst(ICompilationUnit unit, Map<String, String> cleanUpOptions, IProgressMonitor monitor) {
	IJavaProject project= unit.getJavaProject();
	if (compatibleOptions(project, cleanUpOptions)) {
		CompilationUnit ast= SharedASTProvider.getAST(unit, SharedASTProvider.WAIT_NO, monitor);
		if (ast != null)
			return ast;
	}

	ASTParser parser= CleanUpRefactoring.createCleanUpASTParser();
	parser.setSource(unit);

	Map<String, String> compilerOptions= RefactoringASTParser.getCompilerOptions(unit.getJavaProject());
	compilerOptions.putAll(cleanUpOptions);
	parser.setCompilerOptions(compilerOptions);

	return (CompilationUnit)parser.createAST(monitor);
}
 
Example #14
Source File: ClassPathDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void visitCompilationUnit(IFile file) {
	ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file);
	if (cu != null) {
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		CompilationUnit root= (CompilationUnit)parser.createAST(null);
		PackageDeclaration packDecl= root.getPackage();
		
		IPath packPath= file.getParent().getFullPath();
		String cuName= file.getName();
		if (packDecl == null) {
			addToMap(fSourceFolders, packPath, new Path(cuName));
		} else {
			IPath relPath= new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			IPath folderPath= getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(fSourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
Example #15
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void initDomAST() {
		if (isReadOnly())
			return;
		
		ASTParser parser= ASTParser.newParser(AST.JLS8);
		parser.setSource(getCompilationUnit());
		parser.setResolveBindings(true);
		org.eclipse.jdt.core.dom.ASTNode domAst = parser.createAST(new NullProgressMonitor());
		
//		org.eclipse.jdt.core.dom.AST ast = domAst.getAST();
		
		NodeFinder nf = new NodeFinder(domAst, getCompletionOffset(), 1);
		org.eclipse.jdt.core.dom.ASTNode cv = nf.getCoveringNode();
		
		bodyDeclaration = ASTResolving.findParentBodyDeclaration(cv);
		parentDeclaration = ASTResolving.findParentType(cv);
		domInitialized = true;
	}
 
Example #16
Source File: ValidationTestBase.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
protected CompilationUnit prepareAST(String javaFile) throws IOException {
	File projectRoot = new File(VALIDATION_EXAMPLES_ROOT).getAbsoluteFile();
	File sourceFile = new File(projectRoot.getCanonicalPath() + getValidationExamplesPackage() + javaFile);

	ASTParser parser = ASTParser.newParser(AST.JLS8);
	char[] content = SharedUtils.getFileContents(sourceFile);

	String[] classpath = {};
	String[] sourcepath = { projectRoot.getCanonicalPath(), new File(API_SRC_LOC).getCanonicalPath() };
	String[] encodings = { "UTF-8", "UTF-8" };

	parser.setSource(content);

	parser.setResolveBindings(true);
	parser.setBindingsRecovery(true);
	parser.setUnitName(sourceFile.getName());
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setEnvironment(classpath, sourcepath, encodings, true);

	return (CompilationUnit) parser.createAST(null);
}
 
Example #17
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 6 votes vote down vote up
private UMLModelASTReader(File rootFolder, ASTParser parser, List<String> javaFiles, Set<String> repositoryDirectories) {
	this.umlModel = new UMLModel(repositoryDirectories);
	this.projectRoot = rootFolder.getPath();
	this.parser = parser;
	final String[] emptyArray = new String[0];
	
	String[] filesArray = new String[javaFiles.size()];
	for (int i = 0; i < filesArray.length; i++) {
		filesArray[i] = rootFolder + File.separator + javaFiles.get(i).replaceAll("/", systemFileSeparator);
	}

	FileASTRequestor fileASTRequestor = new FileASTRequestor() { 
		@Override
		public void acceptAST(String sourceFilePath, CompilationUnit ast) {
			String relativePath = sourceFilePath.substring(projectRoot.length() + 1).replaceAll(systemFileSeparator, "/");
			processCompilationUnit(relativePath, ast);
		}
	};
	this.parser.createASTs((String[]) filesArray, null, emptyArray, fileASTRequestor, null);
}
 
Example #18
Source File: Java7BaseTest.java    From compiler with Apache License 2.0 6 votes vote down vote up
protected static void dumpJava(final String content) {
	final ASTParser parser = ASTParser.newParser(astLevel);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(content.toCharArray());

	final Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(javaVersion, options);
	parser.setCompilerOptions(options);

	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

	try {
		final UglyMathCommentsExtractor cex = new UglyMathCommentsExtractor(cu, content);
		final ASTDumper dumper = new ASTDumper(cex);
		dumper.dump(cu);
		cex.close();
	} catch (final Exception e) {}
}
 
Example #19
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private CompilationUnit createSourceCuNode() {
	Assert.isTrue(getSourceCu() != null || getSourceClassFile() != null);
	Assert.isTrue(getSourceCu() == null || getSourceClassFile() == null);
	ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setBindingsRecovery(true);
	parser.setResolveBindings(true);
	if (getSourceCu() != null) {
		parser.setSource(getSourceCu());
	} else {
		parser.setSource(getSourceClassFile());
	}
	return (CompilationUnit) parser.createAST(null);
}
 
Example #20
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Type parseType(String typeString, IJavaProject javaProject, List<String> problemsCollector) {
	if ("".equals(typeString.trim())) //speed up for a common case //$NON-NLS-1$
		return null;
	if (! typeString.trim().equals(typeString))
		return null;

	StringBuffer cuBuff= new StringBuffer();
	cuBuff.append("interface A{"); //$NON-NLS-1$
	int offset= cuBuff.length();
	cuBuff.append(typeString).append(" m();}"); //$NON-NLS-1$

	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(cuBuff.toString().toCharArray());
	p.setProject(javaProject);
	CompilationUnit cu= (CompilationUnit) p.createAST(null);
	Selection selection= Selection.createFromStartLength(offset, typeString.length());
	SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
	cu.accept(analyzer);
	ASTNode selected= analyzer.getFirstSelectedNode();
	if (!(selected instanceof Type))
		return null;
	Type type= (Type)selected;
	if (MethodTypesSyntaxChecker.isVoidArrayType(type))
		return null;
	IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS);
	if (problems.length > 0) {
		for (int i= 0; i < problems.length; i++)
			problemsCollector.add(problems[i].getMessage());
	}

	String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
	if (typeString.equals(typeNodeRange))
		return type;
	else
		return null;
}
 
Example #21
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Nonnull
protected final CompilationUnit createWorkingCopy(@Nonnull ICompilationUnit unit) throws JavaModelException {
    unit.becomeWorkingCopy(monitor);
    ASTParser parser = createAstParser();
    parser.setSource(unit);
    parser.setResolveBindings(resolveBindings());
    return (CompilationUnit) parser.createAST(monitor);
}
 
Example #22
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding findTypeBinding(IType currentType) throws JavaModelException{
  final ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setKind(ASTParser.K_COMPILATION_UNIT);
  parser.setSource(currentType.getCompilationUnit());
  parser.setResolveBindings(true);
  CompilationUnit unit = (CompilationUnit) parser.createAST(null);
  return ASTNodes.getTypeBinding(unit, currentType);
}
 
Example #23
Source File: RemoteServiceValidatorTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static ASTNode newAST(ICompilationUnit syncInterface) {
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setResolveBindings(true);
  parser.setProject(syncInterface.getJavaProject());
  parser.setSource(syncInterface);
  return parser.createAST(null);
}
 
Example #24
Source File: JsniParserTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void testParseMethodDeclaration() {
  // Have JDT parse the compilation unit
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(getTestProject());
  parser.setResolveBindings(false);
  parser.setSource(testClass.getCompilationUnit());
  CompilationUnit root = (CompilationUnit) parser.createAST(null);

  // Find the JSNI method and parse it
  TypeDeclaration typeDecl = (TypeDeclaration) root.types().get(0);
  MethodDeclaration jsniMethod = typeDecl.getMethods()[0];
  JavaValidationResult result = JsniParser.parse(jsniMethod);

  // Verify the Java refs
  List<JsniJavaRef> refs = result.getJavaRefs();
  assertEquals(3, refs.size());
  assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.A$B::getNumber()")));
  assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.JsniParserTest::getSum(II)")));
  assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.JsniParserTest::counter")));

  // Verify the problems
  List<GWTJavaProblem> problems = result.getProblems();
  assertEquals(1, problems.size());
  GWTJavaProblem problem = problems.get(0);
  assertEquals(GWTProblemType.JSNI_JAVA_REF_UNRESOLVED_TYPE, problem.getProblemType());
  IRegion expectedProblemRegion = RegionConverter.convertWindowsRegion(184, 0, testClass.getContents());
  assertEquals(expectedProblemRegion.getOffset(), problem.getSourceStart());
}
 
Example #25
Source File: JavaValidationVisitorTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();

  // Have JDT parse the compilation unit
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(getTestProject());
  parser.setResolveBindings(false);
  parser.setSource(testClass.getCompilationUnit());
  ast = parser.createAST(null);
}
 
Example #26
Source File: TypeEnvironment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private StandardType createStandardType(String fullyQualifiedName, IJavaProject focus) {
	try {
		IType javaElementType= focus.findType(fullyQualifiedName);
		StandardType result= fStandardTypes.get(javaElementType);
		if (result != null)
			return result;
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setProject(focus);
		IBinding[] bindings= parser.createBindings(new IJavaElement[] {javaElementType} , null);
		return createStandardType((ITypeBinding)bindings[0]);
	} catch (JavaModelException e) {
		// fall through
	}
	return null;
}
 
Example #27
Source File: JavaConverter.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param javaSrc Java class source code as String
 * @param javaImports imports to use
 * @param targetElement Used to determinate javaCode conversion type
 * @param classPathContext Contextual object from where to get the classpath entries (e.g. IProject in eclipse Module in idea)
 * @param conditionalExpressionsAllowed informs, if conditional aka ternary expressions like "cond? a : b" are allowed (by preference setting)
 */
public String toXtend(final String javaSrc, final String[] javaImports, final EObject targetElement, final Object classPathContext, final boolean conditionalExpressionsAllowed) {
  boolean forceStatement = this.shouldForceStatementMode(targetElement);
  JavaCodeAnalyzer.JavaParseResult<? extends ASTNode> parseResult = this.codeAnalyzer.determinateJavaType(javaSrc);
  if ((parseResult == null)) {
    return javaSrc;
  }
  JavaConverter.ConversionResult conversionResult = null;
  if ((forceStatement || (parseResult.getType() < ASTParser.K_CLASS_BODY_DECLARATIONS))) {
    int _type = parseResult.getType();
    boolean _tripleEquals = (_type == ASTParser.K_EXPRESSION);
    if (_tripleEquals) {
      conversionResult = this.expressionToXtend(javaSrc, classPathContext, conditionalExpressionsAllowed);
    } else {
      conversionResult = this.statementToXtend(javaSrc, classPathContext);
    }
  } else {
    String[] _xifexpression = null;
    if ((javaImports != null)) {
      _xifexpression = javaImports;
    } else {
      _xifexpression = null;
    }
    conversionResult = this.bodyDeclarationToXtend(javaSrc, _xifexpression, classPathContext);
  }
  return conversionResult.getXtendCode();
}
 
Example #28
Source File: JavaASTUtil.java    From compiler with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static ASTParser buildParser(FileKind fileKind) {
	int astLevel = -1;
	String compliance = null;
	switch (fileKind) {
	case SOURCE_JAVA_JLS2:
		astLevel = AST.JLS2;
		compliance = JavaCore.VERSION_1_4;
		break;
	case SOURCE_JAVA_JLS3:
		astLevel = AST.JLS3;
		compliance = JavaCore.VERSION_1_5;
		break;
	case SOURCE_JAVA_JLS4:
		astLevel = AST.JLS4;
		compliance = JavaCore.VERSION_1_7;
		break;
	case SOURCE_JAVA_JLS8:
		astLevel = AST.JLS8;
		compliance = JavaCore.VERSION_1_8;
		break;
	default:
		break;
	}
	if (compliance != null) {
		ASTParser parser = ASTParser.newParser(astLevel);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);

		final Map<?, ?> options = JavaCore.getOptions();
		JavaCore.setComplianceOptions(compliance, options);
		parser.setCompilerOptions(options);
		return parser;
	}
	return null;
}
 
Example #29
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression createExpression(String expr) {
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_EXPRESSION);
	parser.setResolveBindings(true);
	parser.setSource(expr.toCharArray());
	
	org.eclipse.jdt.core.dom.ASTNode astNode = parser.createAST(new NullProgressMonitor());
	return (Expression) astNode;
}
 
Example #30
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private static ASTParser buildAstParser(File srcFolder) {
	ASTParser parser = ASTParser.newParser(AST.JLS11);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	Map<String, String> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
	parser.setCompilerOptions(options);
	parser.setResolveBindings(false);
	parser.setEnvironment(new String[0], new String[]{srcFolder.getPath()}, null, false);
	return parser;
}