Add basic constraint validation capabilities to overwrite annotations

This commit is contained in:
Mumfrey committed 2015-05-28 18:53:40 +01:00
1 parent b46bfe5da6
commit 7434e54b60
9 files changed
+734 -12

No files matched your search

@@ -71,6 +71,7 @@ public abstract class MixinBootstrap {
// Consts
private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch.";
private static final String MIXIN_PACKAGE = "org.spongepowered.asm.mixin.";
private static final String MIXIN_UTIL_PACKAGE = "org.spongepowered.asm.util.";
private static final String ASM_PACKAGE = "org.spongepowered.asm.lib.";
private static final String TRANSFORMER_PROXY_CLASS = MixinBootstrap.MIXIN_PACKAGE + "transformer.MixinTransformer$Proxy";
@@ -88,6 +89,7 @@ public abstract class MixinBootstrap {
// The important ones
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.ASM_PACKAGE);
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.MIXIN_PACKAGE);
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.MIXIN_UTIL_PACKAGE);
// Only needed in dev, in production this would be handled by the tweaker
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.LAUNCH_PACKAGE);
@@ -28,14 +28,18 @@ import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.helpers.Booleans;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
import org.spongepowered.asm.util.PrettyPrinter;
@@ -304,6 +308,47 @@ public class MixinEnvironment {
}
/**
* Wrapper for providing a natural sorting order for providers
*/
static class TokenProviderWrapper implements Comparable<TokenProviderWrapper> {
private static int nextOrder = 0;
private final int priority, order;
private final IEnvironmentTokenProvider provider;
private final MixinEnvironment environment;
public TokenProviderWrapper(IEnvironmentTokenProvider provider, MixinEnvironment environment) {
this.provider = provider;
this.environment = environment;
this.order = TokenProviderWrapper.nextOrder++;
this.priority = provider.getPriority();
}
@Override
public int compareTo(TokenProviderWrapper other) {
if (other == null) {
return 0;
}
if (other.priority == this.priority) {
return other.order - this.order;
}
return (other.priority - this.priority);
}
public IEnvironmentTokenProvider getProvider() {
return this.provider;
}
Integer getToken(String token) {
return this.provider.getToken(token, this.environment);
}
}
/**
* Known re-entrant transformers, other re-entrant transformers will
* detected automatically
@@ -318,6 +363,16 @@ public class MixinEnvironment {
// Blackboard keys
private static final String CONFIGS_KEY = "mixin.configs";
private static final String TRANSFORMER_KEY = "mixin.transformer";
/**
* Array of all (real) environments, indexed by ordinal
*/
private static final MixinEnvironment[] environments = new MixinEnvironment[Phase.phases.size()];
/**
* Currently active environment
*/
private static MixinEnvironment currentEnvironment;
/**
* Current (active) environment phase, set to NOT_INITIALISED until the
@@ -325,16 +380,6 @@ public class MixinEnvironment {
*/
private static Phase currentPhase = Phase.NOT_INITIALISED;
/**
* Array of all (real) environments, indexed by ordinal
*/
private static MixinEnvironment[] environments = new MixinEnvironment[Phase.phases.size()];
/**
* Currently active environment
*/
private static MixinEnvironment currentEnvironment;
/**
* Show debug header info on first environment construction
*/
@@ -364,6 +409,21 @@ public class MixinEnvironment {
* Error handlers for environment
*/
private final Set<String> errorHandlers = new LinkedHashSet<String>();
/**
* List of token provider classes
*/
private final Set<String> tokenProviderClasses = new HashSet<String>();
/**
* List of token providers in this environment
*/
private final List<TokenProviderWrapper> tokenProviders = new ArrayList<TokenProviderWrapper>();
/**
* Internal tokens defined by this environment
*/
private final Map<String, Integer> internalTokens = new HashMap<String, Integer>();
/**
* Detected side
@@ -404,7 +464,7 @@ public class MixinEnvironment {
}
if (MixinEnvironment.showHeader) {
showHeader = false;
MixinEnvironment.showHeader = false;
Side side = this.getSide();
String codeSource = this.getCodeSource();
@@ -481,6 +541,66 @@ public class MixinEnvironment {
return this;
}
/**
* Add a new token provider class to this environment
*
* @param providerName Class name of the token provider to add
* @return fluent interface
*/
public MixinEnvironment registerTokenProviderClass(String providerName) {
if (!this.tokenProviderClasses.contains(providerName)) {
try {
@SuppressWarnings("unchecked")
Class<? extends IEnvironmentTokenProvider> providerClass =
(Class<? extends IEnvironmentTokenProvider>)Class.forName(providerName, true, Launch.classLoader);
IEnvironmentTokenProvider provider = providerClass.newInstance();
this.registerTokenProvider(provider);
} catch (Throwable th) {
this.logger.error("Error instantiating " + providerName, th);
}
}
return this;
}
/**
* Add a new token provider to this environment
*
* @param provider Token provider to add
* @return fluent interface
*/
public MixinEnvironment registerTokenProvider(IEnvironmentTokenProvider provider) {
if (provider != null && !this.tokenProviderClasses.contains(provider.getClass().getName())) {
String providerName = provider.getClass().getName();
TokenProviderWrapper wrapper = new TokenProviderWrapper(provider, this);
this.logger.info("Adding new token provider {} to {}", providerName, this);
this.tokenProviders.add(wrapper);
this.tokenProviderClasses.add(providerName);
Collections.sort(this.tokenProviders);
}
return this;
}
/**
* Get a token value from this environment
*
* @param token Token to fetch
* @return token value or null if the token is not present in the
* environment
*/
public Integer getToken(String token) {
token = token.toUpperCase();
for (TokenProviderWrapper provider : this.tokenProviders) {
Integer value = provider.getToken(token);
if (value != null) {
return value;
}
}
return this.internalTokens.get(token);
}
/**
* Get all registered error handlers for this environment
*
@@ -29,6 +29,8 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* <p>Annotation used to indicate a mixin class member which must overwrite an
* obfuscated method in the target class.</p>
@@ -54,6 +56,14 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
public @interface Overwrite {
/**
* Returns constraints which must be validated for this overwrite to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
/**
* Supplies possible aliases for this method. This should <b>only</b>
* be used in the following scenarios:
@@ -0,0 +1,57 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.extensibility;
import org.spongepowered.asm.mixin.MixinEnvironment;
/**
* Provides a token value into the attached environment
*/
public interface IEnvironmentTokenProvider {
/**
* Default token provider priority
*/
public static final int DEFAULT_PRIORITY = 1000;
/**
* Get the priority for this provider, should return a priority relative to
* {@link #DEFAULT_PRIORITY}.
*/
public abstract int getPriority();
/**
* Get the value of the specified token in this environment, or return null
* if this provider does not have a value for this token. All tokens are
* converted to UPPERCASE before being requested from the provider
*
* @param token Token (in upper case) to search for
* @param env Current environment
* @return The token value, or null if this provider does not have the token
*/
public abstract Integer getToken(String token, MixinEnvironment env);
}
@@ -45,12 +45,17 @@ import org.spongepowered.asm.lib.tree.LineNumberNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.ConstraintParser;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
import org.spongepowered.asm.util.ConstraintViolationException;
import org.spongepowered.asm.util.InvalidConstraintException;
/**
@@ -284,7 +289,11 @@ public class MixinApplicator {
mixin.transformMethod(mixinMethod);
if (!mixinMethod.name.startsWith("<")) {
boolean isOverwrite = ASMHelper.getVisibleAnnotation(mixinMethod, Overwrite.class) != null;
AnnotationNode overwrite = ASMHelper.getVisibleAnnotation(mixinMethod, Overwrite.class);
boolean isOverwrite = overwrite != null;
if (isOverwrite) {
this.checkConstraints(mixin, overwrite);
}
if (MixinApplicator.hasFlag(mixinMethod, Opcodes.ACC_STATIC)
&& !MixinApplicator.hasFlag(mixinMethod, Opcodes.ACC_PRIVATE)
@@ -690,6 +699,26 @@ public class MixinApplicator {
}
}
/**
* Check constraints for the specified annotation based on token values in
* the current environment
*
* @param mixin Mixin being applied
* @param annotation Annotation node to check constraints
*/
private void checkConstraints(MixinTargetContext mixin, AnnotationNode annotation) {
try {
Constraint constraint = ConstraintParser.parse(annotation);
try {
constraint.check(MixinEnvironment.getCurrentEnvironment());
} catch (ConstraintViolationException ex) {
throw new InvalidMixinException(mixin, ex.getMessage(), ex);
}
} catch (InvalidConstraintException ex) {
throw new InvalidMixinException(mixin, ex.getMessage());
}
}
/**
* Merge annotations from the specified source ClassNode to the destination
* ClassNode, replaces annotations of the equivalent type on the target with
@@ -0,0 +1,289 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
/**
* Parser for constraints
*/
public final class ConstraintParser {
/**
* A constraint. Constraints are parsed from string expressions which are
* always of the form:
*
* <blockquote><pre>&lt;token&gt;(&lt;constraint&gt;)</pre></blockquote>
*
* <p><b>token</b> is normalised to uppercase and must be provided by the
* environment.</p>
*
* <p><b>constraint</b> is an integer range specified in one of the
* following formats:
*
* <dl>
* <dt><pre>()</pre></dt>
* <dd>The token value must be present in the environment, but can have
* any value</dd>
* <dt><pre>(1234)</pre></dt>
* <dd>The token value must be <em>exactly equal to </em> <code>1234
* </code></dd>
* <dt><pre>(1234+)
*(1234-)
*(1234&gt;)
*</pre></dt>
* <dd>All of these variants mean the same thing, and can be read as "1234
* or greater"</dd>
* <dt><pre>(&lt;1234)</pre></dt>
* <dd><em>Less than</em> 123</dd>
* <dt><pre>(&lt;=1234)</pre></dt>
* <dd><em>Less than or equal to</em> 1234 (equivalent to <code>1234&lt;
* </code>)</dd>
* <dt><pre>(&gt;1234)</pre></dt>
* <dd><em>Greater than</em> 1234</dd>
* <dt><pre>(&gt;=1234)</pre></dt>
* <dd><em>Greater than or equal to</em> 1234 (equivalent to <code>1234
* &gt;</code>)</dd>
* <dt><pre>(1234-1300)</pre></dt>
* <dd>Value must be <em>between</dd> 1234 and 1300 (inclusive)
* <dt><pre>(1234+10)</pre></dt>
* <dd>Value must be <em>between</dd> 1234 and 1234+10 (1234-1244
* inclusive)</dd>
* </dl>
*
* <p>All whitespace is ignored in constraint declarations. The following
* declarations are equivalent:</p>
*
* <blockquote><pre>token(123-456)
*token ( 123 - 456 )</pre></blockquote>
*
* <p>Multiple constraints should be separated by semicolon (<code>;</code>)
* and are conjoined by an implied logical <code>AND</code> operator. That
* is: all constraints must pass for the constraint to be considered valid.
* </p>
*/
public static class Constraint {
public static final Constraint NONE = new Constraint();
private static final Pattern pattern =
Pattern.compile("^([A-Z0-9\\-_\\.]+)\\((?:(<|<=|>|>=|=)?([0-9]+)(<|(-)([0-9]+)?|>|(\\+)([0-9]+)?)?)?\\)$");
private final String expr;
private String token;
private String[] constraint;
private int min = Integer.MIN_VALUE;
private int max = Integer.MAX_VALUE;
private Constraint next;
Constraint(String expr) {
this.expr = expr;
Matcher matcher = Constraint.pattern.matcher(expr);
if (!matcher.matches()) {
throw new InvalidConstraintException("Constraint syntax was invalid parsing: " + this.expr);
}
this.token = matcher.group(1);
this.constraint = new String[] {
matcher.group(2),
matcher.group(3),
matcher.group(4),
matcher.group(5),
matcher.group(6),
matcher.group(7),
matcher.group(8)
};
this.parse();
}
private Constraint() {
this.expr = null;
this.token = "*";
this.constraint = new String[0];
}
private void parse() {
if (!this.has(1)) {
return;
}
this.max = this.min = this.val(1);
boolean hasModifier = this.has(0);
if (this.has(4)) {
if (hasModifier) {
throw new InvalidConstraintException("Unexpected modifier '" + this.elem(0) + "' in " + this.expr + " parsing range");
}
this.max = this.val(4);
if (this.max < this.min) {
throw new InvalidConstraintException("Invalid range specified '" + this.max + "' is less than " + this.min + " in " + this.expr);
}
return;
} else if (this.has(6)) {
if (hasModifier) {
throw new InvalidConstraintException("Unexpected modifier '" + this.elem(0) + "' in " + this.expr + " parsing range");
}
this.max = this.min + this.val(6);
return;
}
if (hasModifier) {
if (this.has(3)) {
throw new InvalidConstraintException("Unexpected trailing modifier '" + this.elem(3) + "' in " + this.expr);
}
String leading = this.elem(0);
if (">".equals(leading)) {
this.min++;
this.max = Integer.MAX_VALUE;
} else if (">=".equals(leading)) {
this.max = Integer.MAX_VALUE;
} else if ("<".equals(leading)) {
this.max = --this.min;
this.min = Integer.MIN_VALUE;
} else if ("<=".equals(leading)) {
this.max = this.min;
this.min = Integer.MIN_VALUE;
}
} else if (this.has(2)) {
String trailing = this.elem(2);
if ("<".equals(trailing)) {
this.max = this.min;
this.min = Integer.MIN_VALUE;
} else {
this.max = Integer.MAX_VALUE;
}
}
}
private boolean has(int index) {
return this.constraint[index] != null;
}
private String elem(int index) {
return this.constraint[index];
}
private int val(int index) {
return this.constraint[index] != null ? Integer.parseInt(this.constraint[index]) : 0;
}
void append(Constraint next) {
if (this.next != null) {
this.next.append(next);
return;
}
this.next = next;
}
public String getToken() {
return this.token;
}
public int getMin() {
return this.min;
}
public int getMax() {
return this.max;
}
public void check(MixinEnvironment environment) throws ConstraintViolationException {
if (this != Constraint.NONE) {
Integer value = environment.getToken(this.token);
if (value == null) {
throw new ConstraintViolationException("The token '" + this.token + "' could not be resolved in " + environment, this);
}
if (value.intValue() < this.min) {
throw new ConstraintViolationException("Token '" + this.token + "' has a value (" + value
+ ") which is less than the minimum value " + this.min + " in " + environment, this, value.intValue());
}
if (value.intValue() > this.max) {
throw new ConstraintViolationException("Token '" + this.token + "' has a value (" + value
+ ") which is greater than the maximum value " + this.max + " in " + environment, this, value.intValue());
}
}
if (this.next != null) {
this.next.check(environment);
}
}
public String getRangeHumanReadable() {
if (this.min == Integer.MIN_VALUE && this.max == Integer.MAX_VALUE) {
return "ANY VALUE";
} else if (this.min == Integer.MIN_VALUE) {
return String.format("less than or equal to %d", this.max);
} else if (this.max == Integer.MAX_VALUE) {
return String.format("greater than or equal to %d", this.min);
} else if (this.min == this.max) {
return String.format("%d", this.min);
}
return String.format("between %d and %d", this.min, this.max);
}
@Override
public String toString() {
return String.format("Constraint(%s [%d-%d])", this.token, this.min, this.max);
}
}
private ConstraintParser() {
}
public static Constraint parse(String expr) {
if (expr == null || expr.length() == 0) {
return Constraint.NONE;
}
String[] exprs = expr.replaceAll("\\s", "").toUpperCase().split(";");
Constraint head = null;
for (String subExpr : exprs) {
Constraint next = new Constraint(subExpr);
if (head == null) {
head = next;
} else {
head.append(next);
}
}
return head != null ? head : Constraint.NONE;
}
public static Constraint parse(AnnotationNode annotation) {
String constraints = ASMHelper.getAnnotationValue(annotation, "constraints", "");
return ConstraintParser.parse(constraints);
}
}
@@ -0,0 +1,97 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.util;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* Exception thrown when a constraint violation is encountered
*/
public class ConstraintViolationException extends Exception {
private static final String MISSING_VALUE = "UNRESOLVED";
private static final long serialVersionUID = 1L;
private final Constraint constraint;
private final String badValue;
public ConstraintViolationException(Constraint constraint) {
this.constraint = constraint;
this.badValue = ConstraintViolationException.MISSING_VALUE;
}
public ConstraintViolationException(Constraint constraint, int badValue) {
this.constraint = constraint;
this.badValue = String.valueOf(badValue);
}
public ConstraintViolationException(String message, Constraint constraint) {
super(message);
this.constraint = constraint;
this.badValue = ConstraintViolationException.MISSING_VALUE;
}
public ConstraintViolationException(String message, Constraint constraint, int badValue) {
super(message);
this.constraint = constraint;
this.badValue = String.valueOf(badValue);
}
public ConstraintViolationException(Throwable cause, Constraint constraint) {
super(cause);
this.constraint = constraint;
this.badValue = ConstraintViolationException.MISSING_VALUE;
}
public ConstraintViolationException(Throwable cause, Constraint constraint, int badValue) {
super(cause);
this.constraint = constraint;
this.badValue = String.valueOf(badValue);
}
public ConstraintViolationException(String message, Throwable cause, Constraint constraint) {
super(message, cause);
this.constraint = constraint;
this.badValue = ConstraintViolationException.MISSING_VALUE;
}
public ConstraintViolationException(String message, Throwable cause, Constraint constraint, int badValue) {
super(message, cause);
this.constraint = constraint;
this.badValue = String.valueOf(badValue);
}
public Constraint getConstraint() {
return this.constraint;
}
public String getBadValue() {
return this.badValue;
}
}
@@ -0,0 +1,50 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.util;
/**
* Exception thrown when a constraint declaration is invalid
*/
public class InvalidConstraintException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
public InvalidConstraintException() {
}
public InvalidConstraintException(String s) {
super(s);
}
public InvalidConstraintException(Throwable cause) {
super(cause);
}
public InvalidConstraintException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -27,6 +27,8 @@ package org.spongepowered.asm.util;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
@@ -54,6 +56,11 @@ public class PrettyPrinter {
*/
private int width = 100;
/**
* Wrap width used when an explicit wrap width is not specified
*/
private int wrapWidth = 80;
/**
* Content lines
*/
@@ -66,6 +73,15 @@ public class PrettyPrinter {
public PrettyPrinter(int width) {
this.width = width;
}
public PrettyPrinter wrapTo(int wrapWidth) {
this.wrapWidth = wrapWidth;
return this;
}
public int wrapTo() {
return this.wrapWidth;
}
/**
* Adds a blank line to the output
@@ -116,6 +132,58 @@ public class PrettyPrinter {
return this;
}
public PrettyPrinter addWrapped(String format, Object... args) {
return this.addWrapped(this.wrapWidth, format, args);
}
/**
* Adds a formatted line to the output, and attempts to wrap the line
* content to the specified width
*
* @param width wrap width to use for this content
* @param format format string
* @param args arguments
*
* @return fluent interface
*/
public PrettyPrinter addWrapped(int width, String format, Object... args) {
String indent = "";
String line = String.format(format, args).replace("\t", " ");
Matcher indentMatcher = Pattern.compile("^(\\s+)(.*)$").matcher(line);
if (indentMatcher.matches()) {
indent = indentMatcher.group(1);
}
try {
for (String wrappedLine : this.getWrapped(width, line, indent)) {
this.lines.add(wrappedLine);
}
} catch (Exception ex) {
this.add(line);
}
return this;
}
private List<String> getWrapped(int width, String line, String indent) {
List<String> lines = new ArrayList<String>();
while (line.length() > width) {
int wrapPoint = line.lastIndexOf(' ', width);
if (wrapPoint < 10) {
wrapPoint = width;
}
String head = line.substring(0, wrapPoint);
lines.add(head);
line = indent + line.substring(wrapPoint + 1);
}
if (line.length() > 0) {
lines.add(line);
}
return lines;
}
/**
* Adds a horizontal rule to the output