software.amazon.awssdk.services.polly.endpoints.internal.Scope Maven / Gradle / Ivy
Show all versions of polly Show documentation
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package software.amazon.awssdk.services.polly.endpoints.internal;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public class Scope {
private final Deque> scope;
public Scope() {
this.scope = new ArrayDeque<>();
this.scope.push(new FatScope());
}
public void push() {
scope.push(new FatScope<>());
}
public void pop() {
scope.pop();
}
public void insert(String name, T value) {
this.insert(Identifier.of(name), value);
}
public void insert(Identifier name, T value) {
this.scope.getFirst().types().put(name, value);
}
public void insertFact(Expr name, T value) {
this.scope.getFirst().facts().put(name, value);
}
public U inScope(Supplier func) {
this.push();
try {
return func.get();
} finally {
this.pop();
}
}
@Override
public String toString() {
HashMap toPrint = new HashMap<>();
for (FatScope layer : scope) {
toPrint.putAll(layer.types());
}
return toPrint.toString();
}
/**
* Search the fact stack for an explicitly calculated value for [expr]
*
* Currently, this is only impacted by the `isSet` function which will record `T`, rather than {@code Option} for
* its arguments
*
* @param expr
* The expression to evaluate
* @return The value from the scope
*/
public Optional eval(Expr expr) {
for (FatScope layer : scope) {
if (layer.facts().containsKey(expr)) {
return Optional.of(layer.facts().get(expr));
}
}
return Optional.empty();
}
public T expectValue(Identifier name) {
for (FatScope layer : scope) {
if (layer.types().containsKey(name)) {
return layer.types().get(name);
}
}
throw new InnerParseError(String.format("No field named %s", name));
}
public Optional getValue(Identifier name) {
for (FatScope layer : scope) {
if (layer.types().containsKey(name)) {
return Optional.of(layer.types().get(name));
}
}
return Optional.empty();
}
}