org.eclipse.xtext.xbase.compiler.output.ITreeAppendable Java Examples

The following examples show how to use org.eclipse.xtext.xbase.compiler.output.ITreeAppendable. 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: CheckCompiler.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
// CHECKSTYLE:OFF
protected void _toJavaExpression(final XAbstractFeatureCall expr, final ITreeAppendable b) {
  // CHECKSTYLE:ON
  FormalParameter parameter = getFormalParameter(expr);
  if (parameter != null) {
    // No Java entities are generated for this. Replace by a call to the getter function.
    b.append(generatorNaming.catalogInstanceName(parameter)).append(".").append(generatorNaming.formalParameterGetterName(parameter));
    b.append("(").append(getContextImplicitVariableName(expr)).append(")");
  } else {
    Member member = getMember(expr);
    if (member != null) {
      // Something isn't quite right in the Jvm model yet... or in the xbase compiler. Don't know what it is, but even if in an inner
      // class, it generates "this.foo" instead of either just "foo" or "OuterClass.this.foo". Force it to produce the latter.
      CheckCatalog catalog = EcoreUtil2.getContainerOfType(member, CheckCatalog.class);
      String catalogName = generatorNaming.validatorClassName(catalog);
      b.append(catalogName + ".this.").append(member.getName());
      return;
    }
    super._toJavaExpression(expr, b);
  }
}
 
Example #2
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected ITreeAppendable _generateMember(final JvmConstructor it, final ITreeAppendable appendable, final GeneratorConfig config) {
  ITreeAppendable _xblockexpression = null;
  {
    appendable.newLine();
    appendable.openScope();
    this.generateJavaDoc(it, appendable, config);
    final ITreeAppendable tracedAppendable = appendable.trace(it);
    this.generateAnnotations(it.getAnnotations(), tracedAppendable, true, config);
    this.generateModifier(it, tracedAppendable, config);
    this.generateTypeParameterDeclaration(it, tracedAppendable, config);
    this._treeAppendableUtil.traceSignificant(tracedAppendable, it).append(this.makeJavaIdentifier(it.getSimpleName()));
    tracedAppendable.append("(");
    this.generateParameters(it, tracedAppendable, config);
    tracedAppendable.append(")");
    this.generateThrowsClause(it, tracedAppendable, config);
    tracedAppendable.append(" ");
    this.generateExecutableBody(it, tracedAppendable, config);
    appendable.closeScope();
    _xblockexpression = appendable;
  }
  return _xblockexpression;
}
 
Example #3
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void _toJavaStatement(final XConstructorCall expr, ITreeAppendable b, final boolean isReferenced) {
	for (XExpression arg : expr.getArguments()) {
		prepareExpression(arg, b);
	}
	
	if (!isReferenced) {
		b.newLine();
		constructorCallToJavaExpression(expr, b);
		b.append(";");
	} else if (isVariableDeclarationRequired(expr, b, true)) {
		Later later = new Later() {
			@Override
			public void exec(ITreeAppendable appendable) {
				constructorCallToJavaExpression(expr, appendable);
			}
		};
		declareFreshLocalVariable(expr, b, later);
	}
}
 
Example #4
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected ITreeAppendable _generateModifier(final JvmField it, final ITreeAppendable appendable, final GeneratorConfig config) {
  ITreeAppendable _xblockexpression = null;
  {
    this.generateVisibilityModifier(it, appendable);
    boolean _isStatic = it.isStatic();
    if (_isStatic) {
      appendable.append("static ");
    }
    boolean _isFinal = it.isFinal();
    if (_isFinal) {
      appendable.append("final ");
    }
    boolean _isTransient = it.isTransient();
    if (_isTransient) {
      appendable.append("transient ");
    }
    ITreeAppendable _xifexpression = null;
    boolean _isVolatile = it.isVolatile();
    if (_isVolatile) {
      _xifexpression = appendable.append("volatile ");
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example #5
Source File: XtendCompiler.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Symmetric to {@link XtendGenerator#reassignThisType(ITreeAppendable, JvmDeclaredType)}
 */
@Override
protected void doReassignThisInClosure(ITreeAppendable b, JvmType prevType) {
	if (prevType instanceof JvmDeclaredType && ((JvmDeclaredType) prevType).isLocal()) {
		if (b.hasName(Pair.of("this", prevType))) {
			b.declareVariable(prevType, b.getName(Pair.of("this", prevType)));
		} else {
			b.declareSyntheticVariable(prevType, "");
		}
		if (b.hasObject("super")) {
			Object superElement = b.getObject("super");
			if (superElement instanceof JvmType) {
				// Don't reassign the super of the enclosing type if it has already been reassigned
				String superVariable = b.getName(superElement);
				if ("super".equals(superVariable)) {
					b.declareSyntheticVariable(superElement, prevType.getSimpleName()+".super");
				}
			}
		}
	} else {
		super.doReassignThisInClosure(b, prevType);
	}
}
 
Example #6
Source File: TypeConvertingCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
private void convertMultiType(LightweightTypeReference expectation, CompoundTypeReference multiType, XExpression context,
		ITreeAppendable b, Later expression) {
	LightweightTypeReference castTo = null;
	List<LightweightTypeReference> components = multiType.getMultiTypeComponents();
	ITypeReferenceOwner owner = multiType.getOwner();
	LightweightTypeReference commonType = owner.getServices().getTypeConformanceComputer().getCommonSuperType(components, owner);
	if (!isJavaConformant(expectation, commonType)) {
		for(LightweightTypeReference candidate: multiType.getMultiTypeComponents()) {
			if (isJavaConformant(expectation, candidate)) {
				castTo = candidate;
				break;
			}
		}
	}
	if (castTo != null && mustInsertTypeCast(context, castTo)) {
		b.append("((");
		b.append(castTo);
		b.append(")");
		expression.exec(b);
		b.append(")");
	} else {
		expression.exec(b);
	}
}
 
Example #7
Source File: SarlCompiler.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public void doInternalToJavaStatement(XExpression obj, ITreeAppendable appendable, boolean isReferenced) {
	// Overridden for enabling the expressions that are specific to SARL
	if (obj instanceof SarlBreakExpression) {
		_toJavaStatement((SarlBreakExpression) obj, appendable, isReferenced);
	} else if (obj instanceof SarlContinueExpression) {
		_toJavaStatement((SarlContinueExpression) obj, appendable, isReferenced);
	} else if (obj instanceof SarlAssertExpression) {
		_toJavaStatement((SarlAssertExpression) obj, appendable, isReferenced);
	} else {
		try {
			super.doInternalToJavaStatement(obj, appendable, isReferenced);
		} catch (IllegalStateException exception) {
			// Log the exception but do not fail the generation.
			logInternalError(exception);
		}
	}
}
 
Example #8
Source File: LiteralsCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void doInternalToJavaStatement(XExpression obj, ITreeAppendable appendable, boolean isReferenced) {
	if (obj instanceof XStringLiteral) {
		_toJavaStatement((XStringLiteral) obj, appendable, isReferenced);
	} else if (obj instanceof XNumberLiteral) {
		_toJavaStatement((XNumberLiteral) obj, appendable, isReferenced);
	} else if (obj instanceof XNullLiteral) {
		_toJavaStatement((XNullLiteral) obj, appendable, isReferenced);
	} else if (obj instanceof XBooleanLiteral) {
		_toJavaStatement((XBooleanLiteral) obj, appendable, isReferenced);
	} else if (obj instanceof XTypeLiteral) {
		_toJavaStatement((XTypeLiteral) obj, appendable, isReferenced);
	} else {
		super.doInternalToJavaStatement(obj, appendable, isReferenced);
	}
}
 
Example #9
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public void toJava(final JvmAnnotationValue it, final ITreeAppendable appendable, final GeneratorConfig config) {
  JvmOperation _operation = it.getOperation();
  boolean _tripleNotEquals = (_operation != null);
  if (_tripleNotEquals) {
    String _simpleName = it.getOperation().getSimpleName();
    boolean _tripleEquals = (_simpleName == null);
    if (_tripleEquals) {
      return;
    }
    appendable.append(it.getOperation().getSimpleName());
    appendable.append(" = ");
  } else {
    EObject _eContainer = it.eContainer();
    int _size = ((JvmAnnotationReference) _eContainer).getExplicitValues().size();
    boolean _greaterThan = (_size > 1);
    if (_greaterThan) {
      appendable.append("value = ");
    }
  }
  this.toJavaLiteral(it, appendable, config);
}
 
Example #10
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param isReferenced unused in this context but necessary for dispatch signature  
 */
protected void _toJavaStatement(XDoWhileExpression expr, ITreeAppendable b, boolean isReferenced) {
	boolean needsStatement = !canCompileToJavaExpression(expr.getPredicate(), b);
	String variable = null;
	if (needsStatement) {
		variable = b.declareSyntheticVariable(expr, "_dowhile");
		b.newLine().append("boolean ").append(variable).append(" = false;");
	}
	b.newLine().append("do {").increaseIndentation();
	internalToJavaStatement(expr.getBody(), b, false);
	if (needsStatement && !isEarlyExit(expr.getBody())) {
		internalToJavaStatement(expr.getPredicate(), b, true);
		b.newLine();
		b.append(variable).append(" = ");
		internalToJavaExpression(expr.getPredicate(), b);
		b.append(";");
	}
	b.decreaseIndentation().newLine().append("} while(");
	if (needsStatement) {
		b.append(variable);
	} else {
		internalToJavaExpression(expr.getPredicate(), b);
	}
	b.append(");");
}
 
Example #11
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected String declareLocalVariable(XSwitchExpression expr, ITreeAppendable b) {
	// declare local var for the switch expression
	String variableName = getSwitchLocalVariableName(expr, b); 
	if (variableName != null) {
		return variableName;
	}
	String name = createSwitchLocalVariableName(expr);
	JvmTypeReference variableType = getSwitchLocalVariableType(expr);
	b.newLine().append("final ");
	serialize(variableType, expr, b);
	b.append(" ");
	variableName = declareAndAppendSwitchSyntheticLocalVariable(expr, name, b);
	b.append(" = ");
	internalToJavaExpression(expr.getSwitch(), b);
	b.append(";");
	return variableName;
}
 
Example #12
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void _toJavaExpression(XSetLiteral literal, ITreeAppendable b) {
	LightweightTypeReference literalType = batchTypeResolver.resolveTypes(literal).getActualType(literal);
	if (literalType == null) {
		b.append("error - couldn't compute type for literal : "+literal);
		return;
	} 
	if (literalType.isType(Map.class)) {
		LightweightTypeReference keyType = literalType.getTypeArguments().get(0);
		LightweightTypeReference valueType = literalType.getTypeArguments().get(1);
		b.append(Collections.class)
			.append(".<").append(keyType).append(", ").append(valueType)
			.append(">unmodifiableMap(");
		b.append(CollectionLiterals.class).append(".<").append(keyType).append(", ").append(valueType).append(">newHashMap(");
		Iterator<XExpression> elements = literal.getElements().iterator();
		while(elements.hasNext())  {
			XExpression element = elements.next();
			internalToJavaExpression(element, b);
			if (elements.hasNext()) {
				b.append(", ");
			}
		}
		b.append("))");
	} else {
		appendImmutableCollectionExpression(literal, b, "unmodifiableSet", CollectionLiterals.class, "newHashSet");
	}
}
 
Example #13
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected String declareSwitchResultVariable(XSwitchExpression expr, ITreeAppendable b, boolean isReferenced) {
	LightweightTypeReference type = getTypeForVariableDeclaration(expr);
	String switchResultName = b.declareSyntheticVariable(getSwitchExpressionKey(expr), "_switchResult");
	if (isReferenced) {
		b.newLine();
		b.append(type);
		b.append(" ").append(switchResultName).append(" = ");
		b.append(getDefaultValueLiteral(expr));
		b.append(";");
	}
	return switchResultName;
}
 
Example #14
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public ITreeAppendable generateBody(final JvmDeclaredType it, final ITreeAppendable appendable, final GeneratorConfig config) {
  if (it instanceof JvmAnnotationType) {
    return _generateBody((JvmAnnotationType)it, appendable, config);
  } else if (it instanceof JvmEnumerationType) {
    return _generateBody((JvmEnumerationType)it, appendable, config);
  } else if (it instanceof JvmGenericType) {
    return _generateBody((JvmGenericType)it, appendable, config);
  } else {
    throw new IllegalArgumentException("Unhandled parameter types: " +
      Arrays.<Object>asList(it, appendable, config).toString());
  }
}
 
Example #15
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected ITreeAppendable _generateModifier(final JvmOperation it, final ITreeAppendable appendable, final GeneratorConfig config) {
  ITreeAppendable _xblockexpression = null;
  {
    this.generateVisibilityModifier(it, appendable);
    if ((it.isAbstract() && (!this.isDeclaredWithinInterface(it)))) {
      appendable.append("abstract ");
    }
    boolean _isStatic = it.isStatic();
    if (_isStatic) {
      appendable.append("static ");
    }
    if (((((!it.isAbstract()) && (!it.isStatic())) && config.getJavaSourceVersion().isAtLeast(JavaVersion.JAVA8)) && this.isDeclaredWithinInterface(it))) {
      appendable.append("default ");
    }
    boolean _isFinal = it.isFinal();
    if (_isFinal) {
      appendable.append("final ");
    }
    boolean _isSynchronized = it.isSynchronized();
    if (_isSynchronized) {
      appendable.append("synchronized ");
    }
    boolean _isStrictFloatingPoint = it.isStrictFloatingPoint();
    if (_isStrictFloatingPoint) {
      appendable.append("strictfp ");
    }
    ITreeAppendable _xifexpression = null;
    boolean _isNative = it.isNative();
    if (_isNative) {
      _xifexpression = appendable.append("native ");
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example #16
Source File: FeatureCallCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean appendReceiver(XAbstractFeatureCall call, ITreeAppendable b, @SuppressWarnings("unused") boolean isExpressionContext) {
	if (call.isStatic()) {
		if (expressionHelper.findInlineAnnotation(call) != null) {
			return false;
		}
		if (call instanceof XMemberFeatureCall) {
			XMemberFeatureCall memberFeatureCall = (XMemberFeatureCall) call;
			if (memberFeatureCall.isStaticWithDeclaringType()) {
				XAbstractFeatureCall target = (XAbstractFeatureCall) memberFeatureCall.getMemberCallTarget();
				JvmType declaringType = (JvmType) target.getFeature();
				b.trace(target, false).append(declaringType);
				return true;
			}
		}
		b.append(((JvmFeature) call.getFeature()).getDeclaringType());
		return true;
	}
	XExpression receiver = getActualReceiver(call);
	if (receiver != null) {
		internalToJavaExpression(receiver, b);
		if (receiver instanceof XAbstractFeatureCall) {
			// some local types have a reference name bound to the empty string
			// which is the reason why we have to check for an empty string as a valid
			// reference name here
			// see AnonymousClassCompilerTest.testCapturedLocalVar_04
			// if it turns out that we have to deal with generics there too, we may
			// have to create a field in the synthesized local class with a unique
			// name that points to 'this'
			if (((XAbstractFeatureCall) receiver).getFeature() instanceof JvmType) {
				String referenceName = getReferenceName(receiver, b);
				if (referenceName != null && referenceName.length() == 0) {
					return false;
				}
			}
		}
		return true;
	} else {
		return false;
	}
}
 
Example #17
Source File: CheckCompiler.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
// CHECKSTYLE:OFF
protected void _toJavaStatement(final XAbstractFeatureCall expr, final ITreeAppendable b, final boolean isReferenced) {
  // CHECKSTYLE:ON
  FormalParameter parameter = getFormalParameter(expr);
  if (parameter != null) {
    // Nothing to do.
  } else {
    super._toJavaStatement(expr, b, isReferenced);
  }
}
 
Example #18
Source File: XtendGenerator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ITreeAppendable generateVisibilityModifier(final JvmMember it, final ITreeAppendable result) {
  ITreeAppendable _xblockexpression = null;
  {
    JvmVisibility _visibility = it.getVisibility();
    boolean _equals = Objects.equal(_visibility, JvmVisibility.PRIVATE);
    if (_equals) {
      JvmDeclaredType _declaringType = it.getDeclaringType();
      boolean _tripleEquals = (_declaringType == null);
      if (_tripleEquals) {
        return result;
      }
      if ((it.getDeclaringType().isLocal() && (it instanceof JvmOperation))) {
        JvmDeclaredType _declaringType_1 = it.getDeclaringType();
        final JvmGenericType declarator = ((JvmGenericType) _declaringType_1);
        boolean _isAnonymous = declarator.isAnonymous();
        boolean _not = (!_isAnonymous);
        if (_not) {
          return result;
        }
      }
    } else {
      JvmVisibility _visibility_1 = it.getVisibility();
      boolean _equals_1 = Objects.equal(_visibility_1, JvmVisibility.PUBLIC);
      if (_equals_1) {
        if (((it.getDeclaringType() instanceof JvmGenericType) && ((JvmGenericType) it.getDeclaringType()).isInterface())) {
          return result;
        }
      }
    }
    _xblockexpression = super.generateVisibilityModifier(it, result);
  }
  return _xblockexpression;
}
 
Example #19
Source File: TypeConvertingCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/** Convert a wrapper expression (number, char, boolean) to its primitive equivalent.
 *
 * @param wrapper unused in this context but useful for inheritors.
 * @param primitive the primitive type to convert to.
 * @param context the context of the convertion, i.e. the containing expression.
 * @param appendable the receiver of the convertion.
 * @param expression the expression to convert.
 */
protected void convertWrapperToPrimitive(
		final LightweightTypeReference wrapper, 
		final LightweightTypeReference primitive, 
		XExpression context, 
		final ITreeAppendable appendable,
		final Later expression) {
	XExpression normalized = normalizeBlockExpression(context);
	if (normalized instanceof XAbstractFeatureCall && !(context.eContainer() instanceof XAbstractFeatureCall)) {
		// Avoid javac bug
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=410797
		// TODO make that dependent on the compiler version (javac 1.7 fixed that bug)
		XAbstractFeatureCall featureCall = (XAbstractFeatureCall) normalized;
		if (featureCall.isStatic()) {
			JvmIdentifiableElement feature = featureCall.getFeature();
			if (feature instanceof JvmOperation) {
				if (!((JvmOperation) feature).getTypeParameters().isEmpty()) {
					appendable.append("(");
					appendable.append(primitive);
					appendable.append(") ");
					expression.exec(appendable);
					return;
				}
			}
		}
	}
	appendable.append("(");
	if (mustInsertTypeCast(context, wrapper)) {
		appendable.append("(");
		appendable.append(wrapper);
		appendable.append(") ");
	} 
	expression.exec(appendable);
	appendable.append(")");
	appendable.append(".");
	appendable.append(primitive);
	appendable.append("Value()");
}
 
Example #20
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 #21
Source File: TraceableTreeAppendable.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public ITreeAppendable append(CharSequence string) {
	final TraceableTreeAppendable p = getParent();
	if (p != null) {
		p.append(string);
	} else {
		super.append(string);
	}
	return this;
}
 
Example #22
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void _toJavaExpression(XBlockExpression expr, ITreeAppendable b) {
	if (expr.getExpressions().isEmpty()) {
		b.append("null");
		return;
	}
	if (expr.getExpressions().size()==1) {
		// conversion was already performed for single expression blocks
		internalToConvertedExpression(expr.getExpressions().get(0), b, null);
		return;
	}
	b = b.trace(expr, false);
	b.append(getVarName(expr, b));
}
 
Example #23
Source File: AbstractXbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void appendDefaultLiteral(ITreeAppendable b, /* @Nullable */ LightweightTypeReference type) {
	if (type != null && type.isPrimitive()) {
		Primitive primitiveKind = type.getPrimitiveKind();
		switch (primitiveKind) {
			case Boolean:
				b.append("false");
				break;
			default:
				b.append("0");
				break;
		}
	} else {
		b.append("null");
	}
}
 
Example #24
Source File: LiteralsCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
protected void toJavaStatement(final XStringLiteral expr, ITreeAppendable b, boolean isReferenced, final boolean useUnicodeEscapes) {
	generateComment(new Later() {
		@Override
		public void exec(ITreeAppendable appendable) {
			// we have to escape closing comments in string literals
			String escapedClosingComments = expr.getValue().replace("*/", "* /");
			String javaString = Strings.convertToJavaString(escapedClosingComments, useUnicodeEscapes);
			appendable.append("\"").append(javaString).append("\"");
		}
	}, b, isReferenced);
}
 
Example #25
Source File: LiteralsCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void generateComment(final XExpression expr, ITreeAppendable b, boolean isReferenced) {
	generateComment(new Later() {
		@Override
		public void exec(ITreeAppendable appendable) {
			internalToJavaExpression(expr, appendable);
		}
	}, b, isReferenced);
}
 
Example #26
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected ITreeAppendable generateDocumentation(final String text, final List<INode> documentationNodes, final ITreeAppendable appendable, final GeneratorConfig config) {
  ITreeAppendable _xblockexpression = null;
  {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("/**");
    final StringConcatenation doc = ((StringConcatenation) _builder);
    doc.newLine();
    doc.append(" * ");
    doc.append(text, " * ");
    doc.newLine();
    doc.append(" */");
    ITreeAppendable _xifexpression = null;
    boolean _isEmpty = documentationNodes.isEmpty();
    boolean _not = (!_isEmpty);
    if (_not) {
      ITreeAppendable _xblockexpression_1 = null;
      {
        ITextRegionWithLineInformation documentationTrace = ITextRegionWithLineInformation.EMPTY_REGION;
        for (final INode node : documentationNodes) {
          documentationTrace = documentationTrace.merge(node.getTextRegionWithLineInformation());
        }
        LocationData _locationData = new LocationData(documentationTrace, null);
        appendable.trace(_locationData).append(doc.toString());
        _xblockexpression_1 = appendable.newLine();
      }
      _xifexpression = _xblockexpression_1;
    } else {
      _xifexpression = appendable.append(doc.toString()).newLine();
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example #27
Source File: TraceableTreeAppendable.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public ITreeAppendable increaseIndentation() {
	final TraceableTreeAppendable p = getParent();
	if (p != null) {
		p.increaseIndentation();
	} else {
		super.increaseIndentation();
	}
	return this;
}
 
Example #28
Source File: AbstractXbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public ITreeAppendable compile(XExpression obj, ITreeAppendable parentAppendable, /* @Nullable */ LightweightTypeReference expectedReturnType, /* @Nullable */ Set<JvmTypeReference> declaredExceptions) {
	if (declaredExceptions == null) {
		declaredExceptions = newHashSet();
		assert declaredExceptions != null;
	}
	ITreeAppendable appendable = parentAppendable.trace(obj, true);
	final boolean isPrimitiveVoidExpected = expectedReturnType.isPrimitiveVoid(); 
	final boolean isPrimitiveVoid = isPrimitiveVoid(obj);
	final boolean earlyExit = isEarlyExit(obj);
	boolean needsSneakyThrow = needsSneakyThrow(obj, declaredExceptions);
	if (needsSneakyThrow && isPrimitiveVoidExpected && hasJvmConstructorCall(obj)) {
		compileWithJvmConstructorCall((XBlockExpression) obj, appendable);
		return parentAppendable;
	}
	if (needsSneakyThrow) {
		appendable.newLine().append("try {").increaseIndentation();
	}
	internalToJavaStatement(obj, appendable, !isPrimitiveVoidExpected && !isPrimitiveVoid && !earlyExit);
	if (!isPrimitiveVoidExpected && !earlyExit) {
		appendable.newLine().append("return ");
		if (isPrimitiveVoid && !isPrimitiveVoidExpected) {
			appendDefaultLiteral(appendable, expectedReturnType);
		} else {
			internalToConvertedExpression(obj, appendable, expectedReturnType);
		}
		appendable.append(";");
	}
	if (needsSneakyThrow) {
		generateCheckedExceptionHandling(appendable);
	}
	return parentAppendable;
}
 
Example #29
Source File: DynamicValidationContext.java    From sarl with Apache License 2.0 5 votes vote down vote up
private static void appendSafeTitleAnchorExistenceTest(ITreeAppendable receiver, File fileInResource, String anchor) {
	receiver.newLine();
	receiver.append("{").increaseIndentation().newLine(); //$NON-NLS-1$
	receiver.append("// ").append(FileSystem.extension(fileInResource)).append(": "); //$NON-NLS-1$ //$NON-NLS-2$
	receiver.append(fileInResource.getName()).newLine();
	receiver.append(File.class).append(" theFile = new ").append(File.class).append("(\""); //$NON-NLS-1$ //$NON-NLS-2$
	receiver.append(Strings.convertToJavaString(fileInResource.toString())).append("\");"); //$NON-NLS-1$
	receiver.newLine().append("if (theFile.exists()) {"); //$NON-NLS-1$
	receiver.increaseIndentation().newLine();
	receiver.append("String content = ").append(Strings.class); //$NON-NLS-1$
	receiver.append(".concat(\"\\n\", ").append(Files.class); //$NON-NLS-1$
	receiver.append(".readLines(theFile, "); //$NON-NLS-1$
	receiver.append(Charset.class).append(".defaultCharset()));").newLine(); //$NON-NLS-1$
	receiver.append(Matcher.class).append(" matcher = sectionPattern.matcher(content);").newLine(); //$NON-NLS-1$
	receiver.append("while (matcher.find()) {").increaseIndentation().newLine(); //$NON-NLS-1$
	receiver.append("String title = matcher.group(1);").newLine(); //$NON-NLS-1$
	receiver.append("String key1 = computeHeaderIdWithSectionNumber(title);").newLine(); //$NON-NLS-1$
	receiver.append("String key2 = computeHeaderIdWithoutSectionNumber(title);").newLine(); //$NON-NLS-1$
	receiver.append("if (\"").append(Strings.convertToJavaString(anchor)).append("\".equals(key1) || \""); //$NON-NLS-1$ //$NON-NLS-2$
	receiver.append(Strings.convertToJavaString(anchor)).append("\".equals(key2)) {"); //$NON-NLS-1$
	receiver.increaseIndentation().newLine().append("return;").decreaseIndentation().newLine(); //$NON-NLS-1$
	receiver.append("}").decreaseIndentation().newLine(); //$NON-NLS-1$
	receiver.append("}").newLine().append(Assertions.class).append(".fail(\""); //$NON-NLS-1$ //$NON-NLS-2$
	receiver.append(Strings.convertToJavaString(MessageFormat.format(Messages.DynamicValidationContext_0,
			anchor, fileInResource.getName())));
	receiver.append("\");").newLine(); //$NON-NLS-1$
	receiver.append("return;"); //$NON-NLS-1$
	receiver.decreaseIndentation().newLine();
	receiver.append("}").decreaseIndentation().newLine().append("}"); //$NON-NLS-1$ //$NON-NLS-2$
}
 
Example #30
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void _toJavaStatement(XBlockExpression expr, ITreeAppendable b, boolean isReferenced) {
	b = b.trace(expr, false);
	if (expr.getExpressions().isEmpty())
		return;
	if (expr.getExpressions().size()==1) {
		internalToJavaStatement(expr.getExpressions().get(0), b, isReferenced);
		return;
	}
	if (isReferenced)
		declareSyntheticVariable(expr, b);
	boolean needsBraces = isReferenced || !bracesAreAddedByOuterStructure(expr);
	if (needsBraces) {
		b.newLine().append("{").increaseIndentation();
		b.openPseudoScope();
	}
	final EList<XExpression> expressions = expr.getExpressions();
	for (int i = 0; i < expressions.size(); i++) {
		XExpression ex = expressions.get(i);
		if (i < expressions.size() - 1) {
			internalToJavaStatement(ex, b, false);
		} else {
			internalToJavaStatement(ex, b, isReferenced);
			if (isReferenced) {
				b.newLine().append(getVarName(expr, b)).append(" = ");
				internalToConvertedExpression(ex, b, getLightweightType(expr));
				b.append(";");
			}
		}
	}
	if (needsBraces) {
		b.closeScope();
		b.decreaseIndentation().newLine().append("}");
	}
}