Avatar of artemkorsakov

artemkorsakov's solution

to Forth in the Java Track

Published at May 02 2019 · 0 comments
Instructions
Test suite
Solution

Implement an evaluator for a very simple subset of Forth.

Forth is a stack-based programming language. Implement a very basic evaluator for a small subset of Forth.

Your evaluator has to support the following words:

  • +, -, *, / (integer arithmetic)
  • DUP, DROP, SWAP, OVER (stack manipulation)

Your evaluator also has to support defining new words using the customary syntax: : word-name definition ;.

To keep things simple the only data type you need to support is signed integers of at least 16 bits size.

You should use the following rules for the syntax: a number is a sequence of one or more (ASCII) digits, a word is a sequence of one or more letters, digits, symbols or punctuation that is not a number. (Forth probably uses slightly different rules, but this is close enough.)

Words are case-insensitive.

Setup

Go through the setup instructions for Java to install the necessary dependencies:

https://exercism.io/tracks/java/installation

Running the tests

You can run all the tests for an exercise by entering the following in your terminal:

$ gradle test

Use gradlew.bat if you're on Windows

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the @Ignore("Remove to run test") annotation.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

ForthEvaluatorTest.java

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.Arrays;
import java.util.Collections;

import static org.junit.Assert.assertEquals;

public class ForthEvaluatorTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    private ForthEvaluator forthEvaluator;

    @Before
    public void setUp() {
        forthEvaluator = new ForthEvaluator();
    }

    @Test
    public void testNumbersAreJustPushedOntoTheStack() {
        assertEquals(
                Arrays.asList(1, 2, 3, 4, 5),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 4 5")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testTwoNumbersCanBeAdded() {
        assertEquals(
                Collections.singletonList(3),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 +")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfAdditionAttemptedWithNothingOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Addition requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("+"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfAdditionAttemptedWithOneNumberOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Addition requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("1 +"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testTwoNumbersCanBeSubtracted() {
        assertEquals(
                Collections.singletonList(-1),
                forthEvaluator.evaluateProgram(Collections.singletonList("3 4 -")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfSubtractionAttemptedWithNothingOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Subtraction requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("-"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfSubtractionAttemptedWithOneNumberOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Subtraction requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("1 -"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testTwoNumbersCanBeMultiplied() {
        assertEquals(
                Collections.singletonList(8),
                forthEvaluator.evaluateProgram(Collections.singletonList("2 4 *")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfMultiplicationAttemptedWithNothingOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Multiplication requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("*"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfMultiplicationAttemptedWithOneNumberOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Multiplication requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("1 *"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testTwoNumbersCanBeDivided() {
        assertEquals(
                Collections.singletonList(4),
                forthEvaluator.evaluateProgram(Collections.singletonList("12 3 /")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testThatIntegerDivisionIsUsed() {
        assertEquals(
                Collections.singletonList(2),
                forthEvaluator.evaluateProgram(Collections.singletonList("8 3 /")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfDividingByZero() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Division by 0 is not allowed");

        forthEvaluator.evaluateProgram(Collections.singletonList("4 0 /"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfDivisionAttemptedWithNothingOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Division requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("/"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfDivisionAttemptedWithOneNumberOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Division requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("1 /"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testCombinedAdditionAndSubtraction() {
        assertEquals(
                Collections.singletonList(-1),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 + 4 -")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testCombinedMultiplicationAndDivision() {
        assertEquals(
                Collections.singletonList(2),
                forthEvaluator.evaluateProgram(Collections.singletonList("2 4 * 3 /")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDupCopiesAValueOnTheStack() {
        assertEquals(
                Arrays.asList(1, 1),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 dup")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDupCopiesTopValueOnTheStack() {
        assertEquals(
                Arrays.asList(1, 2, 2),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 dup")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfDuplicatingAttemptedWithNothingOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Duplicating requires that the stack contain at least 1 value");

        forthEvaluator.evaluateProgram(Collections.singletonList("dup"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDropRemovesTheTopValueOnTheStackIfItIsTheOnlyOne() {
        assertEquals(
                Collections.emptyList(),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 drop")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDropRemovesTheTopValueOnTheStackIfItIsNotTheOnlyOne() {
        assertEquals(
                Collections.singletonList(1),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 drop")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfDroppingAttemptedWithNothingOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Dropping requires that the stack contain at least 1 value");

        forthEvaluator.evaluateProgram(Collections.singletonList("drop"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testSwapSwapsTheTopTwosValueOnTheStackIfTheyAreTheOnlyOnes() {
        assertEquals(
                Arrays.asList(2, 1),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 swap")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testSwapSwapsTheTopTwosValueOnTheStackIfTheyAreNotTheOnlyOnes() {
        assertEquals(
                Arrays.asList(1, 3, 2),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 swap")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfSwappingAttemptedWithNothingOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Swapping requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("swap"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfSwappingAttemptedWithOneNumberOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Swapping requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("1 swap"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testOverCopiesTheSecondElementIfThereAreOnlyTwo() {
        assertEquals(
                Arrays.asList(1, 2, 1),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 over")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testOverCopiesTheSecondElementIfThereAreMoreThanTwo() {
        assertEquals(
                Arrays.asList(1, 2, 3, 2),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 over")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfOveringAttemptedWithNothingOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Overing requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("over"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfOveringAttemptedWithOneNumberOnTheStack() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Overing requires that the stack contain at least 2 values");

        forthEvaluator.evaluateProgram(Collections.singletonList("1 over"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testUserDefinedOperatorsCanConsistOfBuiltInOperators() {
        assertEquals(
                Arrays.asList(1, 1, 1),
                forthEvaluator.evaluateProgram(Arrays.asList(": dup-twice dup dup ;", "1 dup-twice")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testUserDefinedOperatorsAreEvaluatedInTheCorrectOrder() {
        assertEquals(
                Arrays.asList(1, 2, 3),
                forthEvaluator.evaluateProgram(Arrays.asList(": countup 1 2 3 ;", "countup")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testCanRedefineAUserDefinedOperator() {
        assertEquals(
                Arrays.asList(1, 1, 1),
                forthEvaluator.evaluateProgram(Arrays.asList(": foo dup ;", ": foo dup dup ;", "1 foo")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testCanOverrideBuiltInWordOperators() {
        assertEquals(
                Arrays.asList(1, 1),
                forthEvaluator.evaluateProgram(Arrays.asList(": swap dup ;", "1 swap")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testCanOverrideBuiltInArithmeticOperators() {
        assertEquals(
                Collections.singletonList(12),
                forthEvaluator.evaluateProgram(Arrays.asList(": + * ;", "3 4 +")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testCanUseDifferentWordsWithTheSameName() {
        assertEquals(
                Arrays.asList(5, 6),
                forthEvaluator.evaluateProgram(Arrays.asList(": foo 5 ;", ": bar foo ;", ": foo 6 ;", "bar foo")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testCanDefineWordThatUsesWordWithTheSameName() {
        assertEquals(
                Collections.singletonList(11),
                forthEvaluator.evaluateProgram(Arrays.asList(": foo 10 ;", ": foo foo 1 + ;", "foo")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testCannotRedefineNumbers() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Cannot redefine numbers");

        forthEvaluator.evaluateProgram(Collections.singletonList(": 1 2 ;"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testErrorIfEvaluatingAnUndefinedOperator() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("No definition available for operator \"foo\"");

        forthEvaluator.evaluateProgram(Collections.singletonList("foo"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDupIsCaseInsensitive() {
        assertEquals(
                Arrays.asList(1, 1, 1, 1),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 DUP Dup dup")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDropIsCaseInsensitive() {
        assertEquals(
                Arrays.asList(1),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 4 DROP Drop drop")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testSwapIsCaseInsensitive() {
        assertEquals(
                Arrays.asList(2, 3, 4, 1),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 SWAP 3 Swap 4 swap")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testOverIsCaseInsensitive() {
        assertEquals(
                Arrays.asList(1, 2, 1, 2, 1),
                forthEvaluator.evaluateProgram(Collections.singletonList("1 2 OVER Over over")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testUserDefinedWordsAreCaseInsensitive() {
        assertEquals(
                Arrays.asList(1, 1, 1, 1),
                forthEvaluator.evaluateProgram(Arrays.asList(": foo dup ;", "1 FOO Foo foo")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDefinitionsAreCaseInsensitive() {
        assertEquals(
                Arrays.asList(1, 1, 1, 1),
                forthEvaluator.evaluateProgram(Arrays.asList(": SWAP DUP Dup dup ;", "1 swap")));
    }

}

src/main/java/ForthEvaluator.java

import java.util.ArrayList;
import java.util.List;

class ForthEvaluator {

    List<Integer> evaluateProgram(List<String> singletonList) {
        List<Integer> stack = new ArrayList<>();
        Commands commands = new Commands();

        for (String row : singletonList) {
            if (row.startsWith(":")) {
                commands.addCommand(getNewCommand(row));
            } else {
                stack = commands.execute(stack, row.split(" "));
            }
        }

        return stack;
    }

    /**
     * ": word-name definition ;"
     */
    private String[] getNewCommand(String definition) {
        if (!definition.endsWith(";")) {
            throw new IllegalArgumentException("Unknown definition - " + definition);
        }

        String[] members = definition.substring(2).split("[\\s:;]+");
        if (members.length < 2) {
            throw new IllegalArgumentException("Unknown definition - " + definition);
        }

        if (Commands.isNumber(members[0])) {
            throw new IllegalArgumentException("Cannot redefine numbers");
        }

        return members;
    }
}

src/main/java/Commands.java

import java.util.*;
import java.util.regex.Pattern;

enum ForthCommand {
    ADD, SUB, MUL, DIV, DUP, DROP, SWAP, OVER
}

class Commands {
    private Map<String, Object> commands;
    private static final Pattern pattern = Pattern.compile("^\\d+$");

    Commands() {
        addDefaultCommands();
    }

    static boolean isNumber(String str) {
        return pattern.matcher(str).matches();
    }

    void addCommand(String[] members) {
        String commandName = members[0].toUpperCase();
        String[] commandNames = Arrays.stream(members).skip(1).toArray(String[]::new);
        List<Integer> stack = new ArrayList<>();
        try {
            stack = execute(stack, commandNames);
            addCommand(commandName, stack);
        } catch (Exception ignore) {
            addCommand(commandName, commandNames);
        }
    }

    List<Integer> execute(List<Integer> stack, String[] names) {
        for (String name : names) {
            stack = execute(stack, name);
        }
        return stack;
    }

    private List<Integer> execute(List<Integer> stack, String name) {
        if (isNumber(name)) {
            stack.add(Integer.parseInt(name));
            return stack;
        }

        Object command = getCommand(name);
        if (command instanceof ForthCommand) {
            return execute(stack, (ForthCommand) command);
        } else if (command instanceof String[]) {
            return execute(stack, (String[]) command);
        } else if (command instanceof List) {
            stack.addAll((List<Integer>) command);
            return stack;
        } else {
            throw new IllegalArgumentException("No definition available for operator \"" + name + "\"");
        }
    }

    private Object getCommand(String name) {
        if (commands.containsKey(name.toUpperCase())) {
            return commands.get(name.toUpperCase());
        } else {
            throw new IllegalArgumentException("No definition available for operator \"" + name + "\"");
        }
    }

    private void addCommand(String commandName, Object command) {
        if (commands.containsKey(commandName)) {
            commands.replace(commandName, command);
        } else {
            commands.put(commandName, command);
        }
    }

    private void addDefaultCommands() {
        commands = new HashMap<>();
        commands.put("+", ForthCommand.ADD);
        commands.put("-", ForthCommand.SUB);
        commands.put("*", ForthCommand.MUL);
        commands.put("/", ForthCommand.DIV);
        commands.put("DUP", ForthCommand.DUP);
        commands.put("DROP", ForthCommand.DROP);
        commands.put("SWAP", ForthCommand.SWAP);
        commands.put("OVER", ForthCommand.OVER);
    }

    private List<Integer> execute(List<Integer> stack, ForthCommand forthCommand) {
        switch (forthCommand) {
            case ADD:
                return add(stack);
            case SUB:
                return sub(stack);
            case MUL:
                return mul(stack);
            case DIV:
                return div(stack);
            case DUP:
                return dup(stack);
            case DROP:
                return drop(stack);
            case SWAP:
                return swap(stack);
            case OVER:
                return over(stack);
            default:
                throw new IllegalArgumentException("No definition available for operator \"" + forthCommand + "\"");
        }
    }

    private List<Integer> add(List<Integer> stack) {
        if (stack.size() < 2) {
            throw new IllegalArgumentException("Addition requires that the stack contain at least 2 values");
        }

        int res = stack.get(stack.size() - 2) + stack.get(stack.size() - 1);
        stack.set(stack.size() - 2, res);
        stack.remove(stack.size() - 1);
        return stack;
    }

    private List<Integer> sub(List<Integer> stack) {
        if (stack.size() < 2) {
            throw new IllegalArgumentException("Subtraction requires that the stack contain at least 2 values");
        }

        int res = stack.get(stack.size() - 2) - stack.get(stack.size() - 1);
        stack.set(stack.size() - 2, res);
        stack.remove(stack.size() - 1);
        return stack;
    }

    private List<Integer> mul(List<Integer> stack) {
        if (stack.size() < 2) {
            throw new IllegalArgumentException("Multiplication requires that the stack contain at least 2 values");
        }

        int res = stack.get(stack.size() - 2) * stack.get(stack.size() - 1);
        stack.set(stack.size() - 2, res);
        stack.remove(stack.size() - 1);
        return stack;
    }

    private List<Integer> div(List<Integer> stack) {
        if (stack.size() < 2) {
            throw new IllegalArgumentException("Division requires that the stack contain at least 2 values");
        }

        if (stack.get(stack.size() - 1) == 0) {
            throw new IllegalArgumentException("Division by 0 is not allowed");
        }

        int res = stack.get(stack.size() - 2) / stack.get(stack.size() - 1);
        stack.set(stack.size() - 2, res);
        stack.remove(stack.size() - 1);
        return stack;
    }

    private List<Integer> dup(List<Integer> stack) {
        if (stack.size() == 0) {
            throw new IllegalArgumentException("Duplicating requires that the stack contain at least 1 value");
        }

        int res = stack.get(stack.size() - 1);
        stack.add(res);
        return stack;
    }

    private List<Integer> drop(List<Integer> stack) {
        if (stack.size() == 0) {
            throw new IllegalArgumentException("Dropping requires that the stack contain at least 1 value");
        }

        stack.remove(stack.size() - 1);
        return stack;
    }

    private List<Integer> swap(List<Integer> stack) {
        if (stack.size() < 2) {
            throw new IllegalArgumentException("Swapping requires that the stack contain at least 2 values");
        }

        int res = stack.get(stack.size() - 2);
        stack.set(stack.size() - 2, stack.get(stack.size() - 1));
        stack.set(stack.size() - 1, res);
        return stack;
    }

    private List<Integer> over(List<Integer> stack) {
        if (stack.size() < 2) {
            throw new IllegalArgumentException("Overing requires that the stack contain at least 2 values");
        }

        int res = stack.get(stack.size() - 2);
        stack.add(res);
        return stack;
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?