Search in sources :

Example 11 with InputParseException

use of com.sk89q.worldedit.extension.input.InputParseException in project FastAsyncWorldEdit by IntellectualSites.

the class ClipboardPatternParser method parseFromInput.

@Override
public Pattern parseFromInput(String input, ParserContext context) throws InputParseException {
    String[] offsetParts = input.split("@", 2);
    if (!offsetParts[0].equalsIgnoreCase("#clipboard") && !offsetParts[0].equalsIgnoreCase("#copy")) {
        return null;
    }
    LocalSession session = context.requireSession();
    BlockVector3 offset = BlockVector3.ZERO;
    if (offsetParts.length == 2) {
        String coords = offsetParts[1];
        if (// min length of `[x,y,z]`
        coords.length() < 7 || coords.charAt(0) != '[' || coords.charAt(coords.length() - 1) != ']') {
            throw new InputParseException(Caption.of("worldedit.error.parser.clipboard.missing-offset"));
        }
        String[] offsetSplit = coords.substring(1, coords.length() - 1).split(",");
        if (offsetSplit.length != 3) {
            throw new InputParseException(Caption.of("worldedit.error.parser.clipboard.missing-coordinates"));
        }
        offset = BlockVector3.at(Integer.parseInt(offsetSplit[0]), Integer.parseInt(offsetSplit[1]), Integer.parseInt(offsetSplit[2]));
    }
    if (session != null) {
        try {
            ClipboardHolder holder = session.getClipboard();
            Clipboard clipboard = holder.getClipboard();
            return new ClipboardPattern(clipboard, offset);
        } catch (EmptyClipboardException e) {
            throw new InputParseException(Caption.of("worldedit.error.empty-clipboard"));
        }
    } else {
        throw new InputParseException(Caption.of("worldedit.error.missing-session"));
    }
}
Also used : InputParseException(com.sk89q.worldedit.extension.input.InputParseException) EmptyClipboardException(com.sk89q.worldedit.EmptyClipboardException) ClipboardHolder(com.sk89q.worldedit.session.ClipboardHolder) LocalSession(com.sk89q.worldedit.LocalSession) Clipboard(com.sk89q.worldedit.extent.clipboard.Clipboard) BlockVector3(com.sk89q.worldedit.math.BlockVector3) ClipboardPattern(com.sk89q.worldedit.function.pattern.ClipboardPattern)

Example 12 with InputParseException

use of com.sk89q.worldedit.extension.input.InputParseException in project FastAsyncWorldEdit by IntellectualSites.

the class TypeOrStateApplyingPatternParser method parseFromInput.

@Override
public Pattern parseFromInput(String input, ParserContext context) throws InputParseException {
    if (!input.startsWith("^")) {
        return null;
    }
    Extent extent = context.requireExtent();
    input = input.substring(1);
    String[] parts = input.split("\\[", 2);
    String type = parts[0];
    if (parts.length == 1) {
        return new TypeApplyingPattern(extent, worldEdit.getBlockFactory().parseFromInput(type, context).getBlockType().getDefaultState());
    } else {
        // states given
        if (!parts[1].endsWith("]")) {
            throw new InputParseException(Caption.of("worldedit.error.parser.missing-rbracket"));
        }
        final String[] states = parts[1].substring(0, parts[1].length() - 1).split(",");
        Map<String, String> statesToSet = new HashMap<>();
        for (String state : states) {
            if (state.isEmpty()) {
                throw new InputParseException(Caption.of("worldedit.error.parser.empty-state"));
            }
            String[] propVal = state.split("=", 2);
            if (propVal.length != 2) {
                throw new InputParseException(Caption.of("worldedit.error.parser.missing-equals-separator"));
            }
            final String prop = propVal[0];
            if (prop.isEmpty()) {
                throw new InputParseException(Caption.of("worldedit.error.parser.empty-property"));
            }
            final String value = propVal[1];
            if (value.isEmpty()) {
                throw new InputParseException(Caption.of("worldedit.error.parser.empty-value"));
            }
            if (statesToSet.put(prop, value) != null) {
                throw new InputParseException(Caption.of("worldedit.error.parser.duplicate-property", TextComponent.of(prop)));
            }
        }
        if (type.isEmpty()) {
            return new StateApplyingPattern(extent, statesToSet);
        } else {
            Extent buffer = new ExtentBuffer(extent);
            Pattern typeApplier = new TypeApplyingPattern(buffer, worldEdit.getBlockFactory().parseFromInput(type, context).getBlockType().getDefaultState());
            Pattern stateApplier = new StateApplyingPattern(buffer, statesToSet);
            return new ExtentBufferedCompositePattern(buffer, typeApplier, stateApplier);
        }
    }
}
Also used : ExtentBufferedCompositePattern(com.sk89q.worldedit.function.pattern.ExtentBufferedCompositePattern) TypeApplyingPattern(com.sk89q.worldedit.function.pattern.TypeApplyingPattern) StateApplyingPattern(com.sk89q.worldedit.function.pattern.StateApplyingPattern) Pattern(com.sk89q.worldedit.function.pattern.Pattern) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) ExtentBufferedCompositePattern(com.sk89q.worldedit.function.pattern.ExtentBufferedCompositePattern) TypeApplyingPattern(com.sk89q.worldedit.function.pattern.TypeApplyingPattern) Extent(com.sk89q.worldedit.extent.Extent) HashMap(java.util.HashMap) ExtentBuffer(com.sk89q.worldedit.extent.buffer.ExtentBuffer) StateApplyingPattern(com.sk89q.worldedit.function.pattern.StateApplyingPattern)

Example 13 with InputParseException

use of com.sk89q.worldedit.extension.input.InputParseException in project FastAsyncWorldEdit by IntellectualSites.

the class DefaultItemParser method parseFromInput.

@Override
public BaseItem parseFromInput(String input, ParserContext context) throws InputParseException {
    ItemType itemType;
    CompoundBinaryTag itemNbtData = null;
    BaseItem item = null;
    // Legacy matcher
    if (context.isTryingLegacy()) {
        try {
            String[] split = input.split(":");
            if (split.length == 0) {
                throw new InputParseException(Caption.of("worldedit.error.parser.invalid-colon"));
            } else if (split.length == 1) {
                itemType = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(split[0]));
            } else {
                itemType = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
            }
            if (itemType != null) {
                item = new BaseItem(itemType);
            }
        } catch (NumberFormatException ignored) {
        }
    }
    if (item == null) {
        String typeString;
        String nbtString = null;
        int nbtStart = input.indexOf('{');
        if (nbtStart == -1) {
            typeString = input;
        } else {
            typeString = input.substring(0, nbtStart);
            if (nbtStart + 1 >= input.length()) {
                throw new InputParseException(TranslatableComponent.of("worldedit.error.parser.hanging-lbracket", TextComponent.of(nbtStart)));
            }
            int stateEnd = input.lastIndexOf('}');
            if (stateEnd < 0) {
                throw new InputParseException(TranslatableComponent.of("worldedit.error.parser.missing-rbracket"));
            }
            nbtString = input.substring(nbtStart);
        }
        if ("hand".equalsIgnoreCase(typeString)) {
            BaseItemStack heldItem = getItemInHand(context.requireActor(), HandSide.MAIN_HAND);
            // FAWE start
            itemType = heldItem.getType();
            itemNbtData = heldItem.getNbt();
        // FAWE end
        } else if ("offhand".equalsIgnoreCase(typeString)) {
            BaseItemStack heldItem = getItemInHand(context.requireActor(), HandSide.OFF_HAND);
            // FAWE start
            itemType = heldItem.getType();
            itemNbtData = heldItem.getNbt();
        // FAWE end
        } else {
            itemType = ItemTypes.get(typeString.toLowerCase(Locale.ROOT));
        }
        // FAWE start
        if (itemType == null) {
            throw new NoMatchException(TranslatableComponent.of("worldedit.error.unknown-item", TextComponent.of(input)));
        }
        if (nbtString != null) {
            try {
                CompoundBinaryTag otherTag = TagStringIO.get().asCompound(nbtString);
                if (itemNbtData == null) {
                    itemNbtData = otherTag;
                } else {
                    itemNbtData.put(NbtUtils.getCompoundBinaryTagValues(otherTag));
                }
            } catch (IOException e) {
                throw new NoMatchException(TranslatableComponent.of("worldedit.error.invalid-nbt", TextComponent.of(input), TextComponent.of(e.getMessage())));
            }
        }
        item = new BaseItem(itemType, itemNbtData == null ? null : LazyReference.computed(itemNbtData));
    }
    return item;
}
Also used : InputParseException(com.sk89q.worldedit.extension.input.InputParseException) BaseItemStack(com.sk89q.worldedit.blocks.BaseItemStack) ItemType(com.sk89q.worldedit.world.item.ItemType) IOException(java.io.IOException) NoMatchException(com.sk89q.worldedit.extension.input.NoMatchException) BaseItem(com.sk89q.worldedit.blocks.BaseItem) CompoundBinaryTag(com.sk89q.worldedit.util.nbt.CompoundBinaryTag)

Example 14 with InputParseException

use of com.sk89q.worldedit.extension.input.InputParseException in project FastAsyncWorldEdit by IntellectualSites.

the class BlockStateMaskParser method parseFromInput.

@Override
public Mask parseFromInput(String input, ParserContext context) throws InputParseException {
    if (!(input.startsWith("^[") || input.startsWith("^=[")) || !input.endsWith("]")) {
        return null;
    }
    boolean strict = input.charAt(1) == '=';
    String states = input.substring(2 + (strict ? 1 : 0), input.length() - 1);
    try {
        return new BlockStateMask(context.requireExtent(), Splitter.on(',').omitEmptyStrings().trimResults().withKeyValueSeparator('=').split(states), strict);
    } catch (Exception e) {
        throw new InputParseException(Caption.of("worldedit.error.parser.bad-state-format", TextComponent.of(String.valueOf(e))));
    }
}
Also used : InputParseException(com.sk89q.worldedit.extension.input.InputParseException) BlockStateMask(com.sk89q.worldedit.function.mask.BlockStateMask) InputParseException(com.sk89q.worldedit.extension.input.InputParseException)

Example 15 with InputParseException

use of com.sk89q.worldedit.extension.input.InputParseException in project FastAsyncWorldEdit by IntellectualSites.

the class BlockState method get.

/**
 * Returns a temporary BlockState for a given type and string.
 *
 * <p>It's faster if a BlockType is provided compared to parsing the string.</p>
 *
 * @param type  BlockType e.g., BlockTypes.STONE (or null)
 * @param state String e.g., minecraft:water[level=4]
 * @return BlockState
 */
public static BlockState get(@Nullable BlockType type, String state, BlockState defaultState) throws InputParseException {
    int propStrStart = state.indexOf('[');
    if (type == null) {
        CharSequence key;
        if (propStrStart == -1) {
            key = state;
        } else {
            MutableCharSequence charSequence = MutableCharSequence.getTemporal();
            charSequence.setString(state);
            charSequence.setSubstring(0, propStrStart);
            key = charSequence;
        }
        type = BlockTypes.get(key);
        if (type == null) {
            String input = key.toString();
            throw new SuggestInputParseException("Does not match a valid block type: " + input, input, () -> Stream.of(BlockTypesCache.values).map(BlockType::getId).filter(id -> StringMan.blockStateMatches(input, id)).sorted(StringMan.blockStateComparator(input)).collect(Collectors.toList()));
        }
    }
    if (propStrStart == -1) {
        return type.getDefaultState();
    }
    List<? extends Property<?>> propList = type.getProperties();
    if (state.charAt(state.length() - 1) != ']') {
        state = state + "]";
    }
    MutableCharSequence charSequence = MutableCharSequence.getTemporal();
    charSequence.setString(state);
    if (propList.size() == 1) {
        AbstractProperty<?> property = (AbstractProperty<?>) propList.get(0);
        String name = property.getName();
        charSequence.setSubstring(propStrStart + name.length() + 2, state.length() - 1);
        int index = charSequence.length() <= 0 ? -1 : property.getIndexFor(charSequence);
        if (index != -1) {
            return type.withPropertyId(index);
        }
    }
    int stateId;
    if (defaultState != null) {
        stateId = defaultState.getInternalId();
    } else {
        stateId = type.getDefaultState().getInternalId();
    }
    int length = state.length();
    AbstractProperty<?> property = null;
    int last = propStrStart + 1;
    for (int i = last; i < length; i++) {
        char c = state.charAt(i);
        switch(c) {
            case ']':
            case ',':
                {
                    charSequence.setSubstring(last, i);
                    if (property != null) {
                        int index = property.getIndexFor(charSequence);
                        if (index == -1) {
                            throw SuggestInputParseException.of(charSequence.toString(), (List<Object>) property.getValues());
                        }
                        stateId = property.modifyIndex(stateId, index);
                    } else {
                        // suggest
                        PropertyKey key = PropertyKey.getByName(charSequence);
                        if (key == null || !type.hasProperty(key)) {
                            // Suggest property
                            String input = charSequence.toString();
                            BlockType finalType = type;
                            throw new SuggestInputParseException("Invalid property " + key + ":" + input + " for type " + type, input, () -> finalType.getProperties().stream().map(Property::getName).filter(p -> StringMan.blockStateMatches(input, p)).sorted(StringMan.blockStateComparator(input)).collect(Collectors.toList()));
                        } else {
                            throw new SuggestInputParseException("No operator for " + state, "", () -> Collections.singletonList("="));
                        }
                    }
                    property = null;
                    last = i + 1;
                    break;
                }
            case '=':
                {
                    charSequence.setSubstring(last, i);
                    property = (AbstractProperty) type.getPropertyMap().get(charSequence);
                    last = i + 1;
                    break;
                }
            default:
                continue;
        }
    }
    return type.withPropertyId(stateId >> BlockTypesCache.BIT_OFFSET);
}
Also used : SuggestInputParseException(com.fastasyncworldedit.core.command.SuggestInputParseException) Property(com.sk89q.worldedit.registry.state.Property) BlockVector3(com.sk89q.worldedit.math.BlockVector3) SingleBlockStateMask(com.fastasyncworldedit.core.function.mask.SingleBlockStateMask) BlanketBaseBlock(com.fastasyncworldedit.core.world.block.BlanketBaseBlock) LazyReference(com.sk89q.worldedit.util.concurrency.LazyReference) StringMan(com.fastasyncworldedit.core.util.StringMan) WorldEditException(com.sk89q.worldedit.WorldEditException) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) Map(java.util.Map) PropertyKey(com.fastasyncworldedit.core.registry.state.PropertyKey) WorldEdit(com.sk89q.worldedit.WorldEdit) CompoundBinaryTag(com.sk89q.worldedit.util.nbt.CompoundBinaryTag) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) Function(com.google.common.base.Function) NullExtent(com.sk89q.worldedit.extent.NullExtent) MutableCharSequence(com.fastasyncworldedit.core.util.MutableCharSequence) OutputExtent(com.sk89q.worldedit.extent.OutputExtent) AbstractProperty(com.sk89q.worldedit.registry.state.AbstractProperty) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) List(java.util.List) Stream(java.util.stream.Stream) Capability(com.sk89q.worldedit.extension.platform.Capability) CompoundInput(com.fastasyncworldedit.core.world.block.CompoundInput) CompoundTag(com.sk89q.jnbt.CompoundTag) Mask(com.sk89q.worldedit.function.mask.Mask) ITileInput(com.fastasyncworldedit.core.queue.ITileInput) Pattern(com.sk89q.worldedit.function.pattern.Pattern) Collections(java.util.Collections) Extent(com.sk89q.worldedit.extent.Extent) BlockMaterial(com.sk89q.worldedit.world.registry.BlockMaterial) SuggestInputParseException(com.fastasyncworldedit.core.command.SuggestInputParseException) MutableCharSequence(com.fastasyncworldedit.core.util.MutableCharSequence) AbstractProperty(com.sk89q.worldedit.registry.state.AbstractProperty) MutableCharSequence(com.fastasyncworldedit.core.util.MutableCharSequence) List(java.util.List) PropertyKey(com.fastasyncworldedit.core.registry.state.PropertyKey)

Aggregations

InputParseException (com.sk89q.worldedit.extension.input.InputParseException)29 ParserContext (com.sk89q.worldedit.extension.input.ParserContext)11 NoMatchException (com.sk89q.worldedit.extension.input.NoMatchException)7 Extent (com.sk89q.worldedit.extent.Extent)7 Pattern (com.sk89q.worldedit.function.pattern.Pattern)7 Map (java.util.Map)7 Actor (com.sk89q.worldedit.extension.platform.Actor)5 IOException (java.io.IOException)5 HashMap (java.util.HashMap)5 BlanketBaseBlock (com.fastasyncworldedit.core.world.block.BlanketBaseBlock)4 CompoundTag (com.sk89q.jnbt.CompoundTag)4 WorldEdit (com.sk89q.worldedit.WorldEdit)4 WorldEditException (com.sk89q.worldedit.WorldEditException)4 BlockVector3 (com.sk89q.worldedit.math.BlockVector3)4 World (com.sk89q.worldedit.world.World)4 BaseBlock (com.sk89q.worldedit.world.block.BaseBlock)4 List (java.util.List)4 Stream (java.util.stream.Stream)4 SuggestInputParseException (com.fastasyncworldedit.core.command.SuggestInputParseException)3 Caption (com.fastasyncworldedit.core.configuration.Caption)3