001/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*- 002 * 003 * Copyright © 2024 microBean™. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 006 * the License. You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 011 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 012 * specific language governing permissions and limitations under the License. 013 */ 014package org.microbean.bean; 015 016import java.lang.constant.ClassDesc; 017import java.lang.constant.Constable; 018import java.lang.constant.ConstantDesc; 019import java.lang.constant.DynamicConstantDesc; 020import java.lang.constant.MethodHandleDesc; 021 022import java.util.List; 023import java.util.Optional; 024 025import javax.lang.model.type.TypeMirror; 026 027import org.microbean.constant.Constables; 028 029import org.microbean.qualifier.NamedAttributeMap; 030 031import static java.lang.constant.ConstantDescs.BSM_INVOKE; 032import static java.lang.constant.ConstantDescs.CD_List; 033 034import static org.microbean.lang.ConstantDescs.CD_TypeMirror; 035 036public final record AttributedType(TypeMirror type, List<NamedAttributeMap<?>> attributes) implements Constable { 037 038 public AttributedType { 039 type = switch (type.getKind()) { 040 case ARRAY, BOOLEAN, BYTE, CHAR, DECLARED, DOUBLE, FLOAT, INT, LONG, SHORT -> type; 041 case ERROR, EXECUTABLE, INTERSECTION, MODULE, NONE, NULL, OTHER, PACKAGE, TYPEVAR, UNION, VOID, WILDCARD -> 042 throw new IllegalArgumentException("type: " + type); 043 }; 044 attributes = List.copyOf(attributes); 045 } 046 047 public AttributedType(final TypeMirror type) { 048 this(type, List.of()); 049 } 050 051 /** 052 * Returns an {@link Optional} containing a {@link ConstantDesc} describing this {@link AttributedType}, or an 053 * {@linkplain Optional#isEmpty() empty <code>Optional</code>} if it could not be described. 054 * 055 * @return an {@link Optional} containing a {@link ConstantDesc} describing this {@link AttributedType}, or an 056 * {@linkplain Optional#isEmpty() empty <code>Optional</code>} if it could not be describe; never {@code null} 057 */ 058 @Override // Constable 059 public Optional<? extends ConstantDesc> describeConstable() { 060 return this.type() instanceof Constable t ? t.describeConstable() : Optional.<ConstantDesc>empty() 061 .flatMap(typeDesc -> Constables.describeConstable(this.attributes()) 062 .map(attributesDesc -> DynamicConstantDesc.of(BSM_INVOKE, 063 MethodHandleDesc.ofConstructor(ClassDesc.of(this.getClass().getName()), 064 CD_TypeMirror, 065 CD_List), 066 typeDesc, 067 attributesDesc))); 068 } 069 070}