package aquarius.combinator.expression;

import aquarius.combinator.ExpressionVisitor;
import aquarius.combinator.ParserContext;
import aquarius.runtime.AquariusInputStream;
import aquarius.runtime.Result;
import static aquarius.runtime.Result.*;

/**
* try to match the expression. return matched result or null
* -> expr ?
* @author skgchxngsxyz-opensuse
 * @param <E>
*
*/
public class Optional<E> implements ParsingExpression<E> {
	private final ParsingExpression<E> expr;

	public Optional(ParsingExpression<E> expr) {
		this.expr = expr;
	}

	public ParsingExpression<E> getExpr() {
		return this.expr;
	}

	@Override
	public String toString() {
		return this.expr.toString() + "?";
	}

	@Override
	public Result<E> parse(ParserContext context) {
		AquariusInputStream input = context.getInput();
		int pos = input.getPosition();

		Result<E> result = this.expr.parse(context);
		if(result.isFailure()) {
			input.setPosition(pos);	// roll back position
			return empty();
		}
		return result;
	}

	@Override
	public <T> T accept(ExpressionVisitor<T> visitor) {
		return visitor.visitOptional(this);
	}
}
@@ -423,17 +423,37 @@
 ression%3C
-E
+java.util.Optional%3CE%3E
 %3E %7B%0A%09pri
@@ -732,17 +732,37 @@
  Result%3C
-E
+java.util.Optional%3CE%3E
 %3E parse(
@@ -1007,15 +1007,38 @@
 urn 
+of(java.util.Optional.
 empty()
+)
 ;%0A%09%09
@@ -1048,22 +1048,55 @@
 %09return 
-result
+of(java.util.Optional.of(result.get()))
 ;%0A%09%7D%0A%0A%09@

fix Optional