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

net.sandius.rembulan.compiler.gen.SegmentedCode 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.gen;

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class SegmentedCode {

	private final List> segments;

	private final Map index;

	public static class LabelEntry {

		public final Label label;
		public final int segmentIdx;
		public final int idx;

		public LabelEntry(Label label, int segmentIdx, int idx) {
			this.label = Check.notNull(label);
			this.segmentIdx = segmentIdx;
			this.idx = idx;
		}

	}

	private SegmentedCode(List> segments, Map index) {
		this.segments = Check.notNull(segments);
		this.index = Check.notNull(index);
	}

	public static SegmentedCode singleton(Code code) {
		List> blocks = new ArrayList<>();

		List blks = new ArrayList<>();
		Iterator bit = code.blockIterator();
		while (bit.hasNext()) {
			blks.add(bit.next());
		}
		blocks.add(Collections.unmodifiableList(blks));

		return of(blocks);
	}

	public static SegmentedCode of(List> segments) {
		List> segs = Collections.unmodifiableList(segments);

		// build index
		Map index = new HashMap<>();
		for (int i = 0; i < segs.size(); i++) {
			int j = 0;
			for (BasicBlock blk : segs.get(i)) {
				index.put(blk.label(), new LabelEntry(blk.label(), i, j));
				j++;
			}
		}

		return new SegmentedCode(segs, Collections.unmodifiableMap(index));
	}

	public List> segments() {
		return segments;
	}

	public LabelEntry labelEntry(Label l) {
		LabelEntry le = index.get(Check.notNull(l));
		if (le == null) {
			throw new IllegalStateException("Label not found: " + l);
		}
		else {
			return le;
		}
	}

	public boolean isSingleton() {
		return segments.size() == 1;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy