#! /usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2008 (ita)

# test for looking at dependencies with gcc

VERSION='0.0.1'
APPNAME='cc_test'
top = '.'
out = 'build'

import Utils
import preproc
from preproc import NUM, OP, IDENT

def configure(conf):
	conf.check_tool('gcc')

def build(bld):

	defs = {
		'm1'   : "m1 9 + 9",
		'fun0' : "fun0(x, y) x y",
		'fun1' : "fun1(x, y) x ## y",
		'fun2' : "fun2(x) #x",
		'fun3' : "fun3(x, y) x * y",
		'fun4' : "fun4(x) fun2(x)",
		'fun5' : "fun5(x, y, z) x ## y ## z",
		'fun6' : "fun6(x, y) <x.y>",
		'fun7' : "fun() 7",
	}

	def test(x, result, fun=preproc.reduce_tokens):
		toks = preproc.tokenize(x)
		preproc.reduce_tokens(toks, defs, [])
		ret = preproc.stringize(toks)

		if ret == result:
			color = "GREEN"
		else:
			color = "RED"
		Utils.pprint(color, "%s\t\t%r" % (ret, toks))

	test("1 + m1 + 1", "1+9+9+1")
	test("1 + fun0(1, +) 1", "1+1+1")
	test("fun2(mmm)", "mmm")
	test("m1", "9+9")
	test("fun2(m1)", "m1")
	test("fun4(m1)", "9+9")
	test("fun1(m, m)", "mm")
	test("fun5(a, b, c)", "abc")
	test("fun1(>, =)", ">=")
	test("fun1(a, 12)", "a12")
	test("fun5(a, _, 12)", "a_12")
	test("fun6(math, h)", "<math.h>")

	def test(x, result):
		ret = preproc.extract_include(x, defs)
		if ret == result:
			color = "GREEN"
		else:
			color = "RED"
		Utils.pprint(color, "%s" % (ret))

	test("fun6(math, h)", "math.h")

	def test(x, result):
		toks = preproc.tokenize(x)
		preproc.reduce_tokens(toks, defs, [])
		(_, ret) = preproc.reduce_eval(toks)
		if int(ret) == result:
			color = "GREEN"
		else:
			color = "RED"
		Utils.pprint(color, "%s\t\t%r" % (ret, toks))

	test("1+1", 2)
	test("1-1", 0)
	test("1?77:0", 77)
	test("0?0:88", 88)
	test("1+2*3", 7)
	test("1*2+3", 5)

	test("7*m1*3", 90)
	test("m1*3", 36)
	test("defined m1", 1)
	test("defined(m1)", 1)
	test("defined inex", 0)
	test("defined(inex)", 0)
	test("fun7()", 7)

	test("0&&2<3", 0)
	test("(5>1)*6", 6)
	test("1,2,3*9,9", 9)

	test("0x52 > 02", 1)

	# lazy evaluation
	test("defined(foo) && foo > 2", 0)
	test("defined(m1) && m1 > 20", 0)
	test("defined(m1) || m1 > 20", 1)

	# undefined macros -> 0
	test("not_possibly_defined || another", 0)

	test("1+2+((3+4)+5)+6==(6*7)/2==1*-1*-1", 1)

	return
	test("1?1,(0?5:9):3,4", 0) # <- invalid expression



