view src/nabble/naml/namespaces/RegexNamespace.java @ 0:7ecd1a4ef557

add content
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 21 Mar 2019 19:15:52 -0600
parents
children
line wrap: on
line source

package nabble.naml.namespaces;

import nabble.naml.compiler.Command;
import nabble.naml.compiler.CommandSpec;
import nabble.naml.compiler.IPrintWriter;
import nabble.naml.compiler.Interpreter;
import nabble.naml.compiler.Namespace;

import java.util.regex.Matcher;


@Namespace (
	name = "regex",
	global = true
)
public class RegexNamespace extends Sequence {
	private final Matcher matcher;
	private final String source;  // only for debugging
	private boolean started = false;
	private boolean isFound = false;

	public RegexNamespace(Matcher matcher,String source) {
		this.matcher = matcher;
		this.source = source;
	}

	private boolean find() {
		started = true;
		return isFound = matcher.find();
	}

	@Command public void find(IPrintWriter out,Interpreter interp) {
		out.print( find() );
	}

	@Command public void matches(IPrintWriter out,Interpreter interp) {
		out.print( matcher.matches() );
	}

	public static final CommandSpec found = new CommandSpec.Builder()
		.optionalParameters("group")
		.build()
	;

	@Command public void found(IPrintWriter out,Interpreter interp) {
		String group = interp.getArgString("group");
		out.print( group==null ? matcher.group() : matcher.group(Integer.parseInt(group)) );
	}

	@Command public void has_more_elements(IPrintWriter out,Interpreter interp) {
		if( !started ) {
			out.print( matcher.find() );
			matcher.reset();
		} else if( isFound ) {
			int start = matcher.start();
			out.print( matcher.find() );
			if( !matcher.find(start) )
				throw new RuntimeException();
		} else {
			out.print( false );
		}
	}

	@Command public void next_element(IPrintWriter out,Interpreter interp) {
		out.print( find() );
	}

	@Command public void current_element(IPrintWriter out,Interpreter interp) {
		out.print( matcher.group() );
	}

}