aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/com/jantuomi/tunkki/exception/TunkkiError.java
blob: 24431baa578799d11ea9e01dca3efc9dc25c390a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.jantuomi.tunkki.exception;


import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jan on 12.6.2016.
 */
public class TunkkiError extends Exception {

    public enum ExceptionType {
        IllegalTokenError,
        SyntaxError,
        TypeError,
        FunctionArgumentError,
        ExpectedDifferentTokenError,
        UndeclaredSymbolError,
        IncludeError,
        GeneralError
    }

    private static Map<ExceptionType, String> errorTexts = new HashMap<>();

    static {
        errorTexts.put(ExceptionType.IllegalTokenError, "Unknown or illegal token %s found.");
        errorTexts.put(ExceptionType.SyntaxError, "Unexpected %s.");
        errorTexts.put(ExceptionType.TypeError, "Incompatible types %s and %s.");
        errorTexts.put(ExceptionType.ExpectedDifferentTokenError, "Token '%s' expects a different token stack.");
        errorTexts.put(ExceptionType.FunctionArgumentError, "The parameter list given to function %s is either of wrong length or the parameters are of wrong type. Actual: %s");
        errorTexts.put(ExceptionType.UndeclaredSymbolError, "No symbol %s defined, parameters: [%s].");
        errorTexts.put(ExceptionType.IncludeError, "File %s could not be included.");
        errorTexts.put(ExceptionType.GeneralError, "%s");
    }

    private ExceptionType exceptionType;
    private String completeMessage;
    private List<String> arguments;

    public TunkkiError(ExceptionType exceptionType, int line, String... args) {
        super(exceptionType.toString(), null, false, false);
        this.exceptionType = exceptionType;
        this.arguments = Arrays.asList(args);
        this.completeMessage = formatMessage(exceptionType.toString() + ": " + what(exceptionType), line, args);
    }

    private static String formatMessage(String message, int line, String... parameters) {

        message = String.format(message, parameters);
        if (line == -1) {
            return "\n" + message;
        } else {
            return String.format("\nLine #%d: ", line) + message;
        }
    }

    public static String what(ExceptionType type) {
        return errorTexts.get(type);
    }

    @Override
    public void printStackTrace() {
        System.err.println(completeMessage);
    }

    public ExceptionType getType() {
        return exceptionType;
    }

    public List<String> getArguments() {
        return this.arguments;
    }
}