Avatar of tocklime

tocklime's solution

to Forth in the Java Track

Published at May 15 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")));
    }

}
import java.util.*;
import java.util.function.BiFunction;
import java.util.stream.*;

class ForthEvaluator{

    /**
     * interface to represent how the evaluator is currently working
     */
    private interface ExecutionMode {
        public void handleWord(String w);
    }

    /**
     * Executing mode: read word, apply its effects.
     */
    private final class Executing implements ExecutionMode{
        public void handleWord(String w){
            if(w.equals(":")) {
                ForthEvaluator.this.setExecutionMode(new AwaitingWordName());
            } else {
                String definition = knownWords.get(w);
                if(definition != null)
                    ForthEvaluator.this.evaluateLine(definition);
                else
                    ForthEvaluator.this.primitiveWord(w);
            }
        }
    }
    /**
     * Awaiting word name mode: at start of definition, but we don't know 
     * the word yet. Next word encountered will be the name.
     */
    private final class AwaitingWordName implements ExecutionMode{
        public void handleWord(String w){
            ForthEvaluator.this.setExecutionMode(new DefiningWord(w));
        }
    }
    /**
     * Defining word mode: take each given word, simplify it to primitive operations
     * and remember it. When a ';' is encountered, add the name and definition to
     * outer classes knownWords.
     */
    private final class DefiningWord implements ExecutionMode{
        public final String name;
        public final StringJoiner definition;
        DefiningWord(String name){
            if(Character.isDigit(name.charAt(0)))
                throw new IllegalArgumentException("Cannot redefine numbers");
            this.name = name;
            this.definition = new StringJoiner(" ");
        }
        public void handleWord(String w){
            if(w.equals(";")){
                knownWords.put(name,definition.toString());
                ForthEvaluator.this.setExecutionMode(new Executing());
            }else{
                definition.add(knownWords.getOrDefault(w,w));
            }   
        }
    }

    private void setExecutionMode(ExecutionMode m) {
        this.mode = m;
    }
    private ExecutionMode mode = this.new Executing();

    private final Stack<Integer> stack = new Stack<Integer>();
    private final Map<String,String> knownWords = new HashMap<String,String>();

    /**
     * Get {@code count} items from the stack. {@code name} is there for error messages.
     * 
     * @return array of size {@code count}
     */
    private int[] getN(String name, int count){
        try {
            return IntStream.range(0,count).map(x -> stack.pop()).toArray();
        } 
        catch (EmptyStackException e)
        {
            throw new IllegalArgumentException(
                String.format("%s requires that the stack contain at least %d %s",
                    name,count,count == 1 ? "value" : "values"
                    ));
        }
    }

    /**
     * Execute some binary operation on the stack - pop 2 numbers, apply operation, push result.
     */
    private void primitiveBinaryOp(String name, BiFunction<Integer,Integer,Integer> f){
        int[] p = getN(name,2);
        stack.push(f.apply(p[0],p[1]));
    }

    /**
     * Primitive operations - arithmetic and stack manipulation.
     */
    private void primitiveWord(String w){
        switch(w){
            case "+": primitiveBinaryOp("Addition",(a,b) -> a+b); return;
            case "-": primitiveBinaryOp("Subtraction",(a,b) -> b-a); return;
            case "*": primitiveBinaryOp("Multiplication",(a,b) -> a*b); return;
            case "/": 
                try{
                    primitiveBinaryOp("Division", (a,b) -> b/a);
                } catch (ArithmeticException ae){
                    throw new IllegalArgumentException("Division by 0 is not allowed");
                }
                return;
            case "dup": 
            {
                int a = getN("Duplicating",1)[0];
                stack.push(a); stack.push(a);
                return;
            }
            case "drop": getN("Dropping",1); return;
            case "swap": 
            {
                int[] p = getN("Swapping",2);
                stack.push(p[0]);
                stack.push(p[1]); 
                return;
            }
            case "over": 
            {
                int[] p = getN("Overing",2);
                stack.push(p[1]);
                stack.push(p[0]);
                stack.push(p[1]);
                return;
            }
            default: 
                try{
                    stack.push(Integer.parseInt(w));
                } catch (NumberFormatException e){
                    throw new IllegalArgumentException(String.format("No definition available for operator \"%s\"",w));
                }
                return;
        }
    }

    /**
     * Evaluate a single line of code
     */
    void evaluateLine(String line){
        Arrays.stream(line.split(" ")).forEach(x -> mode.handleWord(x.toLowerCase()));
    }

    /** Evaluate a program.
     * 
     * @return the stack after the execution.
     */
    List<Integer> evaluateProgram(List<String> lines){
        lines.stream().forEach(this::evaluateLine);
        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?