/** * This method handles computed-names, for example {@code [System.iterator]} and {@code ["@type"]}. */ @Override public String toValue(String string, INode node) throws ValueConverterException { if (string != null && string.length() > 0 && string.charAt(0) == '[') { // rules arriving here: // (1) N4JSPropertyComputedName // (2) JsPropertyComputedName // (3) TypesComputedPropertyName // argument 'string' matches '[' (SymbolLiteralComputedName | StringLiteralComputedName) ']' String payload = string.substring(1, string.length() - 1).trim(); // payload matches what's enclosed by square brackets (but devoid of whitespace and comments) if (payload.charAt(0) == '"' || payload.charAt(0) == '\'') { String literalWoQuotes = payload.substring(1, payload.length() - 1); return literalWoQuotes; } else { // argument 'string' matches "[<ident-1>.<ident-2>]" // convert it to "#<ident-2>" return SYMBOL_IDENTIFIER_PREFIX + string.substring(string.indexOf('.') + 1, string.length() - 1); } } return super.toValue(string, node); }
@Override public SyntaxErrorMessage getSyntaxErrorMessage( IValueConverterErrorContext context) { ValueConverterException cause = context.getValueConverterException(); if (cause instanceof N4JSStringValueConverter.BadEscapementException) { if (((N4JSStringValueConverter.BadEscapementException) cause).isError()) return new SyntaxErrorMessage(context.getDefaultMessage(), AbstractN4JSStringValueConverter.ERROR_ISSUE_CODE); return new SyntaxErrorMessage(context.getDefaultMessage(), AbstractN4JSStringValueConverter.WARN_ISSUE_CODE); } if (cause instanceof LegacyOctalIntValueConverter.LeadingZerosException) { return new SyntaxErrorMessage(context.getDefaultMessage(), LegacyOctalIntValueConverter.ISSUE_CODE); } if (cause instanceof RegExLiteralConverter.BogusRegExLiteralException) { return new SyntaxErrorMessage(context.getDefaultMessage(), RegExLiteralConverter.ISSUE_CODE); } return super.getSyntaxErrorMessage(context); }
@Override public void set(EObject object, String feature, Object value, String ruleName, INode node) throws ValueConverterException { if (object instanceof AbstractElement && XtextPackage.Literals.ABSTRACT_ELEMENT__CARDINALITY.getName().equals(feature)) { AbstractElement casted = (AbstractElement) object; String knownCardinality = casted.getCardinality(); if (knownCardinality != null) { String newCardinality = String.valueOf(getTokenAsStringIfPossible(value)); if ("*".equals(newCardinality)) { casted.setCardinality("*"); } else if ("*".equals(knownCardinality)) { // nothing to do } else if ("+".equals(knownCardinality)) { if ("?".equals(newCardinality)) { casted.setCardinality("*"); } } else if ("?".equals(knownCardinality)) { if ("+".equals(newCardinality)) { casted.setCardinality("*"); } } throw new MoreThanOneCardinalityException(newCardinality, casted.getCardinality(), node); } } super.set(object, feature, value, ruleName, node); }
@Check public void checkReferencedMetamodel(ReferencedMetamodel metamodel) throws ValueConverterException { if (metamodel.getEPackage() == null) return; String nsURI = metamodel.getEPackage().getNsURI(); List<GeneratedMetamodel> allGeneratedMetamodels = getInheritedGeneratedMetamodels(metamodel); String text = getUsedUri(metamodel); for (GeneratedMetamodel generatedMetamodel : allGeneratedMetamodels) { EPackage generatedPackage = generatedMetamodel.getEPackage(); if (generatedPackage != null && nsURI.equals((generatedPackage.getNsURI()))) { if (!text.equals(nsURI)) { addIssue("Metamodels that have been generated by a super grammar must be referenced by nsURI: " + nsURI, metamodel, XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, INVALID_PACKAGE_REFERENCE_INHERITED, nsURI); return; } return; } } checkExternalPackage(metamodel, text); }
@Override public String toString(String value) { if (value == null) { throw new ValueConverterException("'null' is not a valid qualified name value", null, null); } String valueDelimiter = getValueNamespaceDelimiter(); List<String> segments = valueDelimiter.length() == 1 ? Strings.split(value, valueDelimiter.charAt(0)) : Strings.split(value, valueDelimiter); int size = segments.size(); if (size == 1) { return delegateToString(segments.get(0)); } StringBuilder result = new StringBuilder(value.length()); String delimiterToUse = getStringNamespaceDelimiter(); for (int i = 0; i < size; i++) { if (i != 0) { result.append(delimiterToUse); } if (i == size - 1 && getWildcardLiteral().equals(segments.get(i))) { result.append(getWildcardLiteral()); } else { result.append(delegateToString(segments.get(i))); } } return result.toString(); }
private IValueConverter<Object> initializeDelegateConverter() { if (valueConverterService instanceof IValueConverterService.Introspectable) { return delegateConverter = ((IValueConverterService.Introspectable) valueConverterService).getConverter(getDelegateRuleName()); } else { final String ruleName = getDelegateRuleName(); return delegateConverter = new IValueConverter<Object>() { @Override public Object toValue(String string, INode node) throws ValueConverterException { return valueConverterService.toValue(string, ruleName, node); } @Override public String toString(Object value) throws ValueConverterException { return valueConverterService.toString(value, ruleName); } }; } }
private IValueConverter<Object> getDelegateConverter() { if (delegateConverter != null) { return delegateConverter; } if (delegateService instanceof IValueConverterService.Introspectable) { return delegateConverter = ((IValueConverterService.Introspectable) delegateService).getConverter(delegateRule.getName()); } else { final String ruleName = delegateRule.getName(); return delegateConverter = new IValueConverter<Object>() { @Override public Object toValue(String string, INode node) throws ValueConverterException { return delegateService.toValue(string, ruleName, node); } @Override public String toString(Object value) throws ValueConverterException { return delegateService.toString(value, ruleName); } }; } }
@ValueConverter(rule = "WrappingDataType") public IValueConverter<String> WrappingDataType() { return new AbstractNullSafeConverter<String>() { @Override protected String internalToString(String value) { return value; } @Override protected String internalToValue(String string, INode node) throws ValueConverterException { return node.getText().trim(); } }; }
@ValueConverter(rule = "DatEnum") public IValueConverter<TestEnum> DatEnum() { return new IValueConverter<TestEnum>() { @Override public TestEnum toValue(String string, INode node) throws ValueConverterException { if ("lit3".equals(string)) return TestEnum.LIT3; else throw new ValueConverterException(null, null, null); } @Override public String toString(TestEnum value) throws ValueConverterException { if (value == TestEnum.LIT3) return TestEnum.LIT3.getName(); else throw new ValueConverterException(null, null, null); } }; }
@ValueConverter(rule = "NULL_STRING") public IValueConverter<String> NULL_STRING() { return new IValueConverter<String>() { @Override public String toString(String value) throws ValueConverterException { if (value == null) return "''"; return "'" + value + "'"; } @Override public String toValue(String string, INode node) throws ValueConverterException { if (string.length() <= 2) { return null; } return string.substring(1, string.length() - 1); } }; }
@Override @ValueConverter(rule = "MyId") public IValueConverter<String> ID() { return new IValueConverter<String>() { @Override public String toValue(String string, INode node) throws ValueConverterException { if (string != null && string.length() > 3) { throw new ValueConverterException("ID too long", node, null); } return string; } @Override public String toString(String value) throws ValueConverterException { return value; } }; }
@Override public void validate(final EObject target, final String newName, final RefactoringIssueAcceptor issues) { try { this.getNameAsValue(newName); } catch (final Throwable _t) { if (_t instanceof ValueConverterException) { final ValueConverterException e = (ValueConverterException)_t; StringConcatenation _builder = new StringConcatenation(); _builder.append("Illegal name: "); String _message = e.getMessage(); _builder.append(_message); issues.add(RefactoringIssueAcceptor.Severity.FATAL, _builder.toString()); } else { throw Exceptions.sneakyThrow(_t); } } }
public ICompletionProposal apply(IEObjectDescription candidate) { if (candidate == null) return null; ICompletionProposal result = null; String proposal = qualifiedNameConverter.toString(candidate.getName()); if (ruleName != null) { try { proposal = getValueConverter().toString(proposal, ruleName); } catch (ValueConverterException e) { log.debug(e.getMessage(), e); return null; } } EObject objectOrProxy = candidate.getEObjectOrProxy(); StyledString displayString = getStyledDisplayString(candidate); Image image = getImage(objectOrProxy); result = createCompletionProposal(proposal, displayString, image, contentAssistContext); if (result instanceof ConfigurableCompletionProposal) { ((ConfigurableCompletionProposal) result).setProposalContextResource(contentAssistContext.getResource()); ((ConfigurableCompletionProposal) result).setAdditionalProposalInfo(objectOrProxy); ((ConfigurableCompletionProposal) result).setHover(hover); } getPriorityHelper().adjustCrossReferencePriority(result, contentAssistContext.getPrefix()); return result; }
@Override public RefactoringStatus validateNewName(String newName) { RefactoringStatus status = super.validateNewName(newName); if(nameRuleName != null && valueConverterService != null) { try { String value = getNameAsValue(newName); String text = getNameAsText(value); if(!equal(text, newName)) { status.addError("Illegal name: '" + newName + "'. Consider using '" + text + "' instead."); } } catch(ValueConverterException vce) { status.addFatalError("Illegal name: " + notNull(vce.getMessage())); } } return status; }
@ValueConverter(rule = "NameString") public IValueConverter<String> NameString() { return new AbstractNullSafeConverter<String>() { @Override protected String internalToString(String value) { return String.format("\"%s\"", value); } @Override protected String internalToValue(String string, INode node) throws ValueConverterException { if (string.matches("\\\".*\\\"")) { return string.subSequence(1, string.length() - 1).toString(); } return string; } }; }
@ValueConverter(rule = "FQN") public IValueConverter<String> FQN() { return new AbstractNullSafeConverter<String>() { @Override protected String internalToString(String value) { // this prohibits FQNs with spaces to be serialized if (value.contains(" ")) { throw new ValueConverterException("Spaces are not allowed inside FQNs.", null, null); } return value; } @Override protected String internalToValue(String string, INode node) throws ValueConverterException { return string; } }; }
@ValueConverter(rule = "CardinalityBound") public IValueConverter<Integer> convertCardinalityBound() { return new AbstractNullSafeConverter<Integer>() { @Override protected String internalToString(Integer value) { if (value < 0) { return "*"; } return value.toString(); } @Override protected Integer internalToValue(String string, INode node) throws ValueConverterException { if ("*".equals(string)) { return -1; } return Integer.parseInt(string); } }; }
/** * Returns a value for the given version <code>string</code> stored * in <code>node</code>. * * @param string the version string to be converted * @param node the node holding the string * @return the converted string * @throws ValueConverterException in case of conversion problems */ public String toValue(String string, INode node) { String result; if (string == null) { result = null; } else { boolean found = false; int size = string.length(); for (int i = 0; !found && i < size; i++) { char c = string.charAt(i); found = ('.' == c // from version terminal || '+' == c || '-' == c); // from exponent terminal } if (found) { throw new ValueConverterException("An identifier must not contain a '.'", node, null); } else { result = string; } } return result; }
/** * Returns a value for the given version <code>string</code> stored * in <code>node</code>. * * @param string the version string to be converted * @param node the node holding the string * @return the converted string * @throws ValueConverterException in case of conversion problems */ public String toValue(String string, INode node) { String result; if (string == null) { result = null; } else if (string.length() < 2) { throw new ValueConverterException( "A version must contain at least 2 characters (v1)", node, null); } else { try { // cut the "v" at the beginning result = string.substring(1, string.length()).trim(); } catch (IllegalArgumentException e) { throw new ValueConverterException(e.getMessage(), node, e); } } return result; }
private void checkHexValue (String value, List<INode> children, int indexOfPercent) { ValueConverterException ex = new ValueConverterException("The value '" + value + "' is an invalid " + getRuleName(), null, null); Object obj1 = (children.size()>indexOfPercent+1 ? children.get(indexOfPercent+1) : null); ILeafNode node1AfterPercent = null; if (obj1 instanceof ILeafNode) { node1AfterPercent = (ILeafNode)obj1; } Object obj2 = (children.size()>indexOfPercent+2 ? children.get(indexOfPercent+2) : null); ILeafNode node2AfterPercent = null; if (obj2 instanceof ILeafNode) { node2AfterPercent = (ILeafNode)obj2; } if (node1AfterPercent==null) throw ex; String valueToTest = null; if (node1AfterPercent != null && node2AfterPercent != null) { valueToTest = node1AfterPercent.getText() + (node2AfterPercent!=null ? node2AfterPercent.getText() : ""); } if (valueToTest != null || !valueToTest.matches("(\\d|[a-fA-F]){2}.*")) { throw ex; } }
@Override public String validate(String stringToValidate) throws ValueConverterException { NonMeasurementData data = (NonMeasurementData) node.getSemanticElement(); // if the DataType is Boolean, return either true or false if (data.getDataType().getValue() == DataType.BOOLEAN_VALUE) { if (stringToValidate.toLowerCase().equals(BOOLEAN_TRUE_REPRESENTATION)) { return BOOLEAN_TRUE_REPRESENTATION; } else if (stringToValidate.toLowerCase().equals(BOOLEAN_FALSE_REPRESENTATION)) { return BOOLEAN_FALSE_REPRESENTATION; } else { throw new ValueConverterException(ERROR_MESSAGE, node, null); } } return nextValidationRoutine(stringToValidate); }
@ValueConverter(rule = "DESCRIPTION") public IValueConverter<String> DESCRIPTION() { return new IValueConverter<String>() { @Override public String toValue(String string, INode node) throws ValueConverterException { return toString(string); } @Override public String toString(String value) throws ValueConverterException { return value.substring(3, value.length() - 2); } }; }
@Override public String toValue(final String string, INode node) throws ValueConverterException { int base = DEC_BASE; String stringToConvert; if (!needToBeConverted(node)) { return string; } stringToConvert = removeQuotationMarksFrom(string); ConvertionValidator validatorPipeline = initValidationPipeline(node); stringToConvert = validatorPipeline.validate(stringToConvert); if (NumericalValidator.isHex(stringToConvert)) { base = HEX_BASE; stringToConvert = parseToStringRepresentation(stringToConvert); } return getCorrespondingValue(node, stringToConvert, base); }
@ValueConverter(rule = "SHORT_LONG") public IValueConverter<Integer> SHORT_LONG() { return new IValueConverter<Integer>() { public Integer toValue(String string, INode node) { if (Strings.isEmpty(string)) throw new ValueConverterException("Couldn't convert empty string to int", node, null); else if ("short".equals(string.trim())) return 1; else if ("long".equals(string.trim())) return 5; try { return Integer.parseInt(string); } catch (NumberFormatException e) { throw new ValueConverterException("Couldn't convert '"+string+"' to int", node, e); } } public String toString(Integer value) { return Integer.toString(value); } }; }
@ValueConverter(rule = "ElementBound") public IValueConverter<Integer> ElementBound() { return new IValueConverter<Integer>() { @Override public Integer toValue(String string, INode node) throws ValueConverterException { if (Strings.isEmpty(string)) throw new ValueConverterException("Couldn't convert empty string to int", node, null); else if ("*".equals(string.trim())) return -1; try { return Integer.parseInt(string); } catch (NumberFormatException e) { throw new ValueConverterException("Couldn't convert '"+string+"' to int", node, e); } } @Override public String toString(Integer value) throws ValueConverterException { return ((value == -1) ? "*" : Integer.toString(value)); } }; }
/** * Converts from a Javascript module specifier (the string after "from" in import) to an internal qualified name. */ @Override public String toValue(String string, INode node) throws ValueConverterException { String withDots = IS_CONVERSION_REQUIRED ? string.replace(DELIMITER_MODULE_SPECIFIER, DELIMITER_INTERNAL) : string; return (String) delegateService.toValue(withDots, grammarAccess.getSTRINGRule().getName(), node); }
/** * Converts from an internal qualified name to a Javascript module specifier (the string after "from" in import). */ @Override public String toString(String value) throws ValueConverterException { String withSlashes = IS_CONVERSION_REQUIRED ? value.replace(DELIMITER_INTERNAL, DELIMITER_MODULE_SPECIFIER) : value; return delegateService.toString(withSlashes, grammarAccess.getSTRINGRule().getName()); }
@Override public String toValue(String string, INode node) { if (string == null) return null; try { String result = convertFromJSIdentifier(string, node); return result; } catch (IllegalArgumentException e) { throw new ValueConverterException(e.getMessage(), node, e); } }
@Override protected void assertValidValue(BigDecimal value) { super.assertValidValue(value); if (value.compareTo(BigDecimal.ZERO) == -1) throw new ValueConverterException(getRuleName() + "-value may not be negative (value: " + value + ").", null, null); }
@Override public BigDecimal toValue(String string, INode node) { if (Strings.isEmpty(string)) throw new ValueConverterException("Couldn't convert empty string to an int value.", node, null); try { return new BigDecimal(string); } catch (NumberFormatException e) { throw new ValueConverterException("Couldn't convert '" + string + "' to an int value.", node, e); } }
public BigInteger toValue(String string, INode node) { if (Strings.isEmpty(string)) throw new ValueConverterException("Couldn't convert empty string to number.", node, null); try { return new BigInteger(string.substring(2), 16); } catch (NumberFormatException e) { throw new ValueConverterException("Couldn't convert '" + string + "' to number.", node, null); } }
@Override public String toValue(String string, INode node) throws ValueConverterException { StringBuilder buffer = new StringBuilder(); boolean isFirst = true; if (node != null) { for(INode child: node.getAsTreeIterable()) { EObject grammarElement = child.getGrammarElement(); if (isDelegateRuleCall(grammarElement) || isWildcardLiteral(grammarElement)) { if (!isFirst) buffer.append(getValueNamespaceDelimiter()); isFirst = false; if (isDelegateRuleCall(grammarElement)) for(ILeafNode leafNode :child.getLeafNodes()){ if(!leafNode.isHidden()) buffer.append(delegateToValue(leafNode)); } else buffer.append(getWildcardLiteral()); } } } else { for (String segment : Strings.split(string, getStringNamespaceDelimiter())) { if (!isFirst) buffer.append(getValueNamespaceDelimiter()); isFirst = false; if(getWildcardLiteral().equals(segment)) { buffer.append(getWildcardLiteral()); } else { buffer.append((String) valueConverterService.toValue(segment, getDelegateRuleName(), null)); } } } return buffer.toString(); }
@Override public Integer toValue(String string, INode node) { if (Strings.isEmpty(string)) throw new ValueConverterException("Couldn't convert empty string to an int value.", node, null); String withoutUnderscore = string.replace("_", ""); if (Strings.isEmpty(withoutUnderscore)) throw new ValueConverterException("Couldn't convert input '" + string + "' to an int value.", node, null); return super.toValue(withoutUnderscore, node); }
@Test public void testIntOnlyUnderscores() throws Exception { try { valueConverterService.toValue("___", "INT", null); fail("Expected exception"); } catch(ValueConverterException e) { assertTrue(e.getMessage(), e.getMessage().contains("'___'")); } }
@Test public void testNegative() throws Exception { try { valueConverterService.toString(-42, "INT"); fail("Negative value not detected."); } catch (ValueConverterException e) { assertTrue(e.getMessage(), e.getMessage().contains("may not be negative")); assertTrue(e.getMessage(), e.getMessage().contains("value: -42")); } }
@Test public void testNullString() throws Exception { try { valueConverterService.toValue(null, "INT", null); fail("Null string not detected."); } catch (ValueConverterException e) { assertTrue(e.getMessage(), e.getMessage().contains("empty string")); } }
@Test public void testNullValue() throws Exception { try { valueConverterService.toString(null, "INT"); fail("Null value not detected."); } catch (ValueConverterException e) { assertTrue(e.getMessage(), e.getMessage().contains("may not be null")); } }
@Test public void testLargeInteger() throws Exception { String valueAsString = Integer.toString(Integer.MAX_VALUE) + "42"; try { valueConverterService.toValue(valueAsString, "INT", null); fail("Expected exception"); } catch(ValueConverterException e) { assertTrue(e.getMessage(), e.getMessage().contains(valueAsString)); } }
@Override public SyntaxErrorMessage getSyntaxErrorMessage(IValueConverterErrorContext context) { ValueConverterException cause = context.getValueConverterException(); if (cause instanceof MoreThanOneCardinalityException) { return new SyntaxErrorMessage(context.getDefaultMessage(), CARDINALITY_ISSUE); } return super.getSyntaxErrorMessage(context); }
@ValueConverter(rule = "LiteralValue") public IValueConverter<Boolean> LiteralValue() { return new AbstractNullSafeConverter<Boolean>() { @Override protected Boolean internalToValue(String string, INode node) throws ValueConverterException { return "+".equals(string); } @Override protected String internalToString(Boolean value) { return value.booleanValue() ? "+" : "!"; } }; }