package org.luaj.vm2.compiler;

import org.luaj.vm2.ast.Chunk;
import org.luaj.vm2.ast.Exp;
import org.luaj.vm2.ast.NameResolver;
import org.luaj.vm2.ast.Stat;
import org.luaj.vm2.ast.Variable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.compiler.CompilerUnitTests;
import org.luaj.vm2.parser.LuaParser;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;

public class LuaParserTests extends CompilerUnitTests {

    protected void setUp() throws Exception {
        super.setUp();
        LuaValue.valueOf(true);
    }
	
	protected void doTest(String file) {
		try {
			if (!hasFixtures()) {
				System.err.println("Skipping parser fixture test; missing resource bundle for: " + file);
				return;
			}
			InputStream is = inputStreamOfFile(file);
			Reader r = new InputStreamReader(is, "ISO-8859-1");
			LuaParser parser = new LuaParser(r);
			parser.Chunk();
		} catch (Exception e) {
			fail(e.getMessage());
			e.printStackTrace();
		}
	}

	public void testContinueParses() {
		try {
			Reader r = new StringReader("while true do continue end");
			LuaParser parser = new LuaParser(r);
			parser.Chunk();
		} catch (Exception e) {
			fail(e.getMessage());
		}
	}

	public void testMethodDefinitionInjectsHiddenSelf() {
		try {
			Reader r = new StringReader("function t:f() return self end");
			LuaParser parser = new LuaParser(r);
			Chunk chunk = parser.Chunk();
			new NameResolver().visit(chunk);

			Stat.FuncDef stat = (Stat.FuncDef) chunk.block.stats.get(0);
			Variable self = stat.body.scope.namedVariables.get("self");
			assertNotNull(self);
			assertTrue(self.isLocal());

			Stat.Return ret = (Stat.Return) stat.body.block.stats.get(0);
			Exp.NameExp selfRef = (Exp.NameExp) ret.values.get(0);
			assertSame(self, selfRef.name.variable);
		} catch (Exception e) {
			fail(e.getMessage());
		}
	}
}
