2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 public final class StackToVariableMapper {
21 private static final String VAR_NAME_PREFIX = "stack";
23 private int stackSize;
24 private StringBuilder varNameBuilder;
26 private int maxStackSize;
28 public StackToVariableMapper() {
29 varNameBuilder = new StringBuilder(VAR_NAME_PREFIX);
32 public void reset(final int newStackSize) {
33 stackSize = newStackSize;
34 if (maxStackSize < stackSize) {
35 maxStackSize = stackSize;
39 public void push(final int numOfElements) {
40 stackSize += numOfElements;
41 if (maxStackSize < stackSize) {
42 maxStackSize = stackSize;
46 public String push() {
51 public void pop(final int numOfElements) {
52 if (numOfElements > stackSize) {
53 throw new IllegalStateException("Stack underflow");
55 stackSize -= numOfElements;
59 final String variableName = get(0);
64 public String get(final int indexFromTop) {
65 if (indexFromTop >= stackSize) {
66 throw new IllegalStateException("Stack underflow");
69 return constructVariableName(stackSize - indexFromTop - 1);
76 public String bottom() {
78 throw new IllegalStateException("Stack underflow");
81 return constructVariableName(0);
84 public int getMaxStackSize() {
88 public String constructVariableName(final int index) {
89 varNameBuilder.setLength(VAR_NAME_PREFIX.length());
90 varNameBuilder.append(index);
91 return varNameBuilder.toString();