Avatar of ksnortum

ksnortum's solution

to Forth in the Java Track

Published at Oct 20 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.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class ForthEvaluator {

	enum State {
		EVALUATE, FUNC_NAME, FUNC_DEFINITION, FUNC_END
	}
	
	private static final String ONE_OR_MORE_SPACES = "\\s+";
	private static final String ONE_OR_MORE_DIGITS_WITH_AN_OPTIONAL_MINUS_SIGN = "-?\\d+";

	List<Integer> evaluateProgram(List<String> program) {
		Deque<Integer> stack = new ArrayDeque<>();
		Map<String, String> function = new HashMap<>();
		State state = State.EVALUATE;

		for (String line : program) {
			String funcName = "";
			StringBuilder funcDefinition = new StringBuilder();

			for (String token : line.toLowerCase().split(ONE_OR_MORE_SPACES)) {
				
				// start of function definition
				if (":".equals(token)) { 
					state = State.FUNC_NAME;
				} else if (state == State.FUNC_NAME) {
					if (isInt(token)) {
						throw new IllegalArgumentException("Cannot redefine numbers");
					}
					
					funcName = token;
					state = State.FUNC_DEFINITION;
				} else if (state == State.FUNC_DEFINITION) {
					
					// function definition terminus 
					if (";".equals(token)) { 
						function.put(funcName, funcDefinition.toString());
						state = State.EVALUATE;
					} else {
						if (funcDefinition.length() > 0) {
							funcDefinition.append(" ");
						}
						
						// create function definition
						// it may be a function itself
						if (function.containsKey(token)) {
							for (String funcToken : function.get(token).split(ONE_OR_MORE_SPACES)) {
								stack = evaluate(funcToken, stack);
							}
							
							funcDefinition.append(stack.removeLast());
						} else {
							funcDefinition.append(token);
						}
					}
				} else if (state == State.EVALUATE) {
					
					// Check for function definition, case insensitive
					if (function.containsKey(token)) {
						
						// evaluate each function definition token
						for (String funcToken : function.get(token).split(ONE_OR_MORE_SPACES)) {
							stack = evaluate(funcToken, stack);
						}
					} else {
						stack = evaluate(token, stack);
					}
				}
			}
		}

		return new ArrayList<Integer>(stack);
	}

	private Deque<Integer> evaluate(String token, Deque<Integer> stack) {
		if (isInt(token)) {
			int number = Integer.parseInt(token);
			stack.addLast(number);
		} else if ("+".equals(token)) {
			if (stack.size() < 2) {
				throw new IllegalArgumentException("Addition requires that the stack contain at least 2 values");
			}
			
			int arg1 = stack.removeFirst();
			int arg2 = stack.removeFirst();
			stack.addLast(arg1 + arg2);
		} else if ("-".equals(token)) {
			if (stack.size() < 2) {
				throw new IllegalArgumentException("Subtraction requires that the stack contain at least 2 values");
			}
			
			int arg1 = stack.removeFirst();
			int arg2 = stack.removeFirst();
			stack.addLast(arg1 - arg2);
		} else if ("*".equals(token)) {
			if (stack.size() < 2) {
				throw new IllegalArgumentException("Multiplication requires that the stack contain at least 2 values");
			}
			
			int arg1 = stack.removeFirst();
			int arg2 = stack.removeFirst();
			stack.addLast(arg1 * arg2);
		} else if ("/".equals(token)) {
			if (stack.size() < 2) {
				throw new IllegalArgumentException("Division requires that the stack contain at least 2 values");
			}
			
			int arg1 = stack.removeFirst();
			int arg2 = stack.removeFirst();
			if (arg2 == 0) {
				throw new IllegalArgumentException("Division by 0 is not allowed");
			}
			
			stack.addLast(arg1 / arg2);
		} else if ("dup".equals(token)) {
			if (stack.size() < 1) {
				throw new IllegalArgumentException("Duplicating requires that the stack contain at least 1 value");
			}
			
			int arg1 = stack.getLast();
			stack.addLast(arg1);
		} else if ("drop".equals(token)) {
			if (stack.size() < 1) {
				throw new IllegalArgumentException("Dropping requires that the stack contain at least 1 value");
			}
			
			stack.removeLast();
		} else if ("swap".equals(token)) {
			if (stack.size() < 2) {
				throw new IllegalArgumentException("Swapping requires that the stack contain at least 2 values");
			}
			
			int arg1 = stack.removeLast();
			int arg2 = stack.removeLast();
			stack.addLast(arg1);
			stack.addLast(arg2);
		} else if ("over".equals(token)) {
			if (stack.size() < 2) {
				throw new IllegalArgumentException("Overing requires that the stack contain at least 2 values");
			}
			
			int arg1 = stack.removeLast();
			int arg2 = stack.removeLast();
			stack.addLast(arg2);
			stack.addLast(arg1);
			stack.addLast(arg2);
		} else {
			throw new IllegalArgumentException("No definition available for operator \"" + token + "\"");
		}

		return stack;
	}

	private boolean isInt(String token) {
		return token.matches(ONE_OR_MORE_DIGITS_WITH_AN_OPTIONAL_MINUS_SIGN);
	}

}

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?