FieldDeclaration.java

package net.morimekta.providence.reflect.model;

import net.morimekta.providence.descriptor.PRequirement;
import net.morimekta.providence.reflect.parser.ThriftToken;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;

/**
 * Represents the declaration of a single field param or thrown exception.
 *
 * <pre>{@code
 * field ::= ({id} ':')? {optionality}? {type} {name} ('=' {defaultValue}) {annotations}?
 * }</pre>
 */
public class FieldDeclaration extends Declaration {
    private final ThriftToken       id;
    private final int               fieldId;
    private final ThriftToken       requirement;
    private final List<ThriftToken> type;
    private final List<ThriftToken> defaultValue;

    public FieldDeclaration(@Nullable String documentation,
                            @Nullable ThriftToken id,
                            int fieldId,
                            @Nullable ThriftToken requirement,
                            @Nonnull ThriftToken name,
                            @Nonnull List<ThriftToken> type,
                            @Nullable List<ThriftToken> defaultValue,
                            @Nullable List<AnnotationDeclaration> annotations) {
        super(documentation, name, annotations);
        this.id = id;
        this.fieldId = fieldId;
        this.requirement = requirement;
        this.type = type;
        this.defaultValue = defaultValue;
    }

    public int getId() {
        return fieldId;
    }

    public ThriftToken getIdToken() {
        return id;
    }

    @Nonnull
    public PRequirement getRequirement() {
        if (requirement != null) {
            switch (requirement.toString()) {
                case "required": return PRequirement.REQUIRED;
                case "optional": return PRequirement.OPTIONAL;
            }
        }
        return PRequirement.DEFAULT;
    }

    @Nullable
    public ThriftToken getRequirementToken() {
        return requirement;
    }

    public String getDefaultValue() {
        if (defaultValue != null) {
            return DeclarationUtil.toValueString(defaultValue);
        }
        return null;
    }

    @Nullable
    public List<ThriftToken> getDefaultValueTokens() {
        return defaultValue;
    }

    @Nonnull
    public String getType() {
        return DeclarationUtil.toTypeString(type);
    }

    @Nonnull
    public ThriftToken getTypeToken() {
        return DeclarationUtil.toTypeToken(type);
    }

    @Nonnull
    public List<ThriftToken> getTypeTokens() {
        return type;
    }
}