Example #1
0
    def testReadonly(self):
        source = """
class public Atom
	readonly N: int
	readonly mass: double
	constructor
		param init N
		param init mass
func public main
	var H: Atom = Atom(1, 1.008)
	var O: Atom = Atom(8, 15.999)
	var waterMass: double = H.mass * 2 + O.mass
		"""
        module = WppCore.createMemModule(source, 'readonly.fake')
        Atom = module.dictionary['Atom']
        mass = Atom.dictionary['mass']
        self.assertEqual(mass.type, 'Readonly')
        self.assertIn('public', mass.attrs)
        self.assertEqual(mass.getLocalType().exportString(), 'double')
        outContext = OutContextMemoryStream()
        module.export(outContext)
        self.assertEqual(str(outContext), source.strip())
    def testUnOp(self):
        source = """
var const public a: int = -20
var const public b: int = -a
var const public c: int = ~b
var const public d: bool = !c
var const public e: int = -a * -b
var const public f: int = -(a & b)
		"""
        expected = """
export const a: number = -20;
export const b: number = -a;
export const c: number = ~b;
export const d: boolean = !c;
export const e: number = -a * -b;
export const f: number = -(a & b);
		"""
        srcModule = WppCore.createMemModule(source, 'unOp.fake')
        dstModule = srcModule.cloneRoot(TsCore())
        outContext = OutContextMemoryStream()
        dstModule.export(outContext)
        self.assertEqual(str(outContext), dstModule.strPack(expected))
	def testAdd(self):
		source = """
func myAdd: double
	param x: double
	param y: double
	x + y
		"""
		module = WppCore.createMemModule(source, 'root.fake')
		# Check isAutoChange for last command in block
		myAddOver = module.dictionary['myAdd']
		self.assertEqual(myAddOver.type, 'Overloads')
		myAddFn = myAddOver.items[0]
		self.assertEqual(myAddFn.type, 'Func')
		block = myAddFn.getBody()
		self.assertEqual(block.type, 'Block')
		lastCmd = block.items[-1]
		self.assertEqual(lastCmd.type, 'Return')
		self.assertTrue(lastCmd.isAutoChange)

		outContext = OutContextMemoryStream()
		module.export(outContext)
		self.assertEqual(str(outContext), module.strPack(source))
Example #4
0
    def testCall(self):
        source = """
func public func1: int
	param x: int
	x * 5
func public func2: int
	param a: int
	param b: int
	func1(a) + func1(b)
		"""
        srcModule = WppCore.createMemModule(source, 'binOp.fake')
        dstModule = srcModule.cloneRoot(PyCore())
        outStream = OutContextMemoryStream()
        dstModule.export(outStream)
        expected = """
def func1(x):
	return x * 5

def func2(a, b):
	return func1(a) + func1(b)
		"""
        self.assertEqual(str(outStream), WppCore.strPack(expected))
	def testMapValues(self):
		""" Test for construction: for value in map.values() """
		source = """
func public sumValues: double
	param map: const Map String, double
	var result: double = 0.0
	foreach map => var value
		result += value
	result
		"""
		expected = """
def sumValues(map):
	result = 0.0
	for value in map.values():
		result += value
	return result
		"""
		srcModule = WppCore.createMemModule(source, 'values.fake')
		dstModule = srcModule.cloneRoot(PyCore())
		outContext = OutContextMemoryStream()
		dstModule.export(outContext)
		self.assertEqual(str(outContext), expected.strip())
Example #6
0
    def testLocationFind(self):
        source = """
func brackets: String
	param s: String
	"(" + s + ")"
func public main
	var r: String = brackets("Hello")
		"""
        module = WppCore.createMemModule(source, 'brackets.fake')
        main = module.dictionary['main'].items[0]
        self.assertEqual(main.type, 'Func')
        self.assertIsNotNone(main.location)
        r = main.getBody().items[0]
        self.assertEqual(r.type, 'Var')
        self.assertIsNotNone(r.location)
        c = r.getValueTaxon()
        self.assertEqual(c.type, 'Call')
        self.assertIsNone(c.location)
        self.assertEqual(c.getLocation(), r.location)
        p = c.getArguments()[0]
        self.assertEqual(p.type, 'Const')
        self.assertEqual(p.getLocation(), r.location)
	def testMatch(self):
		source = """
class public First

class public Second

var first: First
var firstA: First
var second: Second
"""
		module = WppCore.createMemModule(source, 'simple.wpp')
		First = module.findItem('First')
		Second = module.findItem('Second')
		first = module.findItem('first')
		firstA = module.findItem('firstA')
		second = module.findItem('second')
		self.assertEqual(QuasiType.matchTaxons(first, First), ('exact', None))
		self.assertEqual(QuasiType.matchTaxons(firstA, First), ('exact', None))
		self.assertEqual(QuasiType.matchTaxons(first, firstA), ('exact', None))
		self.assertEqual(QuasiType.matchTaxons(firstA, first), ('exact', None))
		self.assertEqual(QuasiType.matchTaxons(second, Second), ('exact', None))
		self.assertEqual(QuasiType.matchTaxons(first, Second), (None, 'Cannot convert from "class Second" to "var first: First"'))
    def testIdExpr(self):
        source = """
class IdExpr
	field myField: int = 256
	method someFunc
		param myParam: String
		var const v1: int = myField
		var const v2: String = myParam
		"""
        expected = """
export class IdExpr {
	private myField: number = 256;
	public someFunc(myParam: string) {
		const v1: number = this.myField;
		const v2: string = myParam;
	}
}
		"""
        srcModule = WppCore.createMemModule(source, 'IdExpr.fake')
        dstModule = srcModule.cloneRoot(TsCore())
        outContext = OutContextMemoryStream()
        dstModule.export(outContext)
        self.assertEqual(str(outContext), WppCore.strPack(expected))
Example #9
0
	def testFindUp(self):
		source = """
func public funcA
	var const first: bool = true
	var const second: int = 22
	var const third: double = 1.23
"""
		module = WppCore.createMemModule(source, 'findUp.wpp')
		funcA = module.findItem('funcA')
		body = funcA.getBody()
		self.assertEqual(len(body.items), 3)
		# Из второй строки можно найти первую
		res = body.items[1].getValueTaxon().startFindUp('first')
		self.assertEqual(res.name, 'first')
		# Из второй строки нельзя найти третью
		res = body.items[1].getValueTaxon().startFindUp('third')
		self.assertIsNone(res)
		# Из второй строки нельзя найти вторую. Потому что выражение используется раньше, чем будет объявлена переменная
		res = body.items[1].getValueTaxon().startFindUp('second')
		self.assertIsNone(res)
		# А из третьей можно найти вторую
		res = body.items[2].getValueTaxon().startFindUp('second')
		self.assertEqual(res.name, 'second')
    def testAutoInit(self):
        source = """
class public A
	field a: int
	field b: double
	constructor
		param init a
		param init b = 1.0
		"""
        module = WppCore.createMemModule(source, 'A.fake')
        classA = module.dictionary['A']
        over = classA.findConstructor()
        self.assertIsNotNone(over)
        c = over.items[0]
        a = c.dictionary['a']
        self.assertIn('init', a.attrs)
        self.assertEqual(classA.dictionary['a'], a.refs['field'])
        autoInits = c.getAutoInits()
        self.assertEqual(len(autoInits), 2)

        outCtx = OutContextMemory()
        classA.export(outCtx)
        self.assertEqual(str(outCtx), source.strip())
Example #11
0
    def testNew(self):
        source = """
class Hello
	field count: int
	constructor
		param init count
	method static create22: Hello
		Hello(22)
		"""
        module = WppCore.createMemModule(source, 'testNew.fake')
        classHello = module.dictionary['Hello']
        overCreate22 = classHello.dictionary['create22']
        create22 = overCreate22.items[0]
        self.assertEqual(create22.type, 'Method')
        self.assertEqual(create22.name, 'create22')
        cmd = create22.getBody().items[-1]
        self.assertEqual(cmd.type, 'Return')
        expr = cmd.getExpression()
        caller = expr.getCaller()
        self.assertEqual(caller.type, 'IdExpr')
        callerDecl = caller.getDeclaration()
        self.assertEqual(callerDecl, classHello)
        self.assertEqual(expr.type, 'New')
Example #12
0
    def testCheckShortStatic(self):
        source = """
class public MyClass
	field static inst: MyClass
	method static getInst: MyClass
		inst
	method setInst
		MyClass.inst = this
	method useInstShort: MyClass
		getInst()
	method useInstFull: MyClass
		MyClass.getInst()
		"""
        module = WppCore.createMemModule(source, 'MyClass.fake')
        myClass = module.dictionary['MyClass']
        useInstShort = myClass.dictionary['useInstShort'].items[0]
        cmd = useInstShort.getBody().items[0]
        self.assertEqual(cmd.type, 'Return')
        call = cmd.getExpression()
        self.assertEqual(call.type, 'Call')
        id = call.getCaller()
        self.assertEqual(id.type, 'IdExpr')
        res = id.checkShortStatic()
        self.assertEqual(res, myClass)

        useInstFull = myClass.dictionary['useInstFull'].items[0]
        cmd = useInstFull.getBody().items[0]
        self.assertEqual(cmd.type, 'Return')
        call = cmd.getExpression()
        self.assertEqual(call.type, 'Call')
        binOp = call.getCaller()
        self.assertEqual(binOp.type, 'BinOp')
        id = binOp.getLeft()
        self.assertEqual(id.type, 'IdExpr')
        res = id.checkShortStatic()
        self.assertIsNone(res)
	def testMapFull(self):
		""" Test for construction: for key, value in map.items() """
		source = """
func public toList: Array String
	param map: const Map String, String
	var result: Array String
	foreach map => var value => var key
		result.push(key + ":" + value)
	result
		"""
		expected = """
def toList(map):
	result = []
	for key, value in map.items():
		result.append(key + ':' + value)
	return result
		"""
		srcModule = WppCore.createMemModule(source, 'foreach.fake')
		dstModule = srcModule.cloneRoot(PyCore())

		toListOver = dstModule.dictionary['toList']
		self.assertEqual(toListOver.type, 'Overloads')
		toList = toListOver.items[0]
		self.assertEqual(toList.type, 'Func')
		cmdFor = toList.getBody().items[1]
		self.assertEqual(cmdFor.type, 'Foreach')
		cmdCall = cmdFor.getBody().items[0]
		self.assertEqual(cmdCall.type, 'Call')
		caller = cmdCall.getCaller()
		self.assertEqual(caller.type, 'BinOp')
		push = caller.getRight()
		self.assertEqual(push.type, 'FieldExpr')

		outContext = OutContextMemoryStream()
		dstModule.export(outContext)
		self.assertEqual(str(outContext), expected.strip())
Example #14
0
	def testCheckThis(self):
		source = """
class A
	method first: String
		"Hello, "
	method second: String
		param name: String
		first() + name
		"""
		expected = """
export class A {
	public first(): string {
		return 'Hello, ';
	}
	public second(name: string): string {
		return this.first() + name;
	}
}
		"""
		srcModule = WppCore.createMemModule(source, 'simple.fake')
		dstModule = srcModule.cloneRoot(TsCore())
		outContext = OutContextMemoryStream()
		dstModule.export(outContext)
		self.assertEqual(str(outContext), expected.strip())
Example #15
0
    def testField(self):
        source = """
class public Field
	field public abcd: int
	method public copy
		param source: Field
		abcd = source.abcd
		"""
        expected = """
class Field:
	__slots__ = ('abcd')
	def __init__(self):
		self.abcd = 0
	def copy(self, source):
		self.abcd = source.abcd
		"""
        srcModule = WppCore.createMemModule(source, 'field.fake')
        dstModule = srcModule.cloneRoot(PyCore())
        cls = dstModule.dictionary['Field']
        over = cls.dictionary['copy']
        method = over.items[0]
        eq = method.getBody().items[0]
        self.assertEqual(eq.type, 'BinOp')
        self.assertEqual(eq.getLeft().type, 'IdExpr')
        r = eq.getRight()
        self.assertEqual(r.type, 'BinOp')
        self.assertEqual(r.opCode, '.')
        self.assertEqual(r.getLeft().type, 'IdExpr')
        self.assertEqual(r.getLeft().id, 'source')
        f = r.getRight()
        self.assertEqual(f.id, 'abcd')
        self.assertEqual(f.type, 'FieldExpr')

        outStream = OutContextMemoryStream()
        dstModule.export(outStream)
        self.assertEqual(str(outStream), WppCore.strPack(expected))
	def testRight(self):
		source = """
class simple Point
	field public x: double
	field public y: double
	constructor
		autoinit x = 0
		autoinit y = 0
	operator const right *: Point
		param left: double
		return Point(left * x, left * y)

var const a: Point = 1.23 * Point(11, 22)
"""
		module = WppCore.createMemModule(source, 'right.wpp')
		a = module.findItem('a')
		v = a.getValueTaxon()
		self.assertEqual(v.type, 'binop')
		decl = v.getDeclaration()
		self.assertEqual(decl.type, 'operator')
		self.assertEqual(decl.name, '*')
		ctx = OutContextMemoryStream()
		module.export(ctx)
		self.assertEqual(str(ctx), module.strPack(source))
	def testOverload(self):
		source = """
class simple Point
	field public x: double
	field public y: double
	constructor
		autoinit x = 0
		autoinit y = 0
	operator const overload +: Point
		altName addNum
		param k: double
		return Point(x + k, y - k)
	operator const overload +: Point
		altName addPoint
		param pt: const ref Point
		return Point(x + pt.x, y + pt.y)
var const a: Point = Point(11, 22)
var const b: Point = a + 1.5
var const c: Point = a + b
"""
		module = WppCore.createMemModule(source, 'overload.wpp')
		ctx = OutContextMemoryStream()
		module.export(ctx)
		self.assertEqual(str(ctx), module.strPack(source))
Example #18
0
	def testConstructor(self):
		source = """
class Point
	field x: double
	field y: double
	constructor
		param init x = 0
		param init y = 0
		"""
		expected = """
export class Point {
	private x: number;
	private y: number;
	public constructor(x: number = 0, y: number = 0) {
		this.x = x;
		this.y = y;
	}
}
		"""
		srcModule = WppCore.createMemModule(source, 'static.fake')
		dstModule = srcModule.cloneRoot(TsCore())
		outContext = OutContextMemoryStream()
		dstModule.export(outContext)
		self.assertEqual(str(outContext), WppCore.strPack(expected))
    def testOverloadOk(self):
        source = """
func overload public myFunc: double
	altName myFunc1
	param val: double
	return val

func overload public myFunc: int
	altName myFunc2
	param val: int
	return val
"""
        module = WppCore.createMemModule(source, 'overloadOk.wpp')
        over = module.findItem('myFunc')
        self.assertEqual(over.type, 'overload')
        self.assertEqual(len(over.items), 2)
        ctx = OutContextMemoryStream()
        module.export(ctx)
        self.assertEqual(str(ctx), WppCore.strPack(source))

        body = over.items[0].getBody()
        self.assertEqual(body.type, 'body')
        found = body.items[0].startFindUp('myFunc')
        self.assertEqual(found.type, 'overload')
    def testCallAndNew(self):
        source = """
class A
	method work
func public main
	var const a: A = A()
	a.work()
		"""
        expected = """
class A {
	public work() {
	}
}

export function main() {
	const a: A = new A();
	a.work();
}
		"""
        srcModule = WppCore.createMemModule(source, 'A.fake')
        dstModule = srcModule.cloneRoot(TsCore())
        outContext = OutContextMemoryStream()
        dstModule.export(outContext)
        self.assertEqual(str(outContext), dstModule.strPack(expected))
Example #21
0
    def testCallMethodStatic(self):
        source = """
class static MyMath
	method abs: double
		param value: double
		value < 0.0 ? -value : value

func public main
	var x: double = MyMath.abs(-3.14)
		"""
        module = WppCore.createMemModule(source, 'CallMetod.fake')
        classMyMath = module.dictionary['MyMath']
        self.assertIn('static', classMyMath.attrs)
        absOver = classMyMath.dictionary['abs']
        absMethod = absOver.items[0]
        self.assertEqual(absOver.type, 'Overloads')
        self.assertEqual(absMethod.type, 'Method')
        self.assertTrue(absMethod.canBeStatic)
        self.assertIn('static', absMethod.attrs)
        self.assertIn('static', absOver.attrs)

        outContext = OutContextMemoryStream()
        module.export(outContext)
        self.assertEqual(str(outContext), module.strPack(source))
Example #22
0
	def testCreateMemModule(self):
		source = ''
		module = WppCore.createMemModule(source, 'myModule.mem')
		self.assertEqual(module.type, 'module')
Example #23
0
	def testInvalidName(self):
		source = "var public MyName: int = 0"
		with self.assertRaises(ErrorTaxon) as cm:
			module = WppCore.createMemModule(source, 'invalidName.wpp')
		self.assertEqual(cm.exception.args[0], 'lowerCamelCase is required for var name "MyName"')
Example #24
0
		return Point(x + p.x, y + p.y)
	operator const overload +: Point
		altName addN
		param k: double
		return Point(x + k, y + k)
	method const overload plus: Point
		altName plusPt
		param p: const ref Point
		return Point(x + p.x, y + p.y)
	method const overload plus: Point
		altName plusN
		param k: double
		return Point(x + k, y + k)
var const a: Point = Point(11, 22) + 3
var const b: Point = a + Point(-1, -2)
var const a1: Point = Point(11, 22).plus(3)
var const b1: Point = a1.plus(Point(-1, -2))
"""

print('-- Wpp')
module = WppCore.createMemModule(source, 'example.wpp')
outCtx = OutContextMemoryStream()
module.export(outCtx)
print(str(outCtx))

print('')
exportTS(module)

print('')
exportPy(module)
Example #25
0
	def createModuleFromWpp(code, fileName):
		from Wpp.WppCore import WppCore
		wppModule = WppCore.createMemModule(code, fileName)
		return PyCore.createFromSource(wppModule)
Example #26
0
	def testReservedName(self):
		source = "var public this: int = 0"
		with self.assertRaises(ErrorTaxon) as cm:
			module = WppCore.createMemModule(source, 'reserved.wpp')
		self.assertEqual(cm.exception.args[0], 'The reserved word "this" cannot be used as a name')
Example #27
0
from Wpp.WppCore import WppCore
from out.OutContextMemoryStream import OutContextMemoryStream

source = """
func public main
	typedef TSize: unsigned long
	var a: TSize = 22.2
"""
module = WppCore.createMemModule(source, 'fake.memory')
outContext = OutContextMemoryStream()
module.export(outContext)
print(str(outContext))
Example #28
0
    def testFindSuitablePure(self):
        source = """
func public overload hello
	altName twoInt
	param a: int
	param b: int

func public overload hello
	altName threeInt
	param a: int
	param b: int
	param c: int

func public overload hello
	altName twoLong
	param a: long
	param b: long
"""

        module = WppCore.createMemModule(source, 'findSuitablePure.wpp')
        hello = module.findItem('hello')
        self.assertEqual(hello.type, TaxonOverload.type)

        qtInt = module.core.findItem('int').buildQuasiType()
        qtLong = module.core.findItem('long').buildQuasiType()
        qtDouble = module.core.findItem('double').buildQuasiType()
        qtBool = module.core.findItem('bool').buildQuasiType()
        constInt = WppConst.create('1')
        qtConstInt = constInt.buildQuasiType()
        helloFuncs = hello.items

        # Если None присутствует в списке аргументов, значит результат будет None
        self.assertIsNone(TaxonOverload.findSuitablePure([None], helloFuncs))
        # Слишком много фактических параметров
        self.assertEqual(
            TaxonOverload.findSuitablePure(
                [qtInt, qtInt, qtInt, qtInt, qtInt, qtInt], helloFuncs),
            'NoSuitable')
        # Слишком мало фактических параметров
        self.assertEqual(TaxonOverload.findSuitablePure([qtInt], helloFuncs),
                         'NoSuitable')
        # Найти вариант с двумя int по строгому соответствию
        res = TaxonOverload.findSuitablePure([qtInt, qtInt], helloFuncs)
        self.assertEqual(res.type, 'func')
        self.assertEqual(getAltName(res), 'twoInt')
        # Вариант с двумя long по строгому соответствию
        res = TaxonOverload.findSuitablePure([qtLong, qtLong], helloFuncs)
        self.assertEqual(getAltName(res), 'twoLong')
        # Вариант с двумя long по нестрогому соответствию int, long
        res = TaxonOverload.findSuitablePure([qtInt, qtLong], helloFuncs)
        self.assertEqual(getAltName(res), 'twoLong')
        # Нет подходящего варианта для int, bool
        res = TaxonOverload.findSuitablePure([qtInt, qtBool], helloFuncs)
        self.assertEqual(res, 'NoSuitable')
        # Если один аргумент с точным типом, а второй получен из константы, то поиск удачный
        res = TaxonOverload.findSuitablePure([qtInt, qtConstInt], helloFuncs)
        self.assertEqual(getAltName(res), 'twoInt')
        # Если два аргумента константы, то им соответствуют оба варианта int, int и long, long. Это ошибка
        res = TaxonOverload.findSuitablePure([qtConstInt, qtConstInt],
                                             helloFuncs)
        self.assertEqual(res, 'NoSuitable')