@SuppressWarnings("unchecked") public static ImmutableClassToInstanceMap<Annotation> annotationMap(Symbol symbol) { ImmutableClassToInstanceMap.Builder<Annotation> builder = ImmutableClassToInstanceMap.builder(); for (Compound compound : symbol.getAnnotationMirrors()) { Name qualifiedAnnotationType = ((TypeElement) compound.getAnnotationType().asElement()).getQualifiedName(); try { Class<? extends Annotation> annotationClazz = Class.forName(qualifiedAnnotationType.toString()).asSubclass(Annotation.class); builder.put((Class) annotationClazz, AnnotationProxyMaker.generateAnnotation(compound, annotationClazz)); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Unrecognized annotation type", e); } } return builder.build(); }
public static RefasterRule<?, ?> create(String qualifiedTemplateClass, Collection<? extends Template<?>> beforeTemplates, @Nullable Template<?> afterTemplate, ImmutableClassToInstanceMap<Annotation> annotations) { checkState(!beforeTemplates.isEmpty(), "No @BeforeTemplate was found in the specified class: %s", qualifiedTemplateClass); Class<?> templateType = beforeTemplates.iterator().next().getClass(); for (Template<?> beforeTemplate : beforeTemplates) { checkState(beforeTemplate.getClass().equals(templateType), "Expected all templates to be of type %s but found template of type %s in %s", templateType, beforeTemplate.getClass(), qualifiedTemplateClass); } if (afterTemplate != null) { checkState(afterTemplate.getClass().equals(templateType), "Expected all templates to be of type %s but found template of type %s in %s", templateType, afterTemplate.getClass(), qualifiedTemplateClass); } @SuppressWarnings("unchecked") RefasterRule<?, ?> result = new AutoValue_RefasterRule( qualifiedTemplateClass, ImmutableList.copyOf(beforeTemplates), afterTemplate, annotations); return result; }
@Test public void genericTemplate() { compile( "import java.util.List;", "class GenericTemplateExample {", " public <E> E example(List<E> list) {", " return list.get(0);", " }", "}"); assertEquals( ExpressionTemplate.create( ImmutableClassToInstanceMap.<Annotation>builder().build(), ImmutableList.of(UTypeVar.create("E")), ImmutableMap.of("list", UClassType.create("java.util.List", UTypeVar.create("E"))), UMethodInvocation.create( UMemberSelect.create( UFreeIdent.create("list"), "get", UMethodType.create(UTypeVar.create("E"), UPrimitiveType.INT)), ULiteral.intLit(0)), UTypeVar.create("E")), UTemplater.createTemplate(context, getMethodDeclaration("example"))); }
@Test public void recursiveTypes() { compile( "class RecursiveTypeExample {", " public <E extends Enum<E>> E example(E e) {", " return e;", " }", "}"); Template<?> template = UTemplater.createTemplate(context, getMethodDeclaration("example")); UTypeVar eVar = Iterables.getOnlyElement(template.typeVariables()); assertEquals( ExpressionTemplate.create( ImmutableClassToInstanceMap.<Annotation>builder().build(), ImmutableList.of(UTypeVar.create("E", UClassType.create("java.lang.Enum", eVar))), ImmutableMap.of("e", eVar), UFreeIdent.create("e"), eVar), template); }
@SuppressWarnings("unchecked") public static ImmutableClassToInstanceMap<Annotation> annotationMap(Symbol symbol) { ImmutableClassToInstanceMap.Builder<Annotation> builder = ImmutableClassToInstanceMap.builder(); for (Compound compound : symbol.getAnnotationMirrors()) { Name qualifiedAnnotationType = ((TypeElement) compound.getAnnotationType().asElement()).getQualifiedName(); try { Class<? extends Annotation> annotationClazz = Class.forName(qualifiedAnnotationType.toString()).asSubclass(Annotation.class); builder.put( (Class) annotationClazz, AnnotationProxyMaker.generateAnnotation(compound, annotationClazz)); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Unrecognized annotation type", e); } } return builder.build(); }
@Test public void recursiveTypes() { compile( "class RecursiveTypeExample {", " public <E extends Enum<E>> E example(E e) {", " return e;", " }", "}"); Template<?> template = UTemplater.createTemplate(context, getMethodDeclaration("example")); UTypeVar eVar = Iterables.getOnlyElement(template.templateTypeVariables()); assertEquals( ExpressionTemplate.create( ImmutableClassToInstanceMap.<Annotation>builder().build(), ImmutableList.of(UTypeVar.create("E", UClassType.create("java.lang.Enum", eVar))), ImmutableMap.of("e", eVar), UFreeIdent.create("e"), eVar), template); }
private <T extends IStrategoTerm> T putAttachments(T term, ImmutableClassToInstanceMap<Object> attachments) { Optional<TermOrigin> origin = TermOrigin.get(attachments); if(origin.isPresent()) { origin.get().put(term); } Optional<TermIndex> index = TermIndex.get(attachments); if(index.isPresent()) { term = StrategoTermIndices.put(index.get(), term, termFactory); } StrategoAnnotations annotations = attachments.getInstance(StrategoAnnotations.class); if(annotations != null) { @SuppressWarnings({ "unchecked" }) T result = (T) termFactory.copyAttachments(term, termFactory.annotateTerm(term, termFactory.makeList(annotations.getAnnotationList()))); term = result; } return term; }
public ITerm fromStratego(IStrategoTerm term) { ImmutableClassToInstanceMap<Object> attachments = getAttachments(term); ITerm rawTerm = match(term, StrategoTerms.<ITerm>cases( // @formatter:off appl -> TB.newAppl(appl.getConstructor().getName(), Arrays.asList(appl.getAllSubterms()).stream().map(this::fromStratego).collect(Collectors.toList())), tuple -> TB.newTuple(Arrays.asList(tuple.getAllSubterms()).stream().map(this::fromStratego).collect(Collectors.toList())), this::fromStrategoList, integer -> TB.newInt(integer.intValue()), real -> { throw new IllegalArgumentException("Real values are not supported."); }, string -> TB.newString(string.stringValue()) // @formatter:on )).withAttachments(attachments); return M.<ITerm>cases( // @formatter:off M.appl2(VAR_CTOR, M.stringValue(), M.stringValue(), (v, resource, name) -> TB.newVar(resource, name).withAttachments(v.getAttachments())), M.appl1(LIST_CTOR, M.list(), (t,xs) -> TB.newList(xs).withAttachments(t.getAttachments())), M.appl2(LISTTAIL_CTOR, M.list(), M.term(), (t,xs,ys) -> TB.newListTail(xs, (IListTerm) ys).withAttachments(t.getAttachments())) // @formatter:on ).match(rawTerm).orElse(rawTerm); }
public void start() { checkState(controllerRoot == null, "Binding Aware Broker was already started."); LOG.info("Starting Binding Aware Broker: {}", identifier); controllerRoot = new RootSalInstance(getRpcProviderRegistry(), getNotificationBroker()); final ImmutableClassToInstanceMap.Builder<BindingAwareService> consBuilder = ImmutableClassToInstanceMap .builder(); consBuilder.put(NotificationService.class, getRoot()); consBuilder.put(RpcConsumerRegistry.class, getRoot()); if (dataBroker != null) { consBuilder.put(DataBroker.class, dataBroker); } consBuilder.put(MountPointService.class, mountService); supportedConsumerServices = consBuilder.build(); final ImmutableClassToInstanceMap.Builder<BindingAwareService> provBuilder = ImmutableClassToInstanceMap .builder(); provBuilder.putAll(supportedConsumerServices).put(NotificationProviderService.class, getRoot()) .put(RpcProviderRegistry.class, getRoot()); if (notificationPublishService != null) { provBuilder.put(NotificationPublishService.class, notificationPublishService); } supportedProviderServices = provBuilder.build(); }
/** * Returns a copy of this context with the map of services added. * <p> * If any services are provided that are already registered, the service registry * will be updated with the provided services. * * @param services a map of services objects keyed by their class, not null * @return an updated service context */ public ServiceContext with(Map<Class<?>, Object> services) { // We have to calculate which of the original objects need to be // retained as ImmutableMap.Builder won't allow a key to be put // more than once ArgumentChecker.noNulls(services, "services"); Map<Class<?>, Object> unchanged = Maps.difference(_services, services).entriesOnlyOnLeft(); ImmutableClassToInstanceMap<Object> combined = ImmutableClassToInstanceMap.builder() .putAll(services) .putAll(unchanged) .build(); return new ServiceContext(combined); }
/** * Creates a class to instance map, from the given coordinates. The map will contain the classes of the coordinates * as keys and the coordinates themselves as values. Duplicate keys (dimensions) are not allowed and will result in * an {@link IllegalArgumentException}. * * @param coordinates the coordinates to be added to the map * @return an immutable map from dimensions (coordinate classes) to coordinate * @throws IllegalArgumentException if more than one coordinate per dimension are provided * @deprecated */ @Deprecated public static <C> ClassToInstanceMap<C> mapOf(Iterable<? extends C> coordinates) { ImmutableClassToInstanceMap.Builder<C> coordinateBuilder = ImmutableClassToInstanceMap.builder(); for (C coordinate : coordinates) { @SuppressWarnings("unchecked") Class<C> coordinateClass = (Class<C>) coordinate.getClass(); coordinateBuilder.put(coordinateClass, coordinate); } return coordinateBuilder.build(); }
private <T1 extends Option<T1>> ImmutableOptionRegistry(Collection<T> options) { /* * we first have to create a mutable map, because the collection might contain options of the same class, where * later ones will override previous ones. This would not be allowed by the builder of the immutable map. */ ClassToInstanceMap<T> mutableOptions = MutableClassToInstanceMap.create(); addToMap(mutableOptions, options); this.options = ImmutableClassToInstanceMap.copyOf(mutableOptions); }
public static BlockTemplate create( Iterable<UTypeVar> typeVariables, Map<String, ? extends UType> expressionArgumentTypes, UStatement... templateStatements) { return create( ImmutableClassToInstanceMap.<Annotation>builder().build(), typeVariables, expressionArgumentTypes, ImmutableList.copyOf(templateStatements)); }
public static BlockTemplate create( ImmutableClassToInstanceMap<Annotation> annotations, Iterable<UTypeVar> typeVariables, Map<String, ? extends UType> expressionArgumentTypes, Iterable<? extends UStatement> templateStatements) { return new AutoValue_BlockTemplate( annotations, ImmutableList.copyOf(typeVariables), ImmutableMap.copyOf(expressionArgumentTypes), ImmutableList.copyOf(templateStatements)); }
@SuppressWarnings("unchecked") @Override public ImmutableClassToInstanceMap<Annotation> annotations() { ImmutableClassToInstanceMap.Builder<Annotation> builder = ImmutableClassToInstanceMap.builder(); for (Annotation annotation : checker().getClass().getDeclaredAnnotations()) { builder.put((Class) annotation.annotationType(), annotation); } return builder.build(); }
public static ExpressionTemplate create( Map<String, ? extends UType> expressionArgumentTypes, UExpression expression, UType returnType) { return create( ImmutableClassToInstanceMap.<Annotation>builder().build(), ImmutableList.<UTypeVar>of(), expressionArgumentTypes, expression, returnType); }
public static ExpressionTemplate create( ImmutableClassToInstanceMap<Annotation> annotations, Iterable<UTypeVar> typeVariables, Map<String, ? extends UType> expressionArgumentTypes, UExpression expression, UType returnType) { return new AutoValue_ExpressionTemplate( annotations, ImmutableList.copyOf(typeVariables), ImmutableMap.copyOf(expressionArgumentTypes), expression, returnType); }
@Test public void genericMethodInvocation() { compile( "import java.util.Collections;", "import java.util.List;", "class GenericTemplateExample {", " public <E> List<E> example(List<E> list) {", " return Collections.unmodifiableList(list);", " }", "}"); UTypeVar tVar = UTypeVar.create("T"); UTypeVar eVar = UTypeVar.create("E"); assertEquals( ExpressionTemplate.create( ImmutableClassToInstanceMap.<Annotation>builder().build(), ImmutableList.of(eVar), ImmutableMap.of("list", UClassType.create("java.util.List", eVar)), UMethodInvocation.create( UStaticIdent.create( "java.util.Collections", "unmodifiableList", UForAll.create( ImmutableList.of(tVar), UMethodType.create( UClassType.create("java.util.List", tVar), UClassType.create( "java.util.List", UWildcardType.create(BoundKind.EXTENDS, tVar))))), UFreeIdent.create("list")), UClassType.create("java.util.List", eVar)), UTemplater.createTemplate(context, getMethodDeclaration("example"))); }
@Test public void recursiveType() { /* * Template: * <E extends Enum<E>> String example(E e) { * return e.name(); * } */ UTypeVar eTypeVar = UTypeVar.create("E"); eTypeVar.setUpperBound(UClassType.create("java.lang.Enum", eTypeVar)); ExpressionTemplate template = ExpressionTemplate.create( ImmutableClassToInstanceMap.<Annotation>builder().build(), ImmutableList.of(eTypeVar), ImmutableMap.of("value", eTypeVar), UMethodInvocation.create( UMemberSelect.create(UFreeIdent.create("value"), "name", UMethodType.create(UClassType.create("java.lang.String")))), UClassType.create("java.lang.String")); compile( "import java.math.RoundingMode;", "class RecursiveTypeExample {", " public void example() {", " System.out.println(RoundingMode.FLOOR.name());", " }", "}"); expectMatches(template, Match.create(ImmutableMap.of( "value", "RoundingMode.FLOOR", "E", "java.math.RoundingMode"))); }
public static RefasterRule<?, ?> create( String qualifiedTemplateClass, Collection<? extends Template<?>> beforeTemplates, Collection<? extends Template<?>> afterTemplates) { return create( qualifiedTemplateClass, ImmutableList.<UTypeVar>of(), beforeTemplates, afterTemplates, ImmutableClassToInstanceMap.<Annotation>builder().build()); }
public static RefasterRule<?, ?> create( String qualifiedTemplateClass, Iterable<UTypeVar> typeVariables, Collection<? extends Template<?>> beforeTemplates, Collection<? extends Template<?>> afterTemplates, ImmutableClassToInstanceMap<Annotation> annotations) { checkState( !beforeTemplates.isEmpty(), "No @BeforeTemplate was found in the specified class: %s", qualifiedTemplateClass); Class<?> templateType = beforeTemplates.iterator().next().getClass(); for (Template<?> beforeTemplate : beforeTemplates) { checkState( beforeTemplate.getClass().equals(templateType), "Expected all templates to be of type %s but found template of type %s in %s", templateType, beforeTemplate.getClass(), qualifiedTemplateClass); } for (Template<?> afterTemplate : afterTemplates) { checkState( afterTemplate.getClass().equals(templateType), "Expected all templates to be of type %s but found template of type %s in %s", templateType, afterTemplate.getClass(), qualifiedTemplateClass); } @SuppressWarnings({"unchecked", "rawtypes"}) RefasterRule<?, ?> result = new AutoValue_RefasterRule( qualifiedTemplateClass, ImmutableList.copyOf(typeVariables), ImmutableList.copyOf(beforeTemplates), ImmutableList.copyOf(afterTemplates), annotations); return result; }
static PlaceholderMethod create( CharSequence name, UType returnType, ImmutableMap<UVariableDecl, ImmutableClassToInstanceMap<Annotation>> parameters, ClassToInstanceMap<Annotation> annotations) { final boolean allowsIdentity = annotations.getInstance(Placeholder.class).allowsIdentity(); final Class<? extends Matcher<? super ExpressionTree>> matchesClass = annotations.containsKey(Matches.class) ? UTemplater.getValue(annotations.getInstance(Matches.class)) : null; final Class<? extends Matcher<? super ExpressionTree>> notMatchesClass = annotations.containsKey(NotMatches.class) ? UTemplater.getValue(annotations.getInstance(NotMatches.class)) : null; final Predicate<Tree.Kind> allowedKinds = annotations.containsKey(OfKind.class) ? Predicates.<Tree.Kind>in(Arrays.asList(annotations.getInstance(OfKind.class).value())) : Predicates.<Tree.Kind>alwaysTrue(); class PlaceholderMatcher implements Serializable, Matcher<ExpressionTree> { @Override public boolean matches(ExpressionTree t, VisitorState state) { try { return (allowsIdentity || !(t instanceof PlaceholderParamIdent)) && (matchesClass == null || matchesClass.newInstance().matches(t, state)) && (notMatchesClass == null || !notMatchesClass.newInstance().matches(t, state)) && allowedKinds.apply(t.getKind()); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } } return new AutoValue_PlaceholderMethod( StringName.of(name), returnType, parameters, new PlaceholderMatcher(), ImmutableClassToInstanceMap.<Annotation, Annotation>copyOf(annotations)); }
/** Parameters which must be referenced in any tree matched to this placeholder. */ Set<UVariableDecl> requiredParameters() { return Maps.filterValues( annotatedParameters(), (ImmutableClassToInstanceMap<Annotation> annotations) -> !annotations.containsKey(MayOptionallyUse.class)) .keySet(); }
@Test public void recursiveType() { /* * Template: * <E extends Enum<E>> String example(E e) { * return e.name(); * } */ UTypeVar eTypeVar = UTypeVar.create("E"); eTypeVar.setUpperBound(UClassType.create("java.lang.Enum", eTypeVar)); ExpressionTemplate template = ExpressionTemplate.create( ImmutableClassToInstanceMap.<Annotation>builder().build(), ImmutableList.of(eTypeVar), ImmutableMap.of("value", eTypeVar), UMethodInvocation.create( UMemberSelect.create( UFreeIdent.create("value"), "name", UMethodType.create(UClassType.create("java.lang.String")))), UClassType.create("java.lang.String")); compile( "import java.math.RoundingMode;", "class RecursiveTypeExample {", " public void example() {", " System.out.println(RoundingMode.FLOOR.name());", " }", "}"); expectMatches( template, Match.create( ImmutableMap.of( "value", "RoundingMode.FLOOR", "E", "java.math.RoundingMode"))); }