SourceDV.java

/*
 * SPDX-FileCopyrightText: 2025 kaumei.io
 * SPDX-License-Identifier: Apache-2.0
 */
package io.kaumei.jdbc.anno.store;

import io.kaumei.jdbc.anno.ctx.Context;
import io.kaumei.jdbc.anno.ctx.JavaModelToString;

import javax.lang.model.element.*;

import static io.kaumei.jdbc.anno.ctx.JavaModelToString.recordComponentElement;
import static io.kaumei.jdbc.anno.ctx.JavaModelToString.typeElement;

public record SourceDV(String value) {

    public static SourceDV empty() {
        return new SourceDV("unknown");
    }

    public static SourceDV generic(String value) {
        return new SourceDV(value);
    }

    public static SourceDV converter(Context ctx, Element element) {
        var sb = new StringBuilder();
        if (element instanceof VariableElement va) {
            sb.append(JavaModelToString.variableElement(va));
        } else if (element instanceof ExecutableElement ee) {
            sb.append(JavaModelToString.executableElement(ee));
        } else if (element instanceof TypeElement te) {
            sb.append(typeElement(te));
        } else if (element instanceof RecordComponentElement rce) {
            sb.append(recordComponentElement(rce));
        } else {
            throw new IllegalArgumentException("Unknown " + element.getClass().getCanonicalName());
        }
        var pos = ctx.sourcePosition(element);
        if (pos != null) {
            sb.append(' ').append(pos);
        }
        return new SourceDV(sb.toString());
    }

    // ------------------------------------------------------------------------

    @Override
    public String toString() {
        return value;
    }

}