All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sandius.rembulan.compiler.util.CodeUtils Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2016 Miroslav Janíček
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 net.sandius.rembulan.compiler.util;

import net.sandius.rembulan.compiler.ir.BasicBlock;
import net.sandius.rembulan.compiler.ir.Code;
import net.sandius.rembulan.compiler.ir.IRNode;
import net.sandius.rembulan.compiler.ir.Label;
import net.sandius.rembulan.util.Check;

import java.util.*;

public abstract class CodeUtils {

	private CodeUtils() {
		// not to be instantiated or extended
	}

	public static Iterator nodeIterator(Code code) {
		return new NodeIterator(code.blockIterator());
	}

	private static class NodeIterator implements Iterator {

		private final Iterator blockIterator;
		private Iterator blockNodeIterator;

		public NodeIterator(Iterator blockIterator) {
			this.blockIterator = Check.notNull(blockIterator);
			this.blockNodeIterator = null;
		}

		@Override
		public boolean hasNext() {
			if (blockNodeIterator != null && blockNodeIterator.hasNext()) {
				return true;
			}
			else {
				if (blockIterator.hasNext()) {
					blockNodeIterator = new BlockNodeIterator(blockIterator.next());
					return this.hasNext();
				}
				else {
					return false;
				}
			}
		}

		@Override
		public IRNode next() {
			if (!hasNext()) {
				throw new NoSuchElementException();
			}
			else {
				return blockNodeIterator.next();
			}
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}

	}

	private static class BlockNodeIterator implements Iterator {

		private final BasicBlock block;
		private int idx;

		public BlockNodeIterator(BasicBlock block) {
			this.block = Check.notNull(block);
			this.idx = 0;
		}

		@Override
		public boolean hasNext() {
			return idx <= block.body().size();
		}

		@Override
		public IRNode next() {
			int i = idx++;

			if (i == block.body().size()) {
				return block.end();
			}
			else if (i < block.body().size()) {
				return block.body().get(i);
			}
			else {
				throw new NoSuchElementException();
			}
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}

	}

	public static Iterable




© 2015 - 2024 Weber Informatics LLC | Privacy Policy