org.eclipse.xtext.xbase.compiler.ImportManager Java Examples

The following examples show how to use org.eclipse.xtext.xbase.compiler.ImportManager. 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: TreeAppendableTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testInsertionIsProhibited() {
	ITextRegionWithLineInformation root = new TextRegionWithLineInformation(47, 11, 12, 137);
	ITextRegionWithLineInformation child = new TextRegionWithLineInformation(8, 15, 12, 137);
	expectedRegions = Arrays.asList(root, child).iterator();
	TreeAppendable appendable = new TreeAppendable(new ImportManager(false), this, this, this, content, "  ", "\n");
	TreeAppendable traced = appendable.trace(content);
	appendable.append("test");
	// don't use @Test(expected=..) since we want to be sure about the cause
	try {
		traced.append("insertion");
		fail("Expected IllegalStateException");
	} catch(IllegalStateException e) {
		// expected
	}
}
 
Example #2
Source File: JavaInlineExpressionCompiler.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public void appendInlineAnnotation(JvmAnnotationTarget target, XtendExecutable source) {
	final ImportManager imports = new ImportManager();
	final InlineAnnotationTreeAppendable result = newAppendable(imports);
	generate(source.getExpression(), null, source, result);

	final String content = result.getContent();
	if (!Strings.isEmpty(content)) {
		final List<String> importedTypes = imports.getImports();
		final JvmTypeReference[] importArray = new JvmTypeReference[importedTypes.size()];
		for (int i = 0; i < importArray.length; ++i) {
			importArray[i] = this.typeReferences.getTypeForName(importedTypes.get(i), source);
		}
		appendInlineAnnotation(target, source.eResource().getResourceSet(), content,
				result.isConstant(), result.isStatement(), importArray);
	}
}
 
Example #3
Source File: TreeAppendableTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testIntermediatesMayBeEmpty() {
	ITextRegionWithLineInformation root = new TextRegionWithLineInformation(47, 11, 12, 137);
	ITextRegionWithLineInformation emptyChild = new TextRegionWithLineInformation(8, 15, 12, 137);
	ITextRegionWithLineInformation emptyGrandChild = new TextRegionWithLineInformation(123, 321, 12, 137);
	expectedRegions = Arrays.asList(root, emptyChild, emptyGrandChild).iterator();
	TreeAppendable appendable = new TreeAppendable(new ImportManager(false), this, this, this, content, "  ", "\n");
	appendable.trace(content).trace(content).append("text");
	assertEquals("text", appendable.getContent());
	AbstractTraceRegion traceRegion = appendable.getTraceRegion();
	assertEquals(1, traceRegion.getNestedRegions().size());
	AbstractTraceRegion child = traceRegion.getNestedRegions().get(0);
	assertEquals(1, child.getNestedRegions().size());
	AbstractTraceRegion grandChild = child.getNestedRegions().get(0);
	assertTrue(grandChild.getNestedRegions().isEmpty());
	assertEquals(0, grandChild.getMyOffset());
	assertEquals(4, grandChild.getMyLength());
	assertEquals(123, grandChild.getMergedAssociatedLocation().getOffset());
	assertEquals(321, grandChild.getMergedAssociatedLocation().getLength());
}
 
Example #4
Source File: Utils.java    From sarl with Apache License 2.0 6 votes vote down vote up
private static void addParamToSignature(StringBuilder signature, XtendParameter parameter,
		SARLGrammarKeywordAccess grammarAccess, ImportManager importManager, ISerializer serializer) {
	signature.append(parameter.getName());
	signature.append(' ');
	signature.append(grammarAccess.getColonKeyword());
	signature.append(' ');
	signature.append(getSignatureType(parameter.getParameterType().getType(), importManager));
	if (parameter.isVarArg()) {
		signature.append(grammarAccess.getWildcardAsteriskKeyword());
	} else if (parameter instanceof SarlFormalParameter) {
		final SarlFormalParameter sarlParameter = (SarlFormalParameter) parameter;
		if (sarlParameter.getDefaultValue() != null) {
			signature.append(' ');
			signature.append(grammarAccess.getEqualsSignKeyword());
			signature.append(' ');
			signature.append(serializer.serialize(sarlParameter.getDefaultValue()).trim());
		}
	}
}
 
Example #5
Source File: Utils.java    From sarl with Apache License 2.0 6 votes vote down vote up
private static void addAnnotationToSignature(StringBuilder textRepresentation, SARLGrammarKeywordAccess elements,
		ISerializer serializer, ImportManager importManager, XAnnotation annotation) {
	textRepresentation.append(elements.getCommercialAtKeyword());
	textRepresentation.append(getSignatureType(annotation.getAnnotationType(), importManager));
	final XExpression value = annotation.getValue();
	if (value != null) {
		textRepresentation.append(elements.getLeftParenthesisKeyword());
		textRepresentation.append(serializer.serialize(value).trim());
		textRepresentation.append(elements.getRightParenthesisKeyword());
	} else if (!annotation.getElementValuePairs().isEmpty()) {
		textRepresentation.append(elements.getLeftParenthesisKeyword());
		boolean addComa = false;
		for (final XAnnotationElementValuePair pair : annotation.getElementValuePairs()) {
			if (addComa) {
				textRepresentation.append(elements.getCommaKeyword());
			} else {
				addComa = true;
			}
			textRepresentation.append(elements.getEqualsSignKeyword());
			textRepresentation.append(serializer.serialize(pair.getValue()).trim());
		}
		textRepresentation.append(elements.getRightParenthesisKeyword());
	}
}
 
Example #6
Source File: TreeAppendableTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testNoRedundantRegions() {
	ITextRegionWithLineInformation redundant = new TextRegionWithLineInformation(47, 11, 12, 137);
	ITextRegionWithLineInformation second = new TextRegionWithLineInformation(8, 15, 12, 137);
	expectedRegions = Arrays.asList(redundant, redundant, second).iterator();
	TreeAppendable appendable = new TreeAppendable(new ImportManager(false), this, this, this, content, "  ", "\n");
	appendable.append("initial");
	appendable.trace(content).append("first");
	appendable.trace(content).append("second");
	assertEquals("initialfirstsecond", appendable.getContent());
	AbstractTraceRegion traceRegion = appendable.getTraceRegion();
	assertNotNull(traceRegion);
	assertEquals(47, traceRegion.getMergedAssociatedLocation().getOffset());
	assertEquals(11, traceRegion.getMergedAssociatedLocation().getLength());
	assertEquals(0, traceRegion.getMyOffset());
	assertEquals("initialfirstsecond".length(), traceRegion.getMyLength());
	List<AbstractTraceRegion> nestedRegions = traceRegion.getNestedRegions();
	assertEquals(1, nestedRegions.size());
	AbstractTraceRegion child = nestedRegions.get(0);
	assertEquals(8, child.getMergedAssociatedLocation().getOffset());
	assertEquals(15, child.getMergedAssociatedLocation().getLength());
	assertEquals("initialfirst".length(), child.getMyOffset());
	assertEquals("second".length(), child.getMyLength());
}
 
Example #7
Source File: GenerateTestsMojo.java    From sarl with Apache License 2.0 6 votes vote down vote up
private static void write(File root, String packageName, String typeName, ImportManager importManager,
		ITreeAppendable it) throws IOException {
	File outputFile = getOutputFolder(root, packageName);
	outputFile.mkdirs();
	outputFile = getOutputJavaFilename(outputFile, typeName);
	try (FileWriter writer = new FileWriter(outputFile)) {
		writer.write("/* This file was automatically generated. Do not change its content. */\n\n"); //$NON-NLS-1$
		writer.write("package "); //$NON-NLS-1$
		writer.write(packageName);
		writer.write(";\n"); //$NON-NLS-1$
		for (final String importedType : importManager.getImports()) {
			writer.write("import "); //$NON-NLS-1$
			writer.write(importedType);
			writer.write(";\n"); //$NON-NLS-1$
		}
		writer.write(it.getContent());
		writer.flush();
	}
}
 
Example #8
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public ImportManager getImportManager(final ITreeAppendable appendable) {
  try {
    ImportManager _xblockexpression = null;
    {
      final Field stateField = appendable.getClass().getDeclaredField("state");
      stateField.setAccessible(true);
      final Object stateValue = stateField.get(appendable);
      final Field importManagerField = stateValue.getClass().getDeclaredField("importManager");
      importManagerField.setAccessible(true);
      Object _get = importManagerField.get(stateValue);
      _xblockexpression = ((ImportManager) _get);
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #9
Source File: TreeAppendableTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testNewlineIndents() {
	expectedRegions = Collections.<ITextRegionWithLineInformation>singleton(ITextRegionWithLineInformation.EMPTY_REGION).iterator();
	TreeAppendable appendable = new TreeAppendable(new ImportManager(false), this, this, this, content, "aa", "bb");
	assertEquals("bb", appendable.newLine().getContent());
	appendable.increaseIndentation();
	assertEquals("bbbbaa", appendable.newLine().getContent());
	appendable.decreaseIndentation();
	assertEquals("bbbbaabb", appendable.newLine().getContent());
}
 
Example #10
Source File: CompilerTraceTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertTrace(final String javaCodeWithMarker, String xbaseCodeWithMarker) throws Exception {
	xbaseCodeWithMarker = " " + xbaseCodeWithMarker + " ";
	Matcher xbaseMatcher = p.matcher(xbaseCodeWithMarker);
	assertTrue(xbaseMatcher.matches());
	String xbaseGroup1 = xbaseMatcher.group(1);
	String xbaseGroup2 = xbaseMatcher.group(2);
	String xbaseGroup3 = xbaseMatcher.group(3);
	String actualCode = xbaseGroup1 + xbaseGroup2 + xbaseGroup3; 
	XExpression model = expression(actualCode,true);
	TreeAppendable appendable = new TreeAppendable(new ImportManager(true), converter, locationProvider, jvmModelAssociations, model, "  ", "\n");
	XbaseCompiler compiler = get(XbaseCompiler.class);
	LightweightTypeReference returnType = typeResolver.resolveTypes(model).getReturnType(model);
	if (returnType == null) {
		throw new IllegalStateException();
	}
	compiler.compile(model, appendable, returnType);
	String compiledJavaCode = appendable.getContent();
	Matcher javaMatcher = p.matcher(javaCodeWithMarker);
	assertTrue(javaMatcher.matches());
	String javaGroup1 = javaMatcher.group(1);
	String javaGroup2 = javaMatcher.group(2);
	String javaGroup3 = javaMatcher.group(3);
	String actualExpectation = javaGroup1 + javaGroup2 + javaGroup3;
	assertEquals(actualExpectation, compiledJavaCode);
	ITrace trace = new SimpleTrace(appendable.getTraceRegion());
	ILocationInResource location = trace.getBestAssociatedLocation(new TextRegion(javaGroup1.length(), javaGroup2.length()));
	if (location == null) {
		throw new IllegalStateException("location may not be null");
	}
	assertEquals(new TextRegion(xbaseGroup1.length(), xbaseGroup2.length()), location.getTextRegion());
}
 
Example #11
Source File: TreeAppendableTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testAppendedTextIsIndented() {
	expectedRegions = Collections.<ITextRegionWithLineInformation>singleton(ITextRegionWithLineInformation.EMPTY_REGION).iterator();
	TreeAppendable appendable = new TreeAppendable(new ImportManager(false), this, this, this, content, "aa", "bb");
	appendable.increaseIndentation();
	appendable.append("my \n text \r more \r\n end");
	assertEquals("my bbaa text bbaa more bbaa end", appendable.getContent());
}
 
Example #12
Source File: CompilationContextImpl.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public ImportManager getImportManager(final ITreeAppendable appendable) {
  try {
    Object _get = this.reflectExtensions.<Object>get(appendable, "state");
    ImportManager _get_1 = null;
    if (_get!=null) {
      _get_1=this.reflectExtensions.<ImportManager>get(_get, "importManager");
    }
    return _get_1;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #13
Source File: GenerateTestsMojo.java    From sarl with Apache License 2.0 5 votes vote down vote up
private void generateTestsForSuccessCode(ITreeAppendable parent, ImportManager importManager,
		File inputFile, List<ValidationComponent> successCompilationComponents) {
	int i = 0;
	for (final ValidationComponent component : successCompilationComponents) {
		getLog().debug(MessageFormat.format(Messages.GenerateTestsMojo_1,
				inputFile.getName(), component.getLinenoInSourceFile(), component.getCode()));
		final String actionName = toActionName("success", component, i); //$NON-NLS-1$
		final String displayName = toTestDisplayName(Messages.GenerateTestsMojo_7, i, component);
		final ILocationData location = new LocationData(
				// Offset
				component.getOffsetInSourceFile(),
				// Length
				component.getLengthInSourceFile(),
				// Line number
				component.getLinenoInSourceFile(),
				// End line number
				component.getEndLinenoInSourceFile(),
				// Source URI
				null);
		final ITreeAppendable it = parent.trace(location);
		//
		it.append("@").append(Test.class).newLine();
		it.append("@").append(DisplayName.class).append("(\"").append(displayName).append("\")").newLine();
		it.append("@").append(Tag.class).append("(\"success\")").newLine();
		it.append("@").append(Tag.class).append("(\"success_").append(Integer.toString(i)).append("\")").newLine();
		it.append("public void ").append(actionName).append("() throws ")
			.append(Exception.class).append(" {").increaseIndentation().newLine();
		it.append(List.class).append("<String> issues = getScriptExecutor().compile(")
			.append(str(component.getLinenoInSourceFile())).append(", \"")
			.append(str(component.getCode())).append("\");").newLine();
		it.append("assertNoIssue(").append(str(component.getLinenoInSourceFile()))
			.append(", issues);").decreaseIndentation().newLine();
		it.append("}").newLine();
		//
		++i;
	}
}
 
Example #14
Source File: GenerateTestsMojo.java    From sarl with Apache License 2.0 5 votes vote down vote up
private void generateTestsForFailureCode(ITreeAppendable parent, ImportManager importManager,
		File inputFile, List<ValidationComponent> failureCompilationComponents) {
	int i = 0;
	for (final ValidationComponent component : failureCompilationComponents) {
		getLog().debug(MessageFormat.format(Messages.GenerateTestsMojo_2,
				inputFile.getName(), component.getLinenoInSourceFile(), component.getCode()));
		final String actionName = toActionName("failure", component, i); //$NON-NLS-1$
		final String displayName = toTestDisplayName(Messages.GenerateTestsMojo_8, i, component);
		final ILocationData location = new LocationData(
				// Offset
				component.getOffsetInSourceFile(),
				// Length
				component.getLengthInSourceFile(),
				// Line number
				component.getLinenoInSourceFile(),
				// End line number
				component.getEndLinenoInSourceFile(),
				// Source URI
				null);
		final ITreeAppendable it = parent.trace(location);
		//
		it.append("@").append(Test.class).newLine();
		it.append("@").append(DisplayName.class).append("(\"").append(displayName).append("\")").newLine();
		it.append("@").append(Tag.class).append("(\"failure\")").newLine();
		it.append("@").append(Tag.class).append("(\"failure_").append(Integer.toString(i)).append("\")").newLine();
		it.append("public void ").append(actionName).append("() throws ")
			.append(Exception.class).append(" {").increaseIndentation().newLine();
		it.append(List.class).append("<String> issues = getScriptExecutor().compile(")
			.append(str(component.getLinenoInSourceFile())).append(", \"")
			.append(str(component.getCode())).append("\");").newLine();
		it.append("assertIssues(").append(str(component.getLinenoInSourceFile()))
			.append(", issues);").decreaseIndentation().newLine();
		it.append("}").newLine();
		//
		++i;
	}
}
 
Example #15
Source File: GenerateTestsMojo.java    From sarl with Apache License 2.0 5 votes vote down vote up
private void generateDynamicTests(ITreeAppendable parent, ImportManager importManager,
		File inputFile, List<DynamicValidationComponent> specificComponents) {
	int i = 0;
	for (final DynamicValidationComponent component : specificComponents) {
		getLog().debug(MessageFormat.format(Messages.GenerateTestsMojo_4,
				inputFile.getName(), component.functionName() + i));
		final String actionName = toActionName("dyn_" + component.functionName(), component, i);
		final String displayName = toTestDisplayName(Messages.GenerateTestsMojo_10, i, component);
		final ILocationData location = new LocationData(
				// Offset
				component.getOffsetInSourceFile(),
				// Length
				component.getLengthInSourceFile(),
				// Line number
				component.getLinenoInSourceFile(),
				// End line number
				component.getEndLinenoInSourceFile(),
				// Source URI
				null);
		final ITreeAppendable it = parent.trace(location);
		//
		it.append("@").append(Test.class).newLine();
		it.append("@").append(DisplayName.class).append("(\"").append(displayName).append("\")").newLine();
		it.append("@").append(Tag.class).append("(\"other\")").newLine();
		it.append("@").append(Tag.class).append("(\"other_").append(Integer.toString(i)).append("\")").newLine();
		it.append("public void ").append(actionName).append("() throws ")
			.append(Exception.class).append(" {").increaseIndentation().newLine();
		component.generateValidationCode(it);
		it.decreaseIndentation().newLine();
		it.append("}").newLine();
		//
		++i;
	}
}
 
Example #16
Source File: CodeBuilderFactory.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the injector.
 * @return the injector.
 */
@Pure
protected Injector getInjector() {
	if (this.builderInjector == null) {
		ImportManager importManager = this.importManagerProvider.get();
		this.builderInjector = createOverridingInjector(this.originalInjector, new CodeBuilderModule(importManager));
	}
	return builderInjector;
}
 
Example #17
Source File: ScriptBuilderImpl.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Finalize the script.
 *
 * <p>The finalization includes: <ul>
 * <li>The import section is created.</li>
 * </ul>
 */
public void finalizeScript() {
	if (this.isFinalized) {
		throw new IllegalStateException("already finalized");
	}
	this.isFinalized = true;
	ImportManager concreteImports = new ImportManager(true);
	XImportSection importSection = getScript().getImportSection();
	if (importSection != null) {
		for (XImportDeclaration decl : importSection.getImportDeclarations()) {
			concreteImports.addImportFor(decl.getImportedType());
		}
	}
	for (String importName : getImportManager().getImports()) {
		JvmType type = findType(getScript(), importName).getType();
		if (concreteImports.addImportFor(type) && type instanceof JvmDeclaredType) {
			XImportDeclaration declaration = XtypeFactory.eINSTANCE.createXImportDeclaration();
			declaration.setImportedType((JvmDeclaredType) type);
			if (importSection == null) {
				importSection = XtypeFactory.eINSTANCE.createXImportSection();
				getScript().setImportSection(importSection);
			}
			importSection.getImportDeclarations().add(declaration);
		}
	}
	Resource resource = getScript().eResource();
	if (resource instanceof DerivedStateAwareResource) {
		((DerivedStateAwareResource) resource).discardDerivedState();
	}
}
 
Example #18
Source File: Utils.java    From sarl with Apache License 2.0 5 votes vote down vote up
private static String getSignatureType(JvmType type, ImportManager importManager) {
	if (importManager != null) {
		importManager.addImportFor(type);
		return type.getSimpleName();
	}
	return type.getIdentifier();
}
 
Example #19
Source File: AbstractExtraLanguageGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Write the given file.
 *
 * @param name the name of the type to write.
 * @param appendable the content to be written.
 * @param context the generator context.
 * @return {@code true} if the file was written.
 */
protected boolean writeFile(QualifiedName name, ExtraLanguageAppendable appendable, IExtraLanguageGeneratorContext context) {
	final ExtraLanguageAppendable fileAppendable = createAppendable(null, context);
	generateFileHeader(name, fileAppendable, context);

	final ImportManager importManager = appendable.getImportManager();
	if (importManager != null && !importManager.getImports().isEmpty()) {
		for (final String imported : importManager.getImports()) {
			final QualifiedName qn = getQualifiedNameConverter().toQualifiedName(imported);
			generateImportStatement(qn, fileAppendable, context);
		}
		fileAppendable.newLine();
	}

	fileAppendable.append(appendable.getContent());
	final String content = fileAppendable.getContent();

	if (!Strings.isEmpty(content)) {
		final String fileName = toFilename(name, FILENAME_SEPARATOR);
		final String outputConfiguration = getOutputConfigurationName();
		if (Strings.isEmpty(outputConfiguration)) {
			context.getFileSystemAccess().generateFile(fileName, content);
		} else {
			context.getFileSystemAccess().generateFile(fileName, outputConfiguration, content);
		}
		return true;
	}
	return false;
}
 
Example #20
Source File: PyGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
private void markCapacityFunctions(PyAppendable it) {
	final Map<JvmOperation, String> mapping = this.useCapacityMapping;
	this.useCapacityMapping = new HashMap<>();
	final ImportManager imports = it.getImportManager();
	for (final Entry<JvmOperation, String> entry : mapping.entrySet()) {
		final JvmOperation operation = entry.getKey();
		final JvmDeclaredType type = operation.getDeclaringType();
		imports.addImportFor(type);
		it.declareVariable(operation, entry.getValue());
	}
}
 
Example #21
Source File: TreeAppendableTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUnsafeInsertionIsOk() {
	ITextRegionWithLineInformation root = new TextRegionWithLineInformation(47, 11, 12, 137);
	ITextRegionWithLineInformation child = new TextRegionWithLineInformation(8, 15, 12, 137);
	expectedRegions = Arrays.asList(root, child).iterator();
	TreeAppendable appendable = new TreeAppendable(new ImportManager(false), this, this, this, content, "  ", "\n");
	TreeAppendable traced = appendable.trace(content);
	appendable.append("test");
	traced.appendUnsafe("insertion");
	assertEquals("insertiontest", appendable.getContent());
}
 
Example #22
Source File: TreeAppendableTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testNoEmptyLeafs() {
	ITextRegionWithLineInformation root = new TextRegionWithLineInformation(47, 11, 12, 137);
	ITextRegionWithLineInformation emptyChild = new TextRegionWithLineInformation(8, 15, 12, 137);
	ITextRegionWithLineInformation emptyGrandChild = new TextRegionWithLineInformation(123, 321, 12, 137);
	expectedRegions = Arrays.asList(root, emptyChild, emptyGrandChild).iterator();
	TreeAppendable appendable = new TreeAppendable(new ImportManager(false), this, this, this, content, "  ", "\n");
	appendable.append("initial");
	appendable.trace(content).trace(content);
	appendable.append("end");
	assertEquals("initialend", appendable.getContent());
	AbstractTraceRegion traceRegion = appendable.getTraceRegion();
	assertTrue(traceRegion.getNestedRegions().isEmpty());
}
 
Example #23
Source File: TreeAppendableTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testLineNumbers() {
	expectedRegions = new AbstractIterator<ITextRegionWithLineInformation>() {
		int start = 0;
		@Override
		protected ITextRegionWithLineInformation computeNext() {
			return new TextRegionWithLineInformation(start++, 1, 1, 1);
		}
	};
	TreeAppendable appendable = new TreeAppendable(new ImportManager(false), this, this, this, content, "  ", "\n");
	appendable.append("start line").increaseIndentation();
	appendable.newLine().trace(content).append("1");
	appendable.trace(content).newLine().append("2");
	appendable.newLine().trace(content).append("3\n4");
	appendable.decreaseIndentation().newLine().append("last line");
	assertEquals(
			"start line\n" +
			"  1\n" +
			"  2\n" +
			"  3\n" +
			"  4\n" +
			"last line", appendable.getContent());
	AbstractTraceRegion rootTraceRegion = appendable.getTraceRegion();
	assertEquals(0, rootTraceRegion.getMyLineNumber());
	assertEquals(5, rootTraceRegion.getMyEndLineNumber());
	AbstractTraceRegion firstChild = rootTraceRegion.getNestedRegions().get(0);
	assertEquals(1, firstChild.getMyLineNumber());
	assertEquals(1, firstChild.getMyEndLineNumber());
	AbstractTraceRegion secondChild = rootTraceRegion.getNestedRegions().get(1);
	assertEquals(2, secondChild.getMyLineNumber());
	assertEquals(2, secondChild.getMyEndLineNumber());
	AbstractTraceRegion thirdChild = rootTraceRegion.getNestedRegions().get(2);
	assertEquals(3, thirdChild.getMyLineNumber());
	assertEquals(4, thirdChild.getMyEndLineNumber());
	expectedRegions = null;
}
 
Example #24
Source File: TreeAppendable.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public TreeAppendable(ImportManager importManager, ITraceURIConverter converter, ILocationInFileProvider locationProvider, IJvmModelAssociations jvmModelAssociations, EObject source,
		String indentation, String lineSeparator) {
	this(
			new SharedAppendableState(indentation, lineSeparator, importManager, source.eResource()),
			converter,
			locationProvider,
			jvmModelAssociations,
			source);
}
 
Example #25
Source File: TreeAppendableTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testEmpty() {
	expectedRegions = Collections.<ITextRegionWithLineInformation>singleton(new TextRegionWithLineInformation(47, 11, 12, 137)).iterator();
	TreeAppendable appendable = new TreeAppendable(new ImportManager(false), this, this, this, content, "  ", "\n");
	assertEquals("", appendable.getContent());
	AbstractTraceRegion traceRegion = appendable.getTraceRegion();
	assertNotNull(traceRegion);
	assertEquals(47, traceRegion.getMergedAssociatedLocation().getOffset());
	assertEquals(11, traceRegion.getMergedAssociatedLocation().getLength());
	assertEquals(getURIForTrace(resource), traceRegion.getAssociatedSrcRelativePath());
	assertTrue(traceRegion.getNestedRegions().isEmpty());
}
 
Example #26
Source File: ImportManagerTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testJavaLangStringFromOtherString() {
	JvmType otherString = typeReferences.findDeclaredType(foo.String.class, expression);
	ImportManager importManager2 = new ImportManager(true, (JvmDeclaredType) otherString);
	JvmType javaLangString = typeReferences.findDeclaredType("java.lang.String", expression);
	assertEquals("java.lang.String", importManager2.serialize(javaLangString).toString());
	assertTrue(importManager2.getImports().isEmpty());
}
 
Example #27
Source File: SharedAppendableState.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public SharedAppendableState(String indentation, String lineSeparator, ImportManager importManager, Resource resource) {
	this.resource = resource;
	this.indentation = indentation;
	this.lineSeparator = lineSeparator;
	this.importManager = importManager;
	this.scopes = new ScopeStack();
	openScope();
}
 
Example #28
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public void addJavaDocImports(final EObject it, final ITreeAppendable appendable, final List<INode> documentationNodes) {
  for (final INode node : documentationNodes) {
    List<ReplaceRegion> _computeTypeRefRegions = this.javaDocTypeReferenceProvider.computeTypeRefRegions(node);
    for (final ReplaceRegion region : _computeTypeRefRegions) {
      {
        final String text = region.getText();
        if (((text != null) && (text.length() > 0))) {
          final QualifiedName fqn = this.qualifiedNameConverter.toQualifiedName(text);
          final EObject context = NodeModelUtils.findActualSemanticObjectFor(node);
          if (((fqn.getSegmentCount() == 1) && (context != null))) {
            final IScope scope = this.scopeProvider.getScope(context, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
            final IEObjectDescription candidate = scope.getSingleElement(fqn);
            if ((candidate != null)) {
              EObject _xifexpression = null;
              boolean _eIsProxy = candidate.getEObjectOrProxy().eIsProxy();
              if (_eIsProxy) {
                _xifexpression = EcoreUtil.resolve(candidate.getEObjectOrProxy(), context);
              } else {
                _xifexpression = candidate.getEObjectOrProxy();
              }
              final JvmType jvmType = ((JvmType) _xifexpression);
              if (((jvmType instanceof JvmDeclaredType) && (!jvmType.eIsProxy()))) {
                final JvmDeclaredType referencedType = ((JvmDeclaredType) jvmType);
                final JvmDeclaredType contextDeclarator = EcoreUtil2.<JvmDeclaredType>getContainerOfType(it, JvmDeclaredType.class);
                String _packageName = referencedType.getPackageName();
                String _packageName_1 = contextDeclarator.getPackageName();
                boolean _notEquals = (!Objects.equal(_packageName, _packageName_1));
                if (_notEquals) {
                  final ImportManager importManager = this.getImportManager(appendable);
                  importManager.addImportFor(jvmType);
                }
              }
            }
          }
        }
      }
    }
  }
}
 
Example #29
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public CharSequence generateType(final JvmDeclaredType type, final GeneratorConfig config) {
  final ImportManager importManager = this.createImportManager(type);
  final TreeAppendable bodyAppendable = this.createAppendable(type, importManager, config);
  bodyAppendable.openScope();
  this.assignThisAndSuper(bodyAppendable, type, config);
  this.generateBody(type, bodyAppendable, config);
  bodyAppendable.closeScope();
  final TreeAppendable importAppendable = this.createAppendable(type, importManager, config);
  this.generateFileHeader(type, importAppendable, config);
  String _packageName = type.getPackageName();
  boolean _tripleNotEquals = (_packageName != null);
  if (_tripleNotEquals) {
    importAppendable.append("package ").append(type.getPackageName()).append(";");
    importAppendable.newLine().newLine();
  }
  List<String> _imports = importManager.getImports();
  for (final String i : _imports) {
    importAppendable.append("import ").append(i).append(";").newLine();
  }
  boolean _isEmpty = importManager.getImports().isEmpty();
  boolean _not = (!_isEmpty);
  if (_not) {
    importAppendable.newLine();
  }
  importAppendable.append(bodyAppendable);
  return importAppendable;
}
 
Example #30
Source File: FakeTreeAppendable.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
public FakeTreeAppendable(ImportManager typeSerializer) {
	super(typeSerializer);
}