aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/zwobble/couscous/interpreter/values/InterpreterFields.java
blob: b0b7992873bf3b61e8496239ee9222e9452e1ed0 (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
package org.zwobble.couscous.interpreter.values;

import org.zwobble.couscous.ast.FieldDeclarationNode;
import org.zwobble.couscous.interpreter.errors.NoSuchField;
import org.zwobble.couscous.interpreter.errors.UnboundField;
import org.zwobble.couscous.interpreter.types.InterpreterType;

import java.util.HashMap;
import java.util.Map;

public class InterpreterFields {
    public static InterpreterFields forClass(InterpreterType type) {
        return new InterpreterFields(true, type);
    }

    public static InterpreterFields forInstanceOf(InterpreterType type) {
        return new InterpreterFields(false, type);
    }

    private final boolean isStatic;
    private final InterpreterType type;
    private final Map<String, InterpreterValue> fields;

    private InterpreterFields(boolean isStatic, InterpreterType type) {
        this.isStatic = isStatic;
        this.type = type;
        this.fields = new HashMap<>();
    }

    public InterpreterValue getField(String fieldName) {
        getFieldDefinition(fieldName);
        if (fields.containsKey(fieldName)) {
            return fields.get(fieldName);
        } else {
            throw new UnboundField(fieldName);
        }
    }

    public void setField(String fieldName, InterpreterValue value) {
        FieldDeclarationNode field = getFieldDefinition(fieldName);
        // TODO: re-enable this
        //InterpreterTypes.checkIsInstance(field.getType(), value);
        fields.put(fieldName, value);
    }

    private FieldDeclarationNode getFieldDefinition(String fieldName) {
        return type.getField(fieldName)
            .filter(field -> field.isStatic() == isStatic)
            .orElseThrow(() -> new NoSuchField(fieldName));
    }
}