diff --git a/manualTests/src/main/x/ConstOrdinalListTest.x b/manualTests/src/main/x/ConstOrdinalListTest.x index ecb071abec..1f90a3b7c4 100644 --- a/manualTests/src/main/x/ConstOrdinalListTest.x +++ b/manualTests/src/main/x/ConstOrdinalListTest.x @@ -1,8 +1,7 @@ /** * A test for ConstOrdinalList. */ -module ConstOrdinalListTest - { +module ConstOrdinalListTest { import ecstasy.collections.ConstOrdinalList; import ecstasy.numbers.PseudoRandom; @@ -11,39 +10,31 @@ module ConstOrdinalListTest void run(String[] args=[]) // void run(String[] args=["dump", "[30159670, 30159670, 182002775, 182002775, 182002775]"]) // void run(String[] args=["dump", "[30159670, 30159670, 182002775, 182002775, 182002775, 298647733, 298647733, 298647733, 298647733, 298647733, 298647733, 298647733, 298647733]"]) -// void run(String[] args=["dump", "[30159670, 30159670, 182002775, 182002775, 182002775, 298647733, 298647733, 298647733, 298647733, 298647733, 298647733, 298647733, 298647733, 30159670, 30159670]"]) - { - if (args.empty) - { - for (UInt64 i : 0 ..< 1000) - { +// void run(String[] args=["dump", "[30159670, 30159670, 182002775, 182002775, 182002775, 298647733, 298647733, 298647733, 298647733, 298647733, 298647733, 298647733, 298647733, 30159670, 30159670]"]) { + if (args.empty) { + for (UInt64 i : 0 ..< 1000) { Random rnd = new PseudoRandom(i+1); Int max = 1+rnd.int(1+rnd.int(Int32.MaxValue)); Int dft = rnd.int(max); test(i, max, dft, rnd); - } } - else - { + } else { // for test reproducers: // e.g. "[4, 27, 27, 27, 27, 13, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 4, 4, 4]" String s = args[0]; Boolean dump = False; - if (s.startsWith("d") || s.startsWith("D")) - { + if (s.startsWith("d") || s.startsWith("D")) { dump = True; s = args[1]; - } + } - if (s.startsWith('[')) - { + if (s.startsWith('[')) { s = s.substring(1); - } - if (s.endsWith(']')) - { + } + if (s.endsWith(']')) { s = s[0 ..< s.size-1]; - } + } Int[] list = s.trim() == "" ? [] @@ -51,93 +42,73 @@ module ConstOrdinalListTest assert:debug; validate(list, 0, dump); - } } + } - void test(Int testNum, Int max, Int dft, Random rnd) - { + void test(Int testNum, Int max, Int dft, Random rnd) { Int[] list = new Int[]; - for (Int i : 0 ..< 10) - { - try - { + for (Int i : 0 ..< 10) { + try { validate(list, testNum*10+i, False); - if (rnd.boolean()) - { - for (Int add : 0 .. rnd.int(1+rnd.int(12))) - { + if (rnd.boolean()) { + for (Int add : 0 .. rnd.int(1+rnd.int(12))) { list.add(dft); - } } - else if (rnd.boolean()) - { + } else if (rnd.boolean()) { Int val = rnd.int(max); - for (Int add : 0 .. rnd.int(1+rnd.int(25))) - { + for (Int add : 0 .. rnd.int(1+rnd.int(25))) { list.add(val); - } } - else - { - for (Int add : 0 .. rnd.int(1+rnd.int(20))) - { + } else { + for (Int add : 0 .. rnd.int(1+rnd.int(20))) { list.add(rnd.int(max)); - } } } - catch (Exception e) - { + } catch (Exception e) { console.print($"Exception with list: {list}"); throw e; - } } } + } - void validate(Int[] list, Int testNum, Boolean dump) - { + void validate(Int[] list, Int testNum, Boolean dump) { console.print($"Test #{testNum}: {list}"); ConstOrdinalList col = new ConstOrdinalList(list); validate(list, col, testNum, "", dump); - for (Int fast = 5; fast < 100; fast *= 2) - { - if (fast > list.size) - { + for (Int fast = 5; fast < 100; fast *= 2) { + if (fast > list.size) { break; - } + } col = new ConstOrdinalList(col.toArray(), fast); validate(list, col, testNum, $"fast={fast}", dump); - } } + } - void validate(Int[] list, ConstOrdinalList col, Int testNum, String desc, Boolean dump) - { + void validate(Int[] list, ConstOrdinalList col, Int testNum, String desc, Boolean dump) { Int len = col.contents.size; console.print($|Test #{testNum}{desc == "" ? desc : $" ({desc})"}, size={col.size}, \ |bytes={len}, compression={calcPct(list.size * 4 + 4, len)} ); - if (dump) - { + if (dump) { console.print(col.contents.toHexDump(40)); - } + } assert list.empty == col.empty; assert list.size == col.size; assert List.equals(list, col); - for (Int i : 0 ..< list.size) - { + for (Int i : 0 ..< list.size) { assert list[i] == col[i]; - } } + } - String calcPct(Int from, Int to) - { + String calcPct(Int from, Int to) { Int pct = (to - from) * 100 / from; return $"{pct < 0 ? "" : "+"}{pct}%"; - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/Dec28.x b/manualTests/src/main/x/Dec28.x index 93c8969815..84b9a187d0 100644 --- a/manualTests/src/main/x/Dec28.x +++ b/manualTests/src/main/x/Dec28.x @@ -1,18 +1,15 @@ -module Test - { +module Test { @Inject Console console; - void run() - { + void run() { assert:debug; for (String s : ["0", "1", "123", "123.45", "1.234567", "0.0001234567", - ".00001234500", "1234000"]) - { + ".00001234500", "1234000"]) { Dec28 dec = new Dec28(s); console.print($"s={s}, dec={dec}"); - } } + } /** * Implementation details: @@ -56,16 +53,13 @@ module Test * 0111110... +qNaN * 1111110... -qNaN */ -const Dec28(Bit[] bits) - { - construct(Bit[] bits) - { +const Dec28(Bit[] bits) { + construct(Bit[] bits) { assert:arg bits.size == 28; this.bits = bits.freeze(); } - construct(String lit) - { + construct(String lit) { Boolean neg = False; UInt32 sig = 0; Boolean dot = False; @@ -73,10 +67,8 @@ const Dec28(Bit[] bits) Int lzc = 0; // leading zero count (after the dot, before any non-zero digits) Int tdc = 0; // trailing digit count Boolean any = False; - Loop: for (Char ch : lit) - { - switch (ch) - { + Loop: for (Char ch : lit) { + switch (ch) { case '+': assert Loop.count == 0; break; @@ -94,21 +86,15 @@ const Dec28(Bit[] bits) case '0'..'9': any = True; sig = sig * 10 + (ch - '0'); - if (dot) - { - if (sig > 0) - { + if (dot) { + if (sig > 0) { ++tdc; - } - else - { + } else { ++lzc; - } } - else if (sig > 0) // ignore leading zeros - { + } else if (sig > 0) // ignore leading zeros { ++ldc; - } + } break; default: @@ -121,18 +107,16 @@ const Dec28(Bit[] bits) assert !dot || lzc+tdc > 0 as "no digits encountered after decimal point"; Int digits = ldc + lzc + tdc; - switch (digits) - { + switch (digits) { case 0: construct Dec28(neg ? NegZero.bits : PosZero.bits); return; case 1..6: - while (digits++ < 7) - { + while (digits++ < 7) { // add a trailing zero sig *= 10; - } + } continue; case 7: construct Dec28(neg, sig, (ldc - 1 - lzc).toInt8()); @@ -140,17 +124,14 @@ const Dec28(Bit[] bits) } // 8 or more digits; test if some were trailing zeros - while (True) - { + while (True) { (val newSig, val digit) = sig /% 10; - if (digit != 0) - { + if (digit != 0) { break; } sig = newSig; - if (--digits == 7) - { + if (--digits == 7) { construct Dec28(neg, sig, (ldc - 1 - lzc).toInt8()); } assert --tdc >= 0; @@ -164,20 +145,17 @@ const Dec28(Bit[] bits) construct Dec28(neg, sig, (6 - tdc - lzc).toInt8()); } - construct(Boolean negative, UInt32 significand, Int8 exponent) - { + construct(Boolean negative, UInt32 significand, Int8 exponent) { Bit[] bits = new Bit[28]; assert:arg significand < 10_000_000; assert:arg -5 <= exponent <= 6; - if (negative) - { + if (negative) { bits[0] = 1; } - if (significand != 0) - { + if (significand != 0) { // adjust exponent such that the minimum exponent is stored as a 0 exponent += 5; @@ -186,15 +164,12 @@ const Dec28(Bit[] bits) significand &= significand & 0x0FFFFF; // 20 bits = 6+ digits bits.replaceAll(8, significand.toBitArray()[12..<32]); - if (highBits >= 8) - { + if (highBits >= 8) { bits[1] = 1; bits[2] = 1; bits.replaceAll(3, exponent.toBitArray()[4..<8]); bits[7] = highBits.toBitArray()[31]; - } - else - { + } else { bits.replaceAll(1, exponent.toBitArray()[4..<8]); bits.replaceAll(5, highBits.toBitArray()[29..<32]); } @@ -213,12 +188,9 @@ const Dec28(Bit[] bits) static Dec28 PosInfinity = new Dec28([0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); static Dec28 NegInfinity = new Dec28([1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); - Dec28 normalize() - { - if (!finite) - { - if (infinity) - { + Dec28 normalize() { + if (!finite) { + if (infinity) { return negative ? NegInfinity : PosInfinity; } @@ -226,8 +198,7 @@ const Dec28(Bit[] bits) return negative ? NegNaN : PosNaN; } - if (significand == 0) - { + if (significand == 0) { return negative ? NegZero : PosZero; } @@ -235,131 +206,107 @@ const Dec28(Bit[] bits) return this; } - Boolean S.get() - { + Boolean S.get() { return bits[0].toBoolean(); } - Boolean G0.get() - { + Boolean G0.get() { return bits[1].toBoolean(); } - Boolean G1.get() - { + Boolean G1.get() { return bits[2].toBoolean(); } - Boolean G2.get() - { + Boolean G2.get() { return bits[3].toBoolean(); } - Boolean G3.get() - { + Boolean G3.get() { return bits[4].toBoolean(); } - Boolean G4.get() - { + Boolean G4.get() { return bits[5].toBoolean(); } - Boolean G5.get() - { + Boolean G5.get() { return bits[6].toBoolean(); } - Boolean G6.get() - { + Boolean G6.get() { return bits[7].toBoolean(); } - Int emax.get() - { + Int emax.get() { return 6; } - Int emin.get() - { + Int emin.get() { return 1-emax; } - Int bias.get() - { + Int bias.get() { // emax+p−2 == 11 return emax+5; } // ----- - Boolean finite.get() - { + Boolean finite.get() { return !(G1 && G2 && G3 && G4); } - Boolean infinity.get() - { + Boolean infinity.get() { return G1 && G2 && G3 && G4 && !G5; } - Boolean NaN.get() - { + Boolean NaN.get() { return G1 && G2 && G3 && G4 && G5; } - Signum sign.get() - { - if (finite && significand == 0) - { + Signum sign.get() { + if (finite && significand == 0) { return Zero; } return negative ? Negative : Positive; } - Boolean negative.get() - { + Boolean negative.get() { return S; } - (Boolean negative, UInt32 significand, Int8 exponent) split() - { + (Boolean negative, UInt32 significand, Int8 exponent) split() { return negative, significand, exponent; } - UInt32 significand.get() - { + UInt32 significand.get() { // if G0 and G1 together are one of 00, 01, or 10, then the significand is formed from bits // Gw+2 (G4) through the end of the encoding (including T). - if (!(G0 & G1)) - { + if (!(G0 & G1)) { return bits[5..<28].toUInt32(); } // otherwise, if G2 and G3 together are one of 00, 01, or 10, then the significand is formed // by prefixing the 4 bits (8+G(w+4)) (8+G6) to T. - if (!(G2 & G3)) - { + if (!(G2 & G3)) { return 0x800000 | bits[7..<28].toUInt32(); } return 0; } - Int8 exponent.get() - { + Int8 exponent.get() { // if G0 and G1 together are one of 00, 01, or 10, then the biased exponent E is formed from // G0 through Gw+1 (G3) - if (!(G0 & G1)) - { + if (!(G0 & G1)) { return bits[1..4].toUInt8().toInt8() + emin.toInt8(); } // otherwise, if G2 and G3 together are one of 00, 01, or 10, then the biased exponent E is // formed from G2 through Gw+3 (G5) - if (!(G2 & G3)) - { + if (!(G2 & G3)) { return bits[3..6].toUInt8().toInt8() + emin.toInt8(); } @@ -369,28 +316,22 @@ const Dec28(Bit[] bits) // ----- operators ----------------------------------------------------------------------------- @Op("-#") - Dec28 neg() - { + Dec28 neg() { return new Dec28(bits.replace(0, ~bits[0])); } @Op("+") - Dec28 add(Dec28 n) - { - if (!(finite && n.finite)) - { - if (NaN) - { + Dec28 add(Dec28 n) { + if (!(finite && n.finite)) { + if (NaN) { return this; } - if (n.NaN) - { + if (n.NaN) { return n; } - if (infinity) - { + if (infinity) { return this; } @@ -399,40 +340,30 @@ const Dec28(Bit[] bits) } (Boolean neg1, UInt32 sig1, Int8 exp1) = this.split(); - if (sig1 == 0) - { + if (sig1 == 0) { return n; } (Boolean neg2, UInt32 sig2, Int8 exp2) = n.split(); - if (sig2 == 0) - { + if (sig2 == 0) { return this; } - if (exp1 != exp2) - { + if (exp1 != exp2) { // TODO scale } - if (neg1 == neg2) - { + if (neg1 == neg2) { sig1 += sig2; - } - else if (sig2 > sig1) - { + } else if (sig2 > sig1) { sig1 = sig2 - sig1; neg1 = !neg1; - } - else - { + } else { sig1 -= sig2; } - if (sig1 > 9999999) - { - if (++exp1 > emax) - { + if (sig1 > 9999999) { + if (++exp1 > emax) { return neg1 ? NegInfinity : PosInfinity; } sig1 /= 10; @@ -442,69 +373,58 @@ const Dec28(Bit[] bits) } @Op("-") - Dec28 sub(Dec28 n) - { + Dec28 sub(Dec28 n) { TODO return new Dec28(); } @Op("*") - Dec28 mul(Dec28 n) - { + Dec28 mul(Dec28 n) { TODO return new Dec28(); } @Op("/") - Dec28 div(Dec28 n) - { + Dec28 div(Dec28 n) { TODO return new Dec28(); } @Op("%") - Dec28 mod(Dec28 n) - { + Dec28 mod(Dec28 n) { TODO return new Dec28(); } @Override - String toString() - { - if (!finite) - { - return switch (negative, NaN) - { - case (False, False): "+∞"; - case (False, True ): "+NaN"; - case (True , False): "-∞"; - case (True , True ): "-NaN"; + String toString() { + if (!finite) { + return switch (negative, NaN) { + case (False, False): "+∞"; + case (False, True ): "+NaN"; + case (True , False): "-∞"; + case (True , True ): "-NaN"; }; } (Boolean neg, UInt32 sig, Int8 exp) = this.split(); - if (sig == 0) - { + if (sig == 0) { return neg ? "-0" : "0"; } StringBuffer buf = new StringBuffer(14); - if (neg) - { + if (neg) { buf.append('-'); } // render up to the first digit of the significand Int pow = exp; - switch (pow <=> -1) - { + switch (pow <=> -1) { case Lesser: // for a significand of 1234567, the value is e.g. 0.00001234567 buf.append('0') .append('.'); - while(pow < -1) - { + while(pow < -1) { buf.append('0'); ++pow; - } + } break; case Equal: @@ -521,20 +441,15 @@ const Dec28(Bit[] bits) // render the significand static UInt32[] pows = [1000000, 100000, 10000, 1000, 100, 10, 1]; - while (sig != 0 && pow < 6) - { - if (pow == exp) - { + while (sig != 0 && pow < 6) { + if (pow == exp) { buf.append('.'); } UInt32 digit; - if (++pow < 6) - { + if (++pow < 6) { (digit, sig) = sig /% pows[pow]; - } - else - { + } else { digit = sig; } @@ -542,8 +457,7 @@ const Dec28(Bit[] bits) } // finish any trailing zeros to the left of the decimal point - while (pow++ < exp) - { + while (pow++ < exp) { buf.append('0'); } @@ -553,4 +467,4 @@ const Dec28(Bit[] bits) // TODO equals hashcode compare } - } \ No newline at end of file +} \ No newline at end of file diff --git a/manualTests/src/main/x/TestAsync.x b/manualTests/src/main/x/TestAsync.x index 6107de4329..980a351be1 100644 --- a/manualTests/src/main/x/TestAsync.x +++ b/manualTests/src/main/x/TestAsync.x @@ -1,24 +1,18 @@ -module TestAsync - { +module TestAsync { @Inject Console console; - void run() - { - for (Int i : 1..3) - { + void run() { + for (Int i : 1..3) { new Async(i).foo(); // synchronous call // new Async(i).foo^(); // asynchronous call - } } + } - service Async(Int id, Int count=5) - { - void foo() - { - for (Int i : 1 .. count) - { + service Async(Int id, Int count=5) { + void foo() { + for (Int i : 1 .. count) { console.print($"Async:{id} #{i}"); - } } } } +} diff --git a/manualTests/src/main/x/annos.x b/manualTests/src/main/x/annos.x index 73ffd44500..51ac1d8f19 100644 --- a/manualTests/src/main/x/annos.x +++ b/manualTests/src/main/x/annos.x @@ -1,55 +1,43 @@ -module TestAnnotations - { +module TestAnnotations { @Inject ecstasy.io.Console console; - void run() - { + void run() { testWatch(); testMixin(); testMixin2(); testMethodMixin(); testClassMixin(); testDefaultParams(); - } + } - function void (Int) logger = (Int v) -> - { + function void (Int) logger = (Int v) -> { @Inject ecstasy.io.Console console; console.print($"->{v}", True); - }; + }; - void testWatch() - { + void testWatch() { console.print("\n** testWatch"); // property-based - for (@Watch(logger) Int i = 3; i > 0; --i) - { - } + for (@Watch(logger) Int i = 3; i > 0; --i) {} console.print(); // var-based - function void (Int) log = (Int v) -> - { + function void (Int) log = (Int v) -> { console.print($"{v}->", True); - }; + }; @Watch(log) Int i; - for (i = 3; i > 0; --i) - { - } + for (i = 3; i > 0; --i) {} console.print(); // lambda-based @Watch((Int v) -> {console.print($"{v}, ", True);}) Int k; - for (k = 3; k > 0; --k) - { - } + for (k = 3; k > 0; --k) {} console.print(); - } + } - void testMixin() - { + void testMixin() { console.print("\n** testMixin"); Int age = 26; @@ -57,180 +45,143 @@ module TestAnnotations val p2 = new @Aged(age + 1) Named("Joe"); val p3 = new @Aged(age) @Skilled("Java") Named("Jon"); val p4 = new @Skilled("Ecstasy") @Aged(21) Named("Joanne"); - try - { + try { new @Aged(-1) Named("Joe"); throw new Exception(); - } - catch (IllegalState e) - { + } catch (IllegalState e) { console.print($"expected assert: {e.text}"); - } - try - { + } + try { new @Skilled("Ecstasy") @Aged(21) Named(""); throw new Exception(); - } - catch (IllegalState e) - { + } catch (IllegalState e) { console.print($"expected assert: {e.text}"); - } } + } - const Named - { - construct(String name) - { + const Named { + construct(String name) { console.print($"construct (name) {this}"); this.name = name; - } - finally - { + } finally { console.print($"finally (name) {this}"); - } + } - assert() - { + assert() { assert name.size > 0; console.print($"assert (name) {name}"); - } - String name; } + String name; + } - mixin Aged into Named - { - construct(Int age) - { + mixin Aged into Named { + construct(Int age) { console.print($"construct (aged) {this}"); this.age = age; - } - finally - { + } finally { console.print($"finally (aged) {this}"); - } + } - assert() - { + assert() { assert age >= 0; console.print($"assert (aged) {age}"); - } - Int age; } + Int age; + } - mixin Skilled into Named - { - construct(String skill) - { + mixin Skilled into Named { + construct(String skill) { console.print($"construct (skill) {this}"); this.skill = skill; - } - finally - { + } finally { console.print($"finally (skill) {this}"); - } + } - assert() - { + assert() { assert skill.size > 0; console.print($"assert (skill) {skill}"); - } - String skill; } + String skill; + } - void testMixin2() - { + void testMixin2() { new Parent().test(); String descr = "from outside"; new Parent().new @Parent.Mixin(descr) Parent.Child().test(); - class Parent - { - mixin Mixin(String descr) into Child - { + class Parent { + mixin Mixin(String descr) into Child { @Override - void test() - { + void test() { console.print($"in test at Mixin {descr}"); super(); - } } + } - void test() - { + void test() { String descr = "from inside"; new @Mixin(descr) Child().test(); - } + } - class Child - { - void test() - { + class Child { + void test() { console.print("in test at Child"); - } } } } + } @Tagged(weight=1) - void testMethodMixin(@Tagged(weight=2) (@Unchecked Int64)? i = Null) - { + void testMethodMixin(@Tagged(weight=2) (@Unchecked Int64)? i = Null) { Method m = testMethodMixin; console.print(m); assert m.is(Tagged); assert m.tag == "method" && m.weight == 1; - } + } - void testClassMixin() - { + void testClassMixin() { Inner inner = new Inner(); assert !inner.is(Tagged); @Tagged(weight=2) - class Inner - { - } - } + class Inner {} + } mixin Tagged(String tag="", Int weight=-1) - into Parameter | Method | Class - { - String tag.get() - { + into Parameter | Method | Class { + String tag.get() { String tag = super(); return tag.size > 0 ? tag : this.is(Parameter) ? "param" : this.is(Method) ? "method" : "class"; - } + } @Override - Int estimateStringLength() - { + Int estimateStringLength() { return super() + tag.size + "weight=".size + 2; - } + } @Override - Appender appendTo(Appender buf) - { + Appender appendTo(Appender buf) { $"@Tagged({tag} {weight}) ".appendTo(buf); return super(buf); - } } + } - void testDefaultParams() - { + void testDefaultParams() { TaggedObject taggedMap = new @TaggedObject(weight=1) HashMap(); assert taggedMap.tag == "none" && taggedMap.weight == 1; TaggedConst taggedRange = new @TaggedConst(hash=2) Range(0, 1); assert taggedRange.hash == 2 && taggedRange.tag == "const" && taggedRange.weight == 1; - } + } mixin TaggedObject(String tag="none", Int weight=-1) into Object; mixin TaggedConst(Int weight=1, Int hash=-1) extends TaggedObject("const", weight); - } \ No newline at end of file +} \ No newline at end of file diff --git a/manualTests/src/main/x/array.x b/manualTests/src/main/x/array.x index d388d2ba4b..162b23824c 100644 --- a/manualTests/src/main/x/array.x +++ b/manualTests/src/main/x/array.x @@ -1,9 +1,7 @@ -module TestArray - { +module TestArray { @Inject ecstasy.io.Console console; - void run() - { + void run() { testSimple(); testStrBuf(); testConstElement(); @@ -25,10 +23,9 @@ module TestArray testIterators(); testConstOrdinalList(); - } + } - void testSimple() - { + void testSimple() { console.print("\n** testSimple()"); Int[] nums = [1,7]; @@ -36,10 +33,9 @@ module TestArray console.print("size=" + nums.size); console.print("[0]=" + nums[0]); console.print("[1]=" + nums[1]); - } + } - void testStrBuf() - { + void testStrBuf() { console.print("\n** testStrBuf()"); StringBuffer buf = new StringBuffer(); @@ -49,18 +45,16 @@ module TestArray .append('!'); console.print("buf=" + buf); - } + } - void testConstElement() - { + void testConstElement() { console.print("\n** testConstElement()"); String cruel = ["hello", "cruel", "world", "!"] [1]; console.print("array[1]=" + cruel); - } + } - void testConstSlice() - { + void testConstSlice() { console.print("\n** testConstSlice()"); String[] cruel = ["hello", "cruel", "world", "!"] [1..2]; @@ -68,10 +62,9 @@ module TestArray String[] cruel2 = ["hello", "cruel", "world", "!"] [2..1]; console.print("array[2..1]=" + cruel2); - } + } - void testArrayList() - { + void testArrayList() { console.print("\n** testArrayList()"); String[] list = new String[]; @@ -93,10 +86,9 @@ module TestArray list.setElement(0, "один"); list.setElement(1, "два"); console.print("list=" + list); - } + } - void testArrayListAdd() - { + void testArrayListAdd() { console.print("\n** testArrayListAdd()"); String?[] list = new String?[]; @@ -126,10 +118,9 @@ module TestArray bools[9] = True; console.print($"bools={bools}"); - } + } - void testFixedArray() - { + void testFixedArray() { console.print("\n** testFixedArray()"); String[] list = new String[3](i -> ["one","two","three"][i]); @@ -146,24 +137,21 @@ module TestArray Boolean[] booleans = new Boolean[3](i -> i % 2 == 0); console.print("booleans=" + booleans); - } + } - void testFormalTypes() - { + void testFormalTypes() { Array a1 = [1, 2]; assert checkElementType(a1); Array a2 = ["1", "2"]; assert !checkElementType(a2); - } + } - private static Boolean checkElementType(Value o) - { + private static Boolean checkElementType(Value o) { return Value.is(Type) && Value.Element.is(Type); - } + } - void testAssignSideEffects() - { + void testAssignSideEffects() { console.print("\n** testAssignSideEffects()"); Int n = 5; @@ -177,57 +165,49 @@ module TestArray nums[--i] += 7; console.print("nums=" + nums + ", i=" + i); - } + } - void testNew() - { + void testNew() { console.print("\n** testNew()"); String[] array = new Array(10); console.print("array=" + array + ", size=" + array.size); - for (Int i : 1..10) - { + for (Int i : 1..10) { array += "#" + i; - } - console.print("array=" + array + ", size=" + array.size); } + console.print("array=" + array + ", size=" + array.size); + } - void testNibble() - { + void testNibble() { console.print("\n** testNibble()"); loop: - for (Nibble b : MinValue .. MaxValue) - { + for (Nibble b : MinValue .. MaxValue) { console.print($"b{loop.count}={b}"); - } } + } - void testBits() - { + void testBits() { console.print("\n** testBits()"); Int n = 17; Bit[] bits = n.toBitArray(); - for (Bit bit : bits) - { + for (Bit bit : bits) { console.print(bit, suppressNewline=True); - } + } console.print(); bits = bits.delete(0); bits = bits.delete(bits.size - 1); - for (Bit bit : bits) - { + for (Bit bit : bits) { console.print(bit, suppressNewline=True); - } - console.print(); } + console.print(); + } - void testComparable() - { + void testComparable() { import ecstasy.collections.Hasher; import ecstasy.collections.NaturalHasher; @@ -243,93 +223,87 @@ module TestArray Bit[] bits = [0, 1, 1, 0]; console.print($"Array.hashCode(bits)={Array.hashCode(bits)}"); - } + } - void testIterators() - { + void testIterators() { console.print("\n** testIterators()"); String[] strs = ["goodbye", "cruel", "world"]; - for (Int i : 1..10) - { + for (Int i : 1..10) { Iterator iter = strs.iterator(); - switch (i) - { - case 1: - console.print("\n --> peeking test"); - iter = iter.peek(s -> console.print($"peeking at {s}")); - break; - - case 2: - console.print("\n --> skipping test"); - iter = iter.skip(2); - break; - - case 3: - console.print("\n --> compound test"); - iter = iter.concat(strs.iterator()); - break; - - case 4: - console.print("\n --> duplicate test"); - (Iterator iter1, Iterator iter2) = iter.bifurcate(); - iter = iter1.concat(iter2); - break; - - case 5: - console.print("\n --> filter test"); - iter = iter.filter(e -> e[0] != 'c'); - break; - - case 6: - console.print("\n --> map test"); - iter = iter.map(e -> e.size.toString()); - break; - - case 7: - console.print("\n --> sort test"); - iter = iter.sorted(); - break; - - case 8: - console.print("\n --> reverse test"); - iter = iter.reversed(); - break; - - case 9: - console.print("\n --> flatmap test"); - iter = iter.flatMap(s -> s.iterator()).map(ch -> ch.toString()); - break; - - case 10: - console.print("\n --> dedup test"); - (Iterator iter1, Iterator iter2) = iter.bifurcate(); - iter = iter1.concat(iter2); - iter = iter.dedup(); - break; - } - - while (String s := iter.next()) - { + switch (i) { + case 1: + console.print("\n --> peeking test"); + iter = iter.peek(s -> console.print($"peeking at {s}")); + break; + + case 2: + console.print("\n --> skipping test"); + iter = iter.skip(2); + break; + + case 3: + console.print("\n --> compound test"); + iter = iter.concat(strs.iterator()); + break; + + case 4: + console.print("\n --> duplicate test"); + (Iterator iter1, Iterator iter2) = iter.bifurcate(); + iter = iter1.concat(iter2); + break; + + case 5: + console.print("\n --> filter test"); + iter = iter.filter(e -> e[0] != 'c'); + break; + + case 6: + console.print("\n --> map test"); + iter = iter.map(e -> e.size.toString()); + break; + + case 7: + console.print("\n --> sort test"); + iter = iter.sorted(); + break; + + case 8: + console.print("\n --> reverse test"); + iter = iter.reversed(); + break; + + case 9: + console.print("\n --> flatmap test"); + iter = iter.flatMap(s -> s.iterator()).map(ch -> ch.toString()); + break; + + case 10: + console.print("\n --> dedup test"); + (Iterator iter1, Iterator iter2) = iter.bifurcate(); + iter = iter1.concat(iter2); + iter = iter.dedup(); + break; + } + + while (String s := iter.next()) { console.print($"s={s}"); - } } + } console.print("\n --> metadata tests"); Iterator iter = strs.iterator(); console.print($"distinct={iter.knownDistinct()}"); console.print($"sorted={iter.knownOrder()}"); - if (Function f := iter.knownOrder()) - { + if (Function f := iter.knownOrder()) { console.print($"order={f}"); - } + } console.print($"knownEmpty={iter.knownEmpty()}"); console.print($"knownSize={iter.knownSize()}"); - if (Int size := iter.knownSize()) - { + if (Int size := iter.knownSize()) { console.print($"size={size}"); - } + } console.print("\n --> misc tests"); console.print($"count={strs.iterator().count()}"); @@ -340,26 +314,23 @@ module TestArray assert Range range := strs.iterator().range(); console.print($"min={min}; max={max}"); console.print($"range={range}"); - } + } - void testConstOrdinalList() - { + void testConstOrdinalList() { console.print("\n** testConstOrdinalList()"); Int[] vals = [1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 8]; val col = new ecstasy.collections.ConstOrdinalList(vals); - for (Int i : 0 ..< vals.size) - { + for (Int i : 0 ..< vals.size) { console.print($"col[{i}]={col[i]}"); - } + } Iterator iter = col.iterator(); - Loop: while (Int val := iter.next()) - { + Loop: while (Int val := iter.next()) { assert val == vals[Loop.count] && val == col[Loop.count]; - } + } console.print($"col={col}"); console.print($"bytes={col.contents}"); - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/collections.x b/manualTests/src/main/x/collections.x index 32e03fe68e..ffd32a8225 100644 --- a/manualTests/src/main/x/collections.x +++ b/manualTests/src/main/x/collections.x @@ -1,71 +1,59 @@ -module TestCollections - { +module TestCollections { @Inject ecstasy.io.Console console; - void run() - { + void run() { console.print("Collection tests"); testLinkedList(); - } + } - class Phone(String desc, String number) - { + class Phone(String desc, String number) { // scenario #1 - all phone numbers in the list, starting with this one @LinkedList Phone? next; - List list.get() - { + List list.get() { return &next; - } + } @Override - String toString() - { + String toString() { return desc + " " + number; - } } + } - class Person(String name, Int age) - { + class Person(String name, Int age) { // scenario #2 - ancestors, starting with this person's parent (assume asexual reproduction, // since this is linked list structure, instead of a tree) @LinkedList(omitThis=True) Person? parent; - List ancestors.get() - { + List ancestors.get() { return &parent; - } + } // scenario #3 - all siblings, including this person @LinkedList(prev=prevSibling) Person? nextSibling; Person? prevSibling; - List siblings.get() - { + List siblings.get() { return &nextSibling; - } + } // scenario #4 - all children of this person @LinkedList(next=nextSibling, prev=prevSibling, omitThis=True) Person? child; - List children.get() - { + List children.get() { return &child; - } + } // scenario #5 - all phone numbers of this person @LinkedList(Phone.next) Phone? phone; // scenario #5 - List phoneNumbers.get() - { + List phoneNumbers.get() { return ☎ - } + } @Override - String toString() - { + String toString() { return name + " " + age; - } } + } - void testLinkedList() - { + void testLinkedList() { console.print("LinkedList scenario 1"); Phone first = new Phone("home", "555-1212"); @@ -74,10 +62,9 @@ module TestCollections phones += new Phone("work", "555-3456"); phones.add(new Phone("cell", "555-9876")); - Loop: for (Phone p : phones) - { + Loop: for (Phone p : phones) { console.print($"[{Loop.count}] {p}"); - } + } Person george1 = new Person("George I", 48); Person george2 = new Person("George II", 25); @@ -98,30 +85,26 @@ module TestCollections console.print("LinkedList scenario 2"); - Loop: for (Person p : albert3.ancestors) - { + Loop: for (Person p : albert3.ancestors) { console.print($"[{Loop.count}] {p}"); - } + } console.print("LinkedList scenario 3"); - Loop: for (Person p : albert3.siblings) - { + Loop: for (Person p : albert3.siblings) { console.print($"[{Loop.count}] {p}"); - } + } console.print("LinkedList scenario 4"); - Loop: for (Person p : george2.children) - { + Loop: for (Person p : george2.children) { console.print($"[{Loop.count}] {p}"); - } + } console.print("LinkedList scenario 5"); - Loop: for (Phone p : george1.phoneNumbers) - { + Loop: for (Phone p : george1.phoneNumbers) { console.print($"[{Loop.count}] {p}"); - } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/compiler.x b/manualTests/src/main/x/compiler.x index 9552086fab..e36c451c10 100644 --- a/manualTests/src/main/x/compiler.x +++ b/manualTests/src/main/x/compiler.x @@ -1,10 +1,8 @@ -module TestCompiler - { +module TestCompiler { @Inject ecstasy.lang.src.Compiler compiler; @Inject Console console; - void run() - { + void run() { @Inject Directory curDir; assert File|Directory sourceFile := curDir.find("src/main/x/errors.x"); @@ -19,10 +17,9 @@ module TestCompiler assert sourceFile.is(File); compile(sourceFile, buildDir); - } + } - void compile(File sourceModule, Directory buildDir) - { + void compile(File sourceModule, Directory buildDir) { console.print($| |compile module : {sourceModule.path} |build directory: {buildDir} @@ -33,9 +30,8 @@ module TestCompiler (Boolean success, String[] errors) = compiler.compile([sourceModule]); console.print(success ? "Compiled successfully" : "Compilation failed:"); - for (String error : errors) - { + for (String error : errors) { console.print(error); - } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/contained.x b/manualTests/src/main/x/contained.x index 7fdf9e65ce..118a194005 100644 --- a/manualTests/src/main/x/contained.x +++ b/manualTests/src/main/x/contained.x @@ -1,12 +1,10 @@ -module TestContained - { +module TestContained { @Inject Console console; @Inject String description; - void run() - { + void run() { @Inject Int value; console.print($"{description=} {value=}"); - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/container.x b/manualTests/src/main/x/container.x index 4852a3b2b8..4dd6a9bae4 100644 --- a/manualTests/src/main/x/container.x +++ b/manualTests/src/main/x/container.x @@ -1,8 +1,7 @@ /** * Test of the BasicResourceProvider. */ -module TestContainer - { +module TestContainer { import ecstasy.mgmt.*; import ecstasy.reflect.ModuleTemplate; @@ -10,23 +9,19 @@ module TestContainer @Inject Console console; - void run(Int depth=0) - { + void run(Int depth=0) { console.print($"Running at depth {depth}"); @Inject("repository") ModuleRepository repository; // run itself - if (depth < 3) - { + if (depth < 3) { ModuleTemplate template = repository.getResolvedModule("TestContainer"); Container container = new Container(template, Lightweight, repository, SimpleResourceProvider); container.invoke("run", Tuple:(depth+1)); - } - else - { + } else { // run TestSimple ModuleTemplate template = repository.getResolvedModule("TestSimple"); ResourceProvider injector = new BasicResourceProvider(); @@ -36,34 +31,31 @@ module TestContainer // run TestContained contained.run(); - } } + } static service SimpleResourceProvider - extends BasicResourceProvider - { + extends BasicResourceProvider { @Override - Supplier getResource(Type type, String name) - { + Supplier getResource(Type type, String name) { import Container.Linker; - switch (type, name) - { - case (String, _): - return "hello"; + switch (type, name) { + case (String, _): + return "hello"; - case (Int, "value"): - return Int:42; + case (Int, "value"): + return Int:42; - case (Linker, "linker"): - @Inject Linker linker; - return linker; + case (Linker, "linker"): + @Inject Linker linker; + return linker; - case (ModuleRepository, "repository"): - @Inject ModuleRepository repository; - return repository; - } - return super(type, name); + case (ModuleRepository, "repository"): + @Inject ModuleRepository repository; + return repository; } + return super(type, name); } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/crypto.x b/manualTests/src/main/x/crypto.x index 65e40038d2..efa17d0940 100644 --- a/manualTests/src/main/x/crypto.x +++ b/manualTests/src/main/x/crypto.x @@ -12,16 +12,14 @@ * -keystore src/main/x/resources/test_store.p12 -storepass password * */ -module TestCrypto - { +module TestCrypto { @Inject Console console; package crypto import crypto.xtclang.org; import crypto.*; - void run(String[] args = ["password"]) - { + void run(String[] args = ["password"]) { File store = File:./resources/test_store.p12; String pairName = "test_pair"; String symName = "test_sym"; @@ -65,12 +63,10 @@ module TestCrypto PrivateKey privateKeyM = new PrivateKey("test-copy", "DES", 8, random.fill(new Byte[8])); testDecryptor(algorithms, "DES", privateKeyM, BIG_TEXT); - } + } - void testDecryptor(Algorithms algorithms, String name, CryptoKey key, String text) - { - if (Decryptor decryptor := algorithms.decryptorFor(name, key)) - { + void testDecryptor(Algorithms algorithms, String name, CryptoKey key, String text) { + if (Decryptor decryptor := algorithms.decryptorFor(name, key)) { console.print($"*** {decryptor} for {key}"); Byte[] bytes = decryptor.encrypt(text.utf8()); @@ -78,46 +74,36 @@ module TestCrypto Byte[] data = decryptor.decrypt(bytes); assert data.unpackUtf8() == text; - } - else - { + } else { console.print($"Cannot find decryptor for {name.quoted()} with {key}"); - } } + } - void testHasher(Algorithms algorithms, String name, String text) - { - if (Signer hasher := algorithms.hasherFor(name)) - { + void testHasher(Algorithms algorithms, String name, String text) { + if (Signer hasher := algorithms.hasherFor(name)) { console.print($"*** {hasher}"); Signature hash = hasher.sign(text.utf8()); console.print(hash.bytes.toHexDump()); assert hasher.verify(hash, text.utf8()); - } - else - { + } else { console.print($"Cannot find hasher for {name.quoted()}"); - } } + } - void testSigner(Algorithms algorithms, String name, CryptoKey key, String text) - { - if (Signer signer := algorithms.signerFor(name, key)) - { + void testSigner(Algorithms algorithms, String name, CryptoKey key, String text) { + if (Signer signer := algorithms.signerFor(name, key)) { console.print($"*** {signer}"); Signature sig = signer.sign(text.utf8()); console.print(sig.bytes.toHexDump()); assert signer.verify(sig, text.utf8()); - } - else - { + } else { console.print($"Cannot find signer for {name.quoted()}"); - } } + } static String SMALL_TEXT = \|The RSA encryption is meant to be used only for small data chunks; \ @@ -125,4 +111,4 @@ module TestCrypto ; static String BIG_TEXT = $./crypto.x; - } \ No newline at end of file +} \ No newline at end of file diff --git a/manualTests/src/main/x/dbTests/CounterDB.x b/manualTests/src/main/x/dbTests/CounterDB.x index 4b444bbb28..838e29f307 100644 --- a/manualTests/src/main/x/dbTests/CounterDB.x +++ b/manualTests/src/main/x/dbTests/CounterDB.x @@ -1,6 +1,5 @@ @Database -module CounterDB - { +module CounterDB { package oodb import oodb.xtclang.org; import oodb.Database; @@ -9,18 +8,15 @@ module CounterDB import oodb.RootSchema; interface CounterSchema - extends RootSchema - { + extends RootSchema { @RO DBMap counters; @RO Cranker cranker; - } + } mixin Cranker - into DBProcessor - { + into DBProcessor { @Override - void process(String name) - { + void process(String name) { CounterSchema schema = dbRoot.as(CounterSchema); DBMap counters = schema.counters; @@ -28,15 +24,13 @@ module CounterDB Int count = counters.getOrDefault(name, 0); counters.put(name, ++count); - if (count % 20 != 0) - { + if (count % 20 != 0) { schedule(name); - } + } - if (count % 60 == 0) - { + if (count % 60 == 0) { counters.remove(name); - } } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/dbTests/CounterTest.x b/manualTests/src/main/x/dbTests/CounterTest.x index e718fc61ab..0cc69bedab 100644 --- a/manualTests/src/main/x/dbTests/CounterTest.x +++ b/manualTests/src/main/x/dbTests/CounterTest.x @@ -5,8 +5,7 @@ * gradle compileOne -PtestName=dbTests/CounterDB * gradle runOne -PtestName=dbTests/CounterTest */ -module CounterTest - { +module CounterTest { package oodb import oodb.xtclang.org; package jsondb import jsondb.xtclang.org; @@ -16,8 +15,7 @@ module CounterTest typedef (oodb.Connection + CounterSchema) as Connection; - void run(String[] args = []) - { + void run(String[] args = []) { @Inject Console console; @Inject Directory homeDir; @Inject Random rnd; @@ -31,49 +29,41 @@ module CounterTest console.print(dump(connection)); StringBuffer msg = new StringBuffer().append($"cranking up schedules: "); - for (Int i : 1..3) - { + for (Int i : 1..3) { // pick a letter to schedule String name = ('A' + rnd.uint(26).toUInt32()).toString(); connection.cranker.schedule(name); msg.append(name).append(", "); - } + } console.print(msg.truncate(-2).toString()); wait(connection, Duration:1s); - } + } - void wait(Connection connection, Duration duration) - { + void wait(Connection connection, Duration duration) { @Inject Console console; @Inject Timer timer; @Future Tuple<> result; - timer.schedule(duration, () -> - { + timer.schedule(duration, () -> { console.print(dump(connection)); - try - { + try { connection.close(); - } - catch (Exception ignore) {} + } catch (Exception ignore) {} result=Tuple:(); - }); + }); return result; - } + } - String dump(Connection connection) - { - try (val tx = connection.createTransaction()) - { + String dump(Connection connection) { + try (val tx = connection.createTransaction()) { StringBuffer buf = new StringBuffer(); - for ((String name, Int count) : connection.counters) - { + for ((String name, Int count) : connection.counters) { buf.append($"{name}={count}, "); - } - return buf.toString().quoted(); } + return buf.toString().quoted(); } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/dbTests/LogDB.x b/manualTests/src/main/x/dbTests/LogDB.x index c2dce708f7..6320c137bb 100644 --- a/manualTests/src/main/x/dbTests/LogDB.x +++ b/manualTests/src/main/x/dbTests/LogDB.x @@ -1,20 +1,17 @@ @Database -module LogDB - { +module LogDB { package oodb import oodb.xtclang.org; import oodb.*; interface LogSchema - extends RootSchema - { + extends RootSchema { @RO @NoTx @AutoTruncate(10K) @AutoExpire(Duration:1h) DBLog logger; @RO CounterSchema counters; - } + } interface CounterSchema - extends DBSchema - { + extends DBSchema { @RO @NoTx DBCounter counter; - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/dbTests/LogTest.x b/manualTests/src/main/x/dbTests/LogTest.x index c266e9a3d0..a5d5828182 100644 --- a/manualTests/src/main/x/dbTests/LogTest.x +++ b/manualTests/src/main/x/dbTests/LogTest.x @@ -5,8 +5,7 @@ * gradle compileOne -PtestName=dbTests/LogDB * gradle runOne -PtestName=dbTests/LogTest */ -module LogTest - { +module LogTest { package oodb import oodb.xtclang.org; package jsondb import jsondb.xtclang.org; @@ -14,8 +13,7 @@ module LogTest import logDB.LogSchema; - void run() - { + void run() { @Inject Directory homeDir; Directory dataDir = homeDir.dirFor("Development/xvm/manualTests/data/logDB").ensure(); @@ -23,29 +21,25 @@ module LogTest reportLogFiles(dataDir, "*** Before"); - using (LogSchema schema = jsondb.createConnection("LogDB", dataDir, buildDir).as(LogSchema)) - { - for (Int i : 1..1000) - { + using (LogSchema schema = jsondb.createConnection("LogDB", dataDir, buildDir).as(LogSchema)) { + for (Int i : 1..1000) { schema.logger.add( $"This is a message to test the log truncation policy: {schema.counters.counter.next()}"); - } } + } reportLogFiles(dataDir, "*** After"); - } + } - void reportLogFiles(Directory dataDir, String prefix) - { + void reportLogFiles(Directory dataDir, String prefix) { @Inject Console console; console.print(prefix); Int size = 0; - for (File file : dataDir.dirFor("logger").files()) - { + for (File file : dataDir.dirFor("logger").files()) { console.print($"\t-{file.size} {file.name}"); size += file.size; - } - console.print($"total size {size} bytes"); } - } \ No newline at end of file + console.print($"total size {size} bytes"); + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/defasn.x b/manualTests/src/main/x/defasn.x index 30bba5120f..3058aecab0 100644 --- a/manualTests/src/main/x/defasn.x +++ b/manualTests/src/main/x/defasn.x @@ -1,33 +1,27 @@ -module TestDefAsn - { +module TestDefAsn { @Inject ecstasy.io.Console console; - void run() - { + void run() { testDefAssignment(); testShort(); testNameHiding(); testWhileLoop(0); testForLoop(0); - } + } - Boolean gimmeTrue() - { + Boolean gimmeTrue() { return True; - } - String? maybeNull() - { + } + String? maybeNull() { return Null; - } + } - void testDefAssignment() - { + void testDefAssignment() { console.print("\n** testDefAssignment()"); - static (String, Int) name() - { + static (String, Int) name() { return "hello", 5; - } + } String n; Int c; @@ -40,24 +34,20 @@ module TestDefAsn Boolean f2 = gimmeTrue(); // vary this test as necessary (do vs. while; break vs. continue; && vs. ||, etc.) - L1: do - { - if (f1 && {i=3; return True;}) - { + L1: do { + if (f1 && {i=3; return True;}) { //i = 3; break L1; - } + } i = 1; continue L1; - } - while (f2); + } while (f2); console.print("i=" + i); - } + } - void testShort() - { + void testShort() { console.print("\n** testShort()"); Int i; @@ -65,68 +55,52 @@ module TestDefAsn Boolean f2 = gimmeTrue(); String? s = maybeNull(); - if (s?.size > 1 && {i=3; return True;}) - { + if (s?.size > 1 && {i=3; return True;}) { //i = 3; - } - else - { + } else { i = 4; - } + } console.print("i=" + i); - } + } String name = "top-level property"; - void testNameHiding() - { - static conditional (String, Int) name() - { + void testNameHiding() { + static conditional (String, Int) name() { return True, "hello", 5; - } + } - if ((String name, Int count) := name()) - { + if ((String name, Int count) := name()) { assert name.size == count; - } } + } - void testWhileLoop(Int? in) - { + void testWhileLoop(Int? in) { Int i; - while (True) - { - if (in.is(Int)) - { + while (True) { + if (in.is(Int)) { i = in; break; - } - else - { + } else { throw new IllegalState(); - } } + } assert i >= 0; - } + } - void testForLoop(Int? in) - { + void testForLoop(Int? in) { Int i; - for (;;) - { - if (in.is(Int)) - { + for (;;) { + if (in.is(Int)) { i = in; break; - } - else - { + } else { return; - } } + } assert i >= 0; - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/errors.x b/manualTests/src/main/x/errors.x index 8fb900e417..d5221abfbb 100644 --- a/manualTests/src/main/x/errors.x +++ b/manualTests/src/main/x/errors.x @@ -1,184 +1,142 @@ -module TestCompilerErrors - { +module TestCompilerErrors { // arrays - void testAOOB1() - { + void testAOOB1() { Object test = ["hello", "cruel", "world", "!"] [-1]; - } - void testAOOB2() - { + } + void testAOOB2() { Object test = ["hello", "cruel", "world", "!"] [4]; - } - void testAOOB3() - { + } + void testAOOB3() { Object test = ["hello", "cruel", "world", "!"] [1..4]; - } - void testAOOB4() - { + } + void testAOOB4() { Object test = ["hello", "cruel", "world", "!"] [4..1]; - } - void testAOOB5() - { + } + void testAOOB5() { Object test = ["hello", "cruel", "world", "!"] [-1..1]; - } - void testAOOB6() - { + } + void testAOOB6() { Object test = ["hello", "cruel", "world", "!"] [1..-1]; - } - void testConstruct() - { + } + void testConstruct() { Int[] array = new Int[7, (i) -> -1]; - } + } // tuples - void testTOOB1() - { + void testTOOB1() { Tuple test = (3, "blind", "mice", "!") [-1..1]; - } - void testTOOB2() - { + } + void testTOOB2() { Tuple test = (3, "blind", "mice", "!") [1..4]; - } - void testTOOB3() - { + } + void testTOOB3() { Tuple test = (3, "blind", "mice", "!") [4..1]; - } - void testTOOB4() - { + } + void testTOOB4() { Tuple test = (3, "blind", "mice", "!") [1..-1]; - } - void testTOOB5() - { + } + void testTOOB5() { Object test = (3, "blind", "mice", "!") [-1]; - } - void testTOOB6() - { + } + void testTOOB6() { Object test = (3, "blind", "mice", "!") [4]; - } + } // methods - class TestMethods - { - static void testMethod1() - { + class TestMethods { + static void testMethod1() { function void () m1 = testMethod2; // no "this" function void () m2 = Test.testMethod2; // no target - } + } void testMethod2() {} - } + } // def assignment - void defAssign1(String? s = Null, Int i = 0) - { - if ((s != Null) || (i == 0)) - { + void defAssign1(String? s = Null, Int i = 0) { + if ((s != Null) || (i == 0)) { i = s.size; // should not compile - } } + } - void defAssign2(String? s = Null, Int i = 0) - { - if ((s == Null) && (i == 1)) - { - } - else - { + void defAssign2(String? s = Null, Int i = 0) { + if ((s == Null) && (i == 1)) {} else { i = s.size; // should not compile - } } + } - package TestVirtualSuper - { - interface Iface - { + package TestVirtualSuper { + interface Iface { void f(); - } + } @Mix class Base - implements Iface - { + implements Iface { @Override - void f(Boolean flag = False) - { + void f(Boolean flag = False) { super(); // should not compile - } } + } class Derived - extends Base - { + extends Base { @Override - Int f(Boolean flag=False) - { + Int f(Boolean flag=False) { return super(flag); // should not compile - } } + } mixin Mix - into Base - { + into Base { @Override - void f(Boolean flag=False) - { + void f(Boolean flag=False) { super(flag); - } } } + } - void testUnreachable(Object o) - { - String s = switch (o.is(_)) - { + void testUnreachable(Object o) { + String s = switch (o.is(_)) { case IntNumber, FPNumber: "Number"; case Int: "Int"; // should not compile: unreachable default: "other"; - }; - } + }; + } - package TestGenerics - { - class Base - { + package TestGenerics { + class Base { Base? nextBase; Child? nextChild; class Child {} - Base!<> createBase() - { + Base!<> createBase() { return new Base(); - } + } - void createChildTest1() - { + void createChildTest1() { Base bi = new Base(); Child ci = bi.new Child(); // should not compile: type is B.C; not assignable to B.C - } } } + } - void testUnassigned() - { + void testUnassigned() { @Custom Int i; Int j = i; // should not compile - unassigned - } + } mixin Custom - into Var - { - } + into Var {} - void testFinal(Boolean f) - { + void testFinal(Boolean f) { @Final Int i; - if (f) - { + if (f) { i = 1; - } + } i = 2; // should not compile - cannot be assigned to - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/exceptions.x b/manualTests/src/main/x/exceptions.x index 96311950aa..3403a16120 100644 --- a/manualTests/src/main/x/exceptions.x +++ b/manualTests/src/main/x/exceptions.x @@ -1,78 +1,55 @@ -module TestTry - { +module TestTry { @Inject ecstasy.io.Console console; - void run() - { + void run() { console.print("Exception tests:"); - try - { + try { testBasic(); - } - catch (Exception e) - { + } catch (Exception e) { console.print("UNEXPECTED THROW in testBasic(): " + e); - } + } - try - { + try { testUsing(); - } - catch (Exception e) - { + } catch (Exception e) { console.print("UNEXPECTED THROW in testUsing(): " + e); - } + } - try - { + try { testFinally(); console.print("TEST ERROR!!!"); - } - catch (Exception e) - { + } catch (Exception e) { console.print("expected throw in testFinally(): " + e); - } + } - try - { + try { testAssert(-1); console.print("TEST ERROR!!!"); - } - catch (Exception e) - { + } catch (Exception e) { console.print("expected throw in testAssert(): " + e); - } + } - try - { + try { testAssert(17); console.print("TEST ERROR!!!"); - } - catch (Exception e) - { + } catch (Exception e) { console.print("expected throw in testAssert(): " + e); - } + } - try - { + try { testAssert(3); console.print("(expected non-throw in testAssert())"); - } - catch (Exception e) - { + } catch (Exception e) { console.print("TEST ERROR!!! Unexpected throw in testAssert(): " + e); - } + } - try - { + try { testAssert2(); console.print("TEST ERROR!!!"); - } - catch (Exception e) - { + } catch (Exception e) { console.print("expected throw in testAssert2(): " + e); - } + } testAssertOnce(True); testAssertOnce(False); @@ -83,103 +60,79 @@ module TestTry testSwitch(1); console.print("\nException tests: finished!"); - } + } - void testThrow() - { + void testThrow() { console.print("in testThrow()"); throw new IllegalState("test"); - } + } - void testBasic() - { + void testBasic() { console.print("\n** testBasic()"); - try - { + try { testThrow(); console.print("DIDN'T THROW!"); - } - catch (Exception e) - { + } catch (Exception e) { console.print("caught: " + e); - } + } console.print("done testBasic()"); - } + } - void testUsing() - { + void testUsing() { console.print("\n** testUsing()"); - try - { - using (ByeBye bye = new ByeBye()) - { + try { + using (ByeBye bye = new ByeBye()) { testThrow(); console.print("DIDN'T THROW!"); - } } - catch (Exception e) - { + } catch (Exception e) { console.print("ok"); - } + } - try (ByeBye bye = new ByeBye()) - { + try (ByeBye bye = new ByeBye()) { console.print(bye); - } - finally - { + } finally { console.print("in finally: " + bye); - } + } console.print("done"); - } + } class ByeBye - implements ecstasy.Closeable - { - construct() - { + implements ecstasy.Closeable { + construct() { console.print("hello!"); - } + } @Override - void close(Exception? cause = Null) - { + void close(Exception? cause = Null) { console.print("bye-bye!"); - } } + } - void testFinally() - { + void testFinally() { console.print("\n** testFinally()"); - FOR: for (Int i : 1..2) - { + FOR: for (Int i : 1..2) { console.print("iteration " + i); - TRY: try - { - if (FOR.last) - { + TRY: try { + if (FOR.last) { console.print("throwing exception inside try"); testThrow(); - } - else - { + } else { console.print("not throwing exception inside try"); continue; - } } - finally - { + } finally { console.print("exception in finally: " + TRY.exception); - } } + } console.print("done testFinally() - which shouldn't happen!"); - } + } /** * ** testAssert(-1) @@ -191,114 +144,86 @@ module TestTry * ** testAssert(3) * (no assertion) */ - void testAssert(Int i) - { + void testAssert(Int i) { console.print($"\n** testAssert({i})"); assert:bounds i >= 0 && i < size(); - } + } - Int size() - { + Int size() { return 6; - } + } - void testAssert2() - { + void testAssert2() { console.print("\n** testAssert2()"); Int x = 4; assert ++x <= 4; - } + } - void testAssertOnce(Boolean firstTime) - { + void testAssertOnce(Boolean firstTime) { console.print($"\n** testAssertOnce({firstTime})"); Int x = 42; - try - { + try { assert:once x < size(); // the assertion passed, which it shouldn't do, unless this is the second time through console.print(firstTime ? "[1st] ERR: should have asserted" : "[2nd] OK: skipped"); - } - catch (Exception e) - { + } catch (Exception e) { console.print(firstTime ? "[1st] OK: assert" : "[2nd] ERR: should have skipped"); console.print(e.text); - } } + } - void testAssertSample() - { + void testAssertSample() { console.print("\n** testAssertSample()"); Int x = 99; Int ok = 0; Int err = 0; - for (Int i : 1..1000) - { - try - { + for (Int i : 1..1000) { + try { assert:rnd(100) x < size(); ++ok; - } - catch (OutOfBounds e) - { + } catch (OutOfBounds e) { assert; - } - catch (Exception e) - { + } catch (Exception e) { ++err; - } - finally - { + } finally { ++x; - } } + } console.print($"results: ok={ok}, errs={err} (should be ~10)"); - } + } - void testSwitch(Int n) - { + void testSwitch(Int n) { console.print($"\n** testSwitch({n})"); - try - { - switch (n) - { - case -1: - return; - - default: - { - try - { - n = 10/n; - break; - } - catch (Exception e) - { - console.print($"exception {e}"); - throw e; - } - finally - { - console.print("inner finally"); - } - } + try { + switch (n) { + case -1: + return; + + default: { + try { + n = 10/n; + break; + } catch (Exception e) { + console.print($"exception {e}"); + throw e; + } finally { + console.print("inner finally"); } } - finally - { + } + } finally { console.print("outer finally"); - if (n == 0) - { + if (n == 0) { // eat the exception return; - } } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/files.x b/manualTests/src/main/x/files.x index 742a2dbcb8..31e317a328 100644 --- a/manualTests/src/main/x/files.x +++ b/manualTests/src/main/x/files.x @@ -1,5 +1,4 @@ -module TestFiles - { +module TestFiles { import ecstasy.fs.Directory; import ecstasy.fs.File; import ecstasy.fs.FileWatcher; @@ -9,15 +8,13 @@ module TestFiles @Inject Console console; @Inject("storage") FileStore store; - void run() - { + void run() { testPaths(); testInject(); testModify(); - } + } - void testPaths() - { + void testPaths() { console.print("\n** testPaths()"); console.print($"root={Path.ROOT}"); console.print($"parent={Path.PARENT}"); @@ -32,15 +29,13 @@ module TestFiles path = new Path(path, "more"); console.print($"path={path}"); - for (Int i : 0..2) - { + for (Int i : 0..2) { console.print($"path[{i}]={path[i]}"); - } + } - Loop: for (Path each : path) - { + Loop: for (Path each : path) { console.print($"iterating path[{Loop.count}]={each}"); - } + } console.print($"path[]={path.toArray()}"); console.print($"path[1..2]={path[1..2]}"); @@ -57,10 +52,9 @@ module TestFiles console.print($"relativize root to path = {path.relativize(Path.ROOT)}"); console.print($"relativize /a/b/c to /a/p/d/q = {new Path("/a/p/d/q").relativize(new Path("/a/b/c"))}"); console.print($"relativize /a/p/d/q to /a/b/c = {new Path("/a/b/c").relativize(new Path("/a/p/d/q"))}"); - } + } - void testInject() - { + void testInject() { console.print("\n** testInject()"); console.print($"readOnly={store.readOnly}"); @@ -78,52 +72,42 @@ module TestFiles console.print($"curDir={curDir}"); console.print($"{curDir.name} content:"); - for (String name : curDir.names()) - { - if (File|Directory node := curDir.find(name)) - { - if (node.is(File)) - { - if (!name.indexOf('.')) - { + for (String name : curDir.names()) { + if (File|Directory node := curDir.find(name)) { + if (node.is(File)) { + if (!name.indexOf('.')) { console.print($"\tf {name} {node.size} bytes"); - } } - else - { + } else { console.print($"\td {name}"); - } } } } + } - void testModify() - { + void testModify() { console.print("\n** testModify()"); @Inject Directory tmpDir; @Inject Timer timer; - FileWatcher watcher = new FileWatcher() - { + FileWatcher watcher = new FileWatcher() { @Override - Boolean onEvent(Event event, Directory dir) - { + Boolean onEvent(Event event, Directory dir) { console.print($|[{this:service}]: Directory event: \"{event}\" {dir.name}\ | after {timer.elapsed.seconds} sec ); return False; - } + } @Override - Boolean onEvent(Event event, File file) - { + Boolean onEvent(Event event, File file) { console.print($|[{this:service}]: File event: \"{event}\" {file.name}\ | after {timer.elapsed.seconds} sec ); return False; - } - }; + } + }; File file = tmpDir.fileFor("test.dat"); @@ -141,8 +125,7 @@ module TestFiles // on Mac OS the WatchService implementation simply polls every 10 seconds; // increase the "wait" value to see the events Int wait = 1; - timer.schedule(Duration.ofSeconds(wait), () -> - { + timer.schedule(Duration.ofSeconds(wait), () -> { console.print($|[{this:service}]: deleting {file.name}\ | after {timer.elapsed.seconds} sec ); @@ -150,14 +133,13 @@ module TestFiles file.delete(); assert !file.exists; - timer.schedule(Duration.ofSeconds(wait), () -> - { + timer.schedule(Duration.ofSeconds(wait), () -> { @Inject Clock clock; assert tmpDir.modified.date == clock.now.date; console.print($"[{this:service}]: tmpDir={tmpDir}"); cancel(); - }); }); - } - } \ No newline at end of file + }); + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/generics.x b/manualTests/src/main/x/generics.x index 05cb7f9006..a885658ba3 100644 --- a/manualTests/src/main/x/generics.x +++ b/manualTests/src/main/x/generics.x @@ -1,9 +1,7 @@ -module TestGenerics - { +module TestGenerics { @Inject ecstasy.io.Console console; - void run() - { + void run() { console.print("Generic tests"); testArrayType(); @@ -11,10 +9,9 @@ module TestGenerics testTypeParams(); testTurtleType(); testConditionalMixins(); - } + } - void testArrayType() - { + void testArrayType() { String[] list = new String[]; list += "one"; @@ -22,10 +19,9 @@ module TestGenerics list.Element el0 = list[0]; console.print("el0=" + el0); - } + } - void testVirtualChild() - { + void testVirtualChild() { Base bi = new Base(); Base.Child c1 = bi.new Child(); @@ -35,38 +31,31 @@ module TestGenerics console.print("bi.c2=" + c2); bi.createChild(); - } + } - interface Runnable - { + interface Runnable { void run(); - } + } - class Base - { + class Base { Base? nextBase; Child? nextChild; - class Child - { + class Child { @Override - String toString() - { + String toString() { return super() + " outer = " + this.Base; - } } + } - class Child2 - { + class Child2 { @Override - String toString() - { + String toString() { return super() + " outer = " + this.Base + " type=" + ChildType; - } } + } - void createChild() - { + void createChild() { Child c1 = new Child(); // compile time type is B.C console.print("c1=" + c1); @@ -83,55 +72,44 @@ module TestGenerics console.print("c4=" + c4); Base.Child2 c5 = b2.new Child2(); - } + } - Base!<> createBase() - { + Base!<> createBase() { return new Base(); - } } + } class Derived - extends Base - { - } + extends Base {} class Derived2 - extends Derived - { - } + extends Derived {} - void testTypeParams() - { + void testTypeParams() { Derived d1 = new Derived(); Derived2 d2 = new Derived2(); foo(d1, d2, d2); - } + } - void foo(CompileType1 c1, CompileType2 c2, CompileType3 c3) - { + void foo(CompileType1 c1, CompileType2 c2, CompileType3 c3) { assert c2.as(CompileType1) != c1; - } + } - void testTurtleType() - { + void testTurtleType() { TestTurtle<> turtle = new TestTurtle<>(); console.print($"{turtle.getType(0)=}"); - class TestTurtle> - { - Type getType(Int index) - { + class TestTurtle> { + Type getType(Int index) { UniformIndexed types = TurtleTypes; return types[index]; - } } } + } - void testConditionalMixins() - { + void testConditionalMixins() { import testConditional.*; Derived1 d1 = new Derived1(); @@ -148,10 +126,9 @@ module TestGenerics Derived3 d3i = new Derived3(3); assert d3i.bi == 1 && d3i.mi == 4; - } + } - package testConditional - { + package testConditional { const Base {} const Base2(Int bi) @@ -174,5 +151,5 @@ module TestGenerics const Derived3(Value d3i) extends Base2(1) incorporates conditional Mix(d3i+1) {} - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/innerouter.x b/manualTests/src/main/x/innerouter.x index f12dd467cf..2d85368c5c 100644 --- a/manualTests/src/main/x/innerouter.x +++ b/manualTests/src/main/x/innerouter.x @@ -1,139 +1,115 @@ -module TestInnerOuter - { +module TestInnerOuter { @Inject Console console; - void run() - { + void run() { testSimple(); testStaticIface(); testAnonInner(); testFunky(); - } + } - interface IfaceOuter - { + interface IfaceOuter { void fnOuter(); - static interface IfaceInner - { + static interface IfaceInner { void fnInner(); - } } + } class Base(String text) - implements IfaceOuter - { - class Child_V() - { - String textByName.get() - { + implements IfaceOuter { + class Child_V() { + String textByName.get() { return this.Base.text; - } + } - String textByOuter.get() - { + String textByOuter.get() { return outer.text; - } + } - void testOuter() - { + void testOuter() { val o1 = outer; Outer o2 = this.Outer; assert &o1 == &o2; assert &o2 == &outer; console.print($"this=\"{this}\"; outer=\"{o1}\", type=\"{&o1.Referent}\""); - } } + } @Override - void fnOuter() - { - } + void fnOuter() {} static const Child_NV(String name) - implements IfaceOuter.IfaceInner - { + implements IfaceOuter.IfaceInner { @Override - void fnInner() - { + void fnInner() { console.print(" -> fnInner"); - } } + } @Override - String toString() - { + String toString() { return text; - } } + } - void testSimple() - { + void testSimple() { console.print("\n** testSimple()"); Base b1 = new Base("Hello"); Base b2 = new Base("World"); Base[] bases = [b1, b2]; - for (Base base : bases) - { + for (Base base : bases) { Base.Child_V child = base.new Child_V(); console.print($"Obtaining text from \"{base}\" child:"); console.print(" -> by-outer=" + child.textByOuter); console.print(" -> by-name=" + child.textByName); - } + } b1.new Child_V().testOuter(); - } + } - void testStaticIface() - { + void testStaticIface() { console.print("\n** testStaticIface()"); IfaceOuter.IfaceInner childNV = new Base.Child_NV("NonVirtual"); console.print($"childNV={childNV}"); childNV.fnInner(); - } + } - void testAnonInner() - { + void testAnonInner() { console.print("\n** testAnonInner()"); - class Inner - { + class Inner { construct(String s) {} - } + } Int i = 4; // var o = new Object() - var o = new Inner("hello") - { - void run() - { + var o = new Inner("hello") { + void run() { console.print($"in run (i={i})"); ++i; // foo(); - } - }; + } + }; o.run(); console.print($"done (i={i})"); - } + } - interface FunkyOuter - { + interface FunkyOuter { String name; interface FunkyInner - extends Orderable - { + extends Orderable { @RO Element e; static Ordered - compare(CompileType value1, CompileType value2) - { + compare(CompileType value1, CompileType value2) { @Inject Console console; console.print($"CompileType={CompileType}"); @@ -147,41 +123,36 @@ module TestInnerOuter // TODO GG: deferred; see explanation in NameExpression.planCodeGen() // return (value1.e <=> value2.e).reversed; return CompileType.OuterType.Element.compare(value1.e, value2.e).reversed; - } } } + } class Parent(String name) - implements FunkyOuter - { + implements FunkyOuter { @Override String name; class Child(Element e) - implements FunkyInner - { + implements FunkyInner { @Override Element e; @Override - String toString() - { + String toString() { return "Child: " + e; - } } + } @Override - String toString() - { + String toString() { return "Parent of " + Element; - } } + } - void testFunky() - { + void testFunky() { Parent p = new Parent("P1"); Parent.Child c1 = p.new Child("hello"); Parent.Child c2 = p.new Child("world"); assert c1 > c2; - } } +} diff --git a/manualTests/src/main/x/lambda.x b/manualTests/src/main/x/lambda.x index e678e02c4d..2ddf54f6cd 100644 --- a/manualTests/src/main/x/lambda.x +++ b/manualTests/src/main/x/lambda.x @@ -1,9 +1,7 @@ -module TestLambda - { +module TestLambda { @Inject ecstasy.io.Console console; - void run() - { + void run() { console.print("Lambda tests:"); testVoid(); @@ -13,89 +11,77 @@ module TestLambda testRefCapture(); testVarCapture(); testComplexCapture(); - } + } - void testVoid() - { + void testVoid() { console.print("\n** testVoid()"); function void() f = () -> { console.print("in the lambda!"); }; f(); - } + } - void testBasic() - { + void testBasic() { console.print("\n** testBasic()"); function Int() f = () -> 4; console.print($"f={f};\nf()={f()}"); - } + } - void testEffectivelyFinalCapture() - { + void testEffectivelyFinalCapture() { console.print("\n** testEffectivelyFinalCapture()"); Int i = 4; function Int() f = () -> i; console.print("result=" + f()); - } + } - void testThisCapture() - { + void testThisCapture() { console.print("\n** testThisCapture()"); function String() f = () -> foo(); console.print("result=" + f()); - } - String foo() - { + } + String foo() { return "hello"; - } + } - void testRefCapture() - { + void testRefCapture() { console.print("\n** testRefCapture()"); Int i = 0; - do - { + do { function Int() f = () -> i; console.print("result=" + f()); - } - while (i++ < 5); - } + } while (i++ < 5); + } - void testVarCapture() - { + void testVarCapture() { console.print("\n** testVarCapture()"); Int i = 0; - while (i < 5) - { + while (i < 5) { function Int() f = () -> ++i; console.print("result=" + f()); // console.print("i=" + i + ", result=" + f() + ", i=" + i); - } + } // test for the capture of an unassigned variable Int j; function void() f2 = () -> {j = ++i;}; f2(); console.print("j=" + &j.get()); - } + } - void testComplexCapture() - { + void testComplexCapture() { console.print("\n** testComplexCapture()"); Int i = 0; - while (i < 5) - { + while (i < 5) { function Int() f1 = () -> i; console.print("result=" + f1()); // initially would appear to be "Int", but must be "Ref" function Int() f2 = () -> ++i; console.print("result=" + f2()); - } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/maps.x b/manualTests/src/main/x/maps.x index 1f1a5dafb3..67068f4b05 100644 --- a/manualTests/src/main/x/maps.x +++ b/manualTests/src/main/x/maps.x @@ -1,5 +1,4 @@ -module TestMaps - { +module TestMaps { package collections import collections.xtclang.org; import collections.ConcurrentHashMap; @@ -10,8 +9,7 @@ module TestMaps @Inject Timer timer; Log log = new ecstasy.io.ConsoleLog(console); - void run() - { + void run() { testBasic(new ListMap()); testBasic(new HashMap()); testBasic(new SkiplistMap()); @@ -70,10 +68,9 @@ module TestMaps // log.add($"iteration #{seed}"); // testRandomOps(new ConcurrentHashMap(), seed); // } - } + } - void testBasic(Map map) - { + void testBasic(Map map) { console.print("\n** testBasic()"); String one = "Hello from Map"; @@ -83,38 +80,30 @@ module TestMaps assert String s1 := map.get(1), s1 == one; assert String s2 := map.get(2), s2 == two; - } + } - void testEquals(Map map1) - { + void testEquals(Map map1) { map1.put(1, "v1"); Map map2 = [1="v1"]; assert map1 == map2; - } + } - void testHasher() - { - try - { + void testHasher() { + try { Map map = new HashMap(); assert:test; - } - catch (IllegalState e) - { + } catch (IllegalState e) { console.print($"expected: {e.text}"); - } + } - try - { + try { Map map = new HashMap(); assert:test; - } - catch (IllegalState e) - { + } catch (IllegalState e) { console.print($"expected: {e.text}"); - } + } Map map = new HashMap(); map.put(1, "i1"); @@ -126,34 +115,29 @@ module TestMaps Map map2 = new HashMap(); map2.put(array, 0); assert map2.get(array); - } + } - static void testFill100() - { + static void testFill100() { Map map = new HashMap(); - for (Int i = 0; i < 100; i++) - { + for (Int i = 0; i < 100; i++) { map.put(i, i); - } } + } - void profile(function void () run, Int iterations) - { + void profile(function void () run, Int iterations) { // warmup run(); timer.reset(); - for (Int i = 0; i < iterations; i++) - { + for (Int i = 0; i < iterations; i++) { run(); - } + } Duration time = timer.elapsed; console.print($"Elapsed {time.milliseconds} ms"); console.print($"Latency {(time / iterations).milliseconds} ms"); - } + } - void testListMap() - { + void testListMap() { console.print("\n** testListMap()"); Map map = new ListMap(); @@ -170,161 +154,129 @@ module TestMaps console.print($"map={map}"); console.print("keys/values:"); - loop: for (String key : map.keys) - { + loop: for (String key : map.keys) { console.print($"[{loop.count}]:{key}={map[key]}"); - } + } // same thing, but using "$" syntax console.print($"keys:{{L: for (val v : map.keys) {$.addAll($"\n[{L.count}]={v}");}}}"); console.print("values:"); - loop: for (String value : map.values) - { + loop: for (String value : map.values) { console.print($"[{loop.count}]:{value}"); - } + } console.print("entries:"); - loop: for (Map.Entry entry : map.entries) - { + loop: for (Map.Entry entry : map.entries) { console.print($"[{loop.count}]:{entry.key}={entry.value}"); - } + } // test very bad hashing - const Point(Int x) - { - static Int64 hashCode(CompileType value) - { + const Point(Int x) { + static Int64 hashCode(CompileType value) { return 100 + value.x.toInt64() % 3; - } } + } ListMap map2 = new ListMap(); - for (Int i : 0 ..< 12) - { + for (Int i : 0 ..< 12) { map2.put(new Point(i), i); - } + } - for (Int i : 0 ..< 12) - { + for (Int i : 0 ..< 12) { assert Int v := map2.get(new Point(i)); assert v == i; - } + } - for (Int i : 0 ..< 12) - { + for (Int i : 0 ..< 12) { map2.remove(new Point(i)); map2.put(new Point(12 + i), 12 + i); - } + } - for (Int i : 12 ..< 24) - { + for (Int i : 12 ..< 24) { assert Int v := map2.get(new Point(i)); assert v == i; - } } + } - void testMapIteration(Map map) - { + void testMapIteration(Map map) { console.print($"\n** testMapIteration({&map.actualType.underlyingTypes[0]})"); map.put("hello", 1); map.put("goodbye", 2); console.print("keys:"); - for (String key : map) - { + for (String key : map) { console.print($"{key}"); - } + } console.print("keys and values:"); - for ((String s, Int i) : map) - { + for ((String s, Int i) : map) { console.print($"{s} = {i}"); - } + } console.print("values:"); - for (Int i : map.values) - { + for (Int i : map.values) { console.print($"? = {i}"); - } } + } - void testMapStableIteration(Map map) - { - for (Int i : 0..10) - { + void testMapStableIteration(Map map) { + for (Int i : 0..10) { map[i] = i + 1; - } + } Iterator.Entry> iter = map.entries.iterator(); Map control = new HashMap(); - if (Map.Entry next := iter.next()) - { + if (Map.Entry next := iter.next()) { assert(!control.contains(next.key)); control.put(next.key, next.value); - } + } - for (Int i : 11..100) - { + for (Int i : 11..100) { map[i] = i + 1; - } + } - for (Int i : 0..20) - { - if (Map.Entry next := iter.next()) - { + for (Int i : 0..20) { + if (Map.Entry next := iter.next()) { assert(!control.contains(next.key)); control.put(next.key, next.value); - } } + } - for (Int i : 100..500) - { + for (Int i : 100..500) { map[i] = i; - } + } - while (Map.Entry next := iter.next()) - { + while (Map.Entry next := iter.next()) { assert(!control.contains(next.key)); control.put(next.key, next.value); - } + } // verify that we at least saw all the original items from the time the // iterator was created - for (Int i : 0..10) - { + for (Int i : 0..10) { assert(control.contains(i)); - } } + } - void testFreezable() - { + void testFreezable() { console.print("\n** testFreezable()"); Container c = new Container(); - void modifyAttempt(Map map) - { + void modifyAttempt(Map map) { Map mapNew; - try - { + try { mapNew = map.put("1", "a"); assert mapNew != map as $"Invalid modification for {&map.actualType}"; - } - catch (ReadOnly e) - { - } + } catch (ReadOnly e) {} - try - { + try { mapNew = map.put("2", "b"); assert mapNew != map as $"Invalid insert for {&map.actualType}"; - } - catch (ReadOnly e) - { - } - } + } catch (ReadOnly e) {} + } modifyAttempt(c.mapL); modifyAttempt(c.mapH); @@ -334,171 +286,145 @@ module TestMaps console.print($"{c.mapH} {c.mapH.keys} {c.mapH.values}"); console.print($"{c.mapS} {c.mapS.keys} {c.mapS.values}"); - try - { + try { NotFreezable nf = c.nf; - } - catch (Exception e) - { + } catch (Exception e) { console.print($"Expected not freezable: {e.text}"); - } + } - const Container() - { + const Container() { @Lazy - Map mapL.calc() - { + Map mapL.calc() { Map map = new ListMap(); map.put("1", "L"); return map; - } + } @Lazy - Map mapH.calc() - { + Map mapH.calc() { Map map = new HashMap(); map.put("1", "H"); return map; - } + } @Lazy - Map mapS.calc() - { + Map mapS.calc() { Map map = new SkiplistMap(); map.put("1", "S"); return map; - } + } - @Lazy NotFreezable nf.calc() - { + @Lazy NotFreezable nf.calc() { return new NotFreezable(0); - } } + } class NotFreezable(Int x); - } + } - static void testBasicOps(Map map) - { - for (Int i : 0..14) - { + static void testBasicOps(Map map) { + for (Int i : 0..14) { map.put($"key_{i}", $"val_{i}"); - } + } Int count = 0; - for (String s : map) - { + for (String s : map) { ++count; - } + } assert count == 15; - for (Int i = 1; i < 14; i += 2) - { + for (Int i = 1; i < 14; i += 2) { map.remove($"key_{i}"); - } + } Int count2 = 0; - for ((_, _) : map) - { + for ((_, _) : map) { ++count2; - } - assert count2 == 8; } + assert count2 == 8; + } - static void testRandomOps(Map map, UInt64 seed) - { + static void testRandomOps(Map map, UInt64 seed) { Random rnd = new ecstasy.numbers.PseudoRandom(seed); Map check = new HashMap(); Int steps = rnd.int(1000) + 1; - for (Int step : 0..steps) - { - switch (rnd.int(100)+1) - { - case 1..49: - for (Int i : 0..rnd.int(rnd.int(10)+1)+1) - { - Int k = rnd.int(1000); - Int v = rnd.int(1000); + for (Int step : 0..steps) { + switch (rnd.int(100)+1) { + case 1..49: + for (Int i : 0..rnd.int(rnd.int(10)+1)+1) { + Int k = rnd.int(1000); + Int v = rnd.int(1000); + map.put(k, v); + check.put(k, v); + } + break; + + case 50..59: + if (!check.empty) { + Int[] keys = check.keys.toArray(); + for (Int i : 0..rnd.int(rnd.int(20)+1)+1) { + Int k = keys[rnd.int(keys.size)]; + Int v = map.getOrDefault(k, -1); + assert v == check.getOrDefault(k, -1); + ++v; map.put(k, v); check.put(k, v); - } - break; - - case 50..59: - if (!check.empty) - { - Int[] keys = check.keys.toArray(); - for (Int i : 0..rnd.int(rnd.int(20)+1)+1) - { - Int k = keys[rnd.int(keys.size)]; - Int v = map.getOrDefault(k, -1); - assert v == check.getOrDefault(k, -1); - ++v; - map.put(k, v); - check.put(k, v); - } - } - break; - - case 60..69: - for (Int i : 0..rnd.int(rnd.int(100)+1)+1) - { - Int k = rnd.int(1000); - assert map.contains(k) == check.contains(k); - } - break; - - case 70..79: - if (!check.empty) - { - Int[] keys = check.keys.toArray(); - for (Int i : 0..rnd.int(rnd.int(100)+1)+1) - { - Int k = keys[rnd.int(keys.size)]; - assert map.getOrNull(k) == check.getOrNull(k); - } - } - break; - - case 80..89: - if (!check.empty) - { - Int[] keys = check.keys.toArray(); - for (Int i : 0..rnd.int(rnd.int(40)+1)+1) - { - Int k = keys[rnd.int(keys.size)]; - map.remove(k); - check.remove(k); - } - } - break; - - case 90..99: - for (Int i : 0..rnd.int(25)+1) - { - Int k = rnd.int(1000); + } + } + break; + + case 60..69: + for (Int i : 0..rnd.int(rnd.int(100)+1)+1) { + Int k = rnd.int(1000); + assert map.contains(k) == check.contains(k); + } + break; + + case 70..79: + if (!check.empty) { + Int[] keys = check.keys.toArray(); + for (Int i : 0..rnd.int(rnd.int(100)+1)+1) { + Int k = keys[rnd.int(keys.size)]; + assert map.getOrNull(k) == check.getOrNull(k); + } + } + break; + + case 80..89: + if (!check.empty) { + Int[] keys = check.keys.toArray(); + for (Int i : 0..rnd.int(rnd.int(40)+1)+1) { + Int k = keys[rnd.int(keys.size)]; map.remove(k); check.remove(k); - } - break; - - case 100: - map.clear(); - check.clear(); - break; + } + } + break; - default: - assert; + case 90..99: + for (Int i : 0..rnd.int(25)+1) { + Int k = rnd.int(1000); + map.remove(k); + check.remove(k); } + break; - assert map == check; + case 100: + map.clear(); + check.clear(); + break; + + default: + assert; } + + assert map == check; } + } - void testProcess(Map map) - { + void testProcess(Map map) { assert(map.processIfPresent(1, e -> e.value++) == False); map.put(1, 1); @@ -508,41 +434,34 @@ module TestMaps map.process(1, e -> {e.delete();}); assert(map.contains(1) == False); - try - { - map.process(1, e -> - { + try { + map.process(1, e -> { TODO; - }); - } - catch (UnsupportedOperation e) - { + }); + } catch (UnsupportedOperation e) { // expected - } } + } - void testConcurrentProcess(Map map) - { + void testConcurrentProcess(Map map) { console.print($"\n** testConcurrentProcess({&map.actualClass.name})"); map.put(0, 0); Int count = 0; // run a long running blocking processor in the background - map.process^(0, e -> - { + map.process^(0, e -> { @Inject Timer timer; @Future Int result; - timer.schedule(Duration:0.2s, () -> - { + timer.schedule(Duration:0.2s, () -> { result = 42; - }); + }); Int r = result; // blocking console.print($"{++count}) process(0) {r}"); e.value++; return result; - }); + }); // write to an alternate key; should not block with CHM even on the same partition map.put(17, 1); @@ -552,120 +471,103 @@ module TestMaps map.get(0); console.print($"{++count}) get(0)"); - try - { - Int ex = map.process(0, e -> - { + try { + Int ex = map.process(0, e -> { console.print($"{++count}) deferred process(0) throw"); - if (e.exists) - { + if (e.exists) { TODO; - } + } return 123; - }); + }); assert; - } - catch (UnsupportedOperation e) - { + } catch (UnsupportedOperation e) { // expected - } + } // write to the same key; CHM should block until original write completes map.put(0, 1); console.print($"{++count}) put(0)"); // processor based write to the same key; CHM should also block - Int n = map.process(0, e -> - { + Int n = map.process(0, e -> { console.print($"{++count}) process(0)"); return ++e.value; - }); + }); // verify that our second process didn't finish until after our // delayed first one on the same key assert n == 2; - } + } - void testConcurrentLoad(Map map, Int concurrency, Int iterations, Int range) - { + void testConcurrentLoad(Map map, Int concurrency, Int iterations, Int range) { timer.reset(); - Future[] futures = new Future[concurrency](i -> - { + Future[] futures = new Future[concurrency](i -> { Int n = new LoadGenerator().run^(map, iterations, i, range); return &n; - }); + }); - for (Future future : futures) - { + for (Future future : futures) { future.get(); - } + } Duration time = timer.elapsed; console.print($"Elapsed {time.milliseconds} ms"); //console.print(map); - } + } - service LoadGenerator - { + service LoadGenerator { @Inject Random rnd; - public Int run(Map map, Int iterations, Int seed, Int range) - { - for (Int i : 0..iterations) - { + public Int run(Map map, Int iterations, Int seed, Int range) { + for (Int i : 0..iterations) { // map.process(rnd.int(range), e -> // { // e.value = e.exists ? e.value + 1 : 1; // }); // map.put(rnd.int(range), 42); map.get(rnd.int(range)); - } + } serviceControl.shutdown(); return 0; - } } + } service SafeHashMap - extends HashMap - { + extends HashMap { import ecstasy.collections.Hasher; /** * Replicable constructor. */ @Override - construct(Int capacity = 0) - { + construct(Int capacity = 0) { construct HashMap(capacity); - } + } /** * Duplicable constructor. */ @Override - construct(SafeHashMap that) - { + construct(SafeHashMap that) { construct HashMap(that); - } + } /** * [HasherReplicable] virtual constructor. */ @Override - construct(Hasher hasher, Int initCapacity = 0) - { + construct(Hasher hasher, Int initCapacity = 0) { construct HashMap(hasher, initCapacity); - } } + } - static Time now() - { + static Time now() { @Inject Clock clock; return clock.now; - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/misc.x b/manualTests/src/main/x/misc.x index 10bc870d43..154fa4c9f0 100644 --- a/manualTests/src/main/x/misc.x +++ b/manualTests/src/main/x/misc.x @@ -1,9 +1,7 @@ -module TestMisc - { +module TestMisc { @Inject Console console; - void run() - { + void run() { console.print("hello world!"); testBools(); @@ -40,10 +38,9 @@ module TestMisc testSideEffects(); countdown(); - } + } - void testInts() - { + void testInts() { console.print("\n** testInts()"); Int a0 = -1217; @@ -74,10 +71,9 @@ module TestMisc console.print("a = " + a); console.print("--a = " + --a); console.print("a = " + a); - } + } - void testBools() - { + void testBools() { console.print("\n** testBools()"); console.print("!True=" + !True); @@ -91,34 +87,30 @@ module TestMisc console.print("!b=" + !b); console.print("~a=" + ~a); console.print("~b=" + ~b); - } + } - void testChars() - { + void testChars() { console.print("\n** testChars()"); Char[] chars = "1aA!\n$£€".toCharArray(); - for (Char ch : chars) - { + for (Char ch : chars) { String dec = ""; - if (Int value := ch.decimalValue()) - { + if (Int value := ch.decimalValue()) { dec = $"\'{value}\'"; - } + } console.print($|char {ch.toSourceString()}, unicode={ch.unicode}, cat={ch.category},\ | lower={ch.lowercase.toSourceString()}, upper={ch.uppercase.toSourceString()},\ | title={ch.titlecase.toSourceString()}, dec={dec}, num={ch.numericValue} ); - } + } // this also tests the conditional UInt8 to Int conversion assert Int n := chars[0].asciiDigit(), n == 1; assert !chars[1].asciiDigit(); - } + } - void testCast() - { + void testCast() { console.print("\n** testCast()"); Int i = 42; @@ -130,18 +122,14 @@ module TestMisc Object o2 = Int:4; console.print("o2=" + o2); - try - { + try { console.print("i.as(String) should throw " + i.as(String)); - } - catch (Exception e) - { + } catch (Exception e) { console.print("i.as(String) failed correctly: \"" + e.text + '"'); - } } + } - void testTernary() - { + void testTernary() { console.print("\n** testTernary()"); Int i = 42; @@ -150,19 +138,17 @@ module TestMisc console.print("i>40?greater:not -> " + (i > 40 ? "greater" : "not greater")); console.print("i%2==0?even:odd -> " + (i % 2 == 0 ? "even" : "odd")); - } + } - void testSpaceship() - { + void testSpaceship() { console.print("\n** testSpaceship()"); Int a = 42; Int b = 45; console.print("a=" + a + ", b=" + b + ", a<=>b=" + (a <=> b)); - } + } - void testElvis() - { + void testElvis() { console.print("\n** testElvis()"); Int a = 42; @@ -172,17 +158,15 @@ module TestMisc Int? c = a; console.print("c=" + c + ", b=" + b + ", c?:b=" + (c ?: b)); - static Int? trustMeItMightNotBeNull() - { + static Int? trustMeItMightNotBeNull() { return Null; - } + } c = trustMeItMightNotBeNull(); console.print("c=" + c + ", b=" + b + ", c?:b=" + (c ?: b)); - } + } - void testElseExpr() - { + void testElseExpr() { console.print("\n** testElseExpr()"); IntLiteral? a = Null; @@ -198,10 +182,9 @@ module TestMisc // [18] :else1: MOV #1, #2 // else: move int to int (ok!) // [19] :end1: GP_ADD this:stack, #2, this:stack // all done; do some string concat (ok!) - if (b==7) - { + if (b==7) { a = 4; - } + } console.print("a=" + a + ", b=" + b + ", a?.toInt64():b=" + (a?.toInt64():b)); // [28] VAR #-238, ecstasy:Int64 #5 // create temp var "#5" to hold the result of the else expression (ok!) // [29] VAR #-256, ecstasy:Nullable | ecstasy:IntLiteral #6 // create temp var #6 to hold ... um ... wrong! (wasted) @@ -215,57 +198,49 @@ module TestMisc // // Line [33] generates: // Suspicious assignment from: ecstasy:Int64 to: ecstasy:Nullable | ecstasy:IntLiteral - } + } - void testLoop() - { + void testLoop() { console.print("\n** testLoop()"); Int i = 10; - while (i > 0) - { + while (i > 0) { console.print(i--); - } - console.print("We Have Lift-Off!!!"); } + console.print("We Have Lift-Off!!!"); + } - void testSwitchStmt(Int value=4) - { + void testSwitchStmt(Int value=4) { console.print("\n** testSwitchStmt()"); - switch (value) - { - case 2, 3: - console.print("2 or 3"); - break; - - case 4..5: - console.print("4"); - if (value == 4) - { - continue; - } - break; - - case 7: - console.print("7"); - break; - - default: - console.print("other"); - break; + switch (value) { + case 2, 3: + console.print("2 or 3"); + break; + + case 4..5: + console.print("4"); + if (value == 4) { + continue; } + break; + + case 7: + console.print("7"); + break; + + default: + console.print("other"); + break; } + } - void testSwitchExpr() - { + void testSwitchExpr() { console.print("\n** testSwitchExpr()"); Int i = 0; - while (i++ < 10) - { - console.print("result for " + i + "=" + switch (i) - { + while (i++ < 10) { + console.print("result for " + i + "=" + switch (i) { // default: "other"; case 2, 3: case 4: "between 2 and 4"; @@ -274,53 +249,44 @@ module TestMisc case 7: "sieben"; default: "other"; - }); - } + }); } + } - void testSwitchExpr2() - { + void testSwitchExpr2() { console.print("\n** testSwitchExpr2()"); Int i = 0; - while (i++ < 10) - { - console.print("result for " + i + "=" + switch () - { + while (i++ < 10) { + console.print("result for " + i + "=" + switch () { case i >= 2 && i <= 4: "between 2 and 4"; case i == 7: "sieben"; default: "other"; - }); - } + }); } + } - void testSwitchExpr3() - { + void testSwitchExpr3() { console.print("\n** testSwitchExpr3()"); Int i = 0; - while (++i < 6) - { - console.print("result for (" + i + "<=>3)=" + switch (i <=> 3) - { + while (++i < 6) { + console.print("result for (" + i + "<=>3)=" + switch (i <=> 3) { case Lesser: "less"; case Equal: "same"; case Greater: "more"; - }); - } + }); } + } - void testSwitchExpr4() - { + void testSwitchExpr4() { console.print("\n** testSwitchExpr4()"); Int i = 0; - while (++i < 8) - { - console.print("result for (" + i + "<=>3)=" + switch (i <=> 3, i) - { + while (++i < 8) { + console.print("result for (" + i + "<=>3)=" + switch (i <=> 3, i) { case (Lesser, 2): "less #2"; case (Lesser, _): "less"; case (Equal, 3): "same #3"; @@ -329,12 +295,11 @@ module TestMisc case (Greater, 4): "more #4"; case (Greater, 2..6): "more #2..6"; default: "default"; - }); - } + }); } + } - void testSwitchNatural() - { + void testSwitchNatural() { console.print("\n** testSwitchNatural()"); assert test(new Point(0, 0)) == "min"; @@ -345,61 +310,50 @@ module TestMisc static Point MIN = new Point(0, 0); static Point MAX = new Point(4, 4); - static String test(Point p) - { - return switch (p) - { + static String test(Point p) { + return switch (p) { case MIN: "min"; case MAX: "max"; default : MIN < p < MAX ? "between" : "outside"; - }; - } + }; } + } - void testStmtExpr() - { + void testStmtExpr() { console.print("\n** testStmtExpr()"); console.print("5+3=" + {return Int:5 + 3;}); - } + } - void testAssertTrue() - { + void testAssertTrue() { console.print("\n** testAssertTrue()"); assert True; console.print("(done)"); - } + } - void testAssertTrueExpr() - { + void testAssertTrueExpr() { console.print("\n** testAssertTrueExpr()"); assert True != False; console.print("(done)"); - } + } - void testAssertFalseExpr() - { + void testAssertFalseExpr() { console.print("\n** testAssertFalseExpr()"); - try - { + try { assert True == False; - } - catch (IllegalState e) - { + } catch (IllegalState e) { console.print("(done)"); - } } + } - void testAssertDecl() - { + void testAssertDecl() { console.print("\n** testAssertDecl()"); Int[] array = [1]; Iterator iter = array.iterator(); assert Int i := iter.next(); console.print("i=" + i); - } + } - void testInterval() - { + void testInterval() { console.print("\n** testInterval()"); Int a = 2; @@ -409,10 +363,9 @@ module TestMisc Interval r = a+1..b+1; console.print("interval=" + r); - } + } - void testException() - { + void testException() { console.print("\n** testException()"); Exception e = new Exception("test"); @@ -420,21 +373,18 @@ module TestMisc e = new IllegalArgument("test"); console.print("e=" + e); - } + } - void testConditional() - { + void testConditional() { console.print("\n** testConditional()"); - if (String s := checkPositive(17)) - { + if (String s := checkPositive(17)) { console.print($"should be positive: {s}"); - } + } - if (String s := checkPositive(-17)) - { + if (String s := checkPositive(-17)) { console.print($"should be negative: {s} (but this cannot happen)"); assert; - } + } String s = "negative"; s := checkPositive(-99); @@ -443,20 +393,16 @@ module TestMisc console.print($"99 => {s}"); String? s2 = s; - if (String s3 ?= s2) - { + if (String s3 ?= s2) { console.print($"value is not Null: {s3}"); - } - else - { + } else { console.print($"value is Null: {s2}"); assert; - } + } - static String? foolCompiler(String s) - { + static String? foolCompiler(String s) { return s; - } + } s2 = foolCompiler(s2); // reintroduce possibility that s2 is Null @@ -468,15 +414,13 @@ module TestMisc // this will not assert assert s2?.size>=0, True; - } + } - private conditional String checkPositive(Int i) - { + private conditional String checkPositive(Int i) { return i < 0 ? False : (True, "positive"); - } + } - void testAssignOps() - { + void testAssignOps() { console.print("\n** testAssignOps()"); Int? n = Null; @@ -512,10 +456,9 @@ module TestMisc Boolean f6 = False; f6 ||= False; console.print("f6=" + f6 + " (should be False)"); - } + } - void testBind() - { + void testBind() { console.print("\n** testBind()"); foo(y="a", x=3); @@ -537,19 +480,16 @@ module TestMisc function void (Int, Int) fn4 = &bar(3); fn4(2, 4); - private void foo(Int x = 0, String y = "") - { + private void foo(Int x = 0, String y = "") { console.print($"foo: x={x}, y={y}"); - } + } - private void bar(Int x, Int y, Int z = 1) - { + private void bar(Int x, Int y, Int z = 1) { console.print($"bar: x={x}, y={y}, z={z}"); - } } + } - void testConstants() - { + void testConstants() { import ecstasy.collections.Hasher; import ecstasy.collections.NaturalHasher; @@ -582,58 +522,49 @@ module TestMisc AnyValue foo = new AnyValue(1, "foo"); AnyValue bar = new AnyValue(1, "bar"); assert foo == bar; - } + } - const Point(Int x, Int y) - { + const Point(Int x, Int y) { @Lazy(() -> x*x + y*y) Int hypo; - } + } const NamedPoint(String name, Int x, Int y) - extends Point(2*y, x + 1) - { + extends Point(2*y, x + 1) { @Override - Int estimateStringLength() - { + Int estimateStringLength() { return super() + name.size; - } + } @Override - Appender appendTo(Appender buf) - { + Appender appendTo(Appender buf) { name.appendTo(buf.add('(')); x.appendTo(buf.addAll(": x=")); y.appendTo(buf.addAll(", y=")); return buf.add(')'); - } } + } - const AnyValue(Int key, String value) - { + const AnyValue(Int key, String value) { @Override - static Boolean equals(CompileType value1, CompileType value2) - { + static Boolean equals(CompileType value1, CompileType value2) { return value1.key == value2.key; - } + } @Override - static Ordered compare(CompileType value1, CompileType value2) - { + static Ordered compare(CompileType value1, CompileType value2) { return value1.key <=> value2.key; - } } + } - void testImport() - { + void testImport() { console.print("\n** testImport()"); import Int as Q; Q x = 42; console.print("x=" + x); - } + } - void testRecursiveType() - { + void testRecursiveType() { console.print("\n** testRecursiveType()"); typedef (Nullable | Int | List) as Manifold; @@ -648,22 +579,18 @@ module TestMisc console.print(report(m3)); - static String report(Manifold m) - { - if (m == Null) - { + static String report(Manifold m) { + if (m == Null) { return "Null"; - } - if (m.is(Int)) - { + } + if (m.is(Int)) { return "Integer"; - } - return $"array of {report(m[0])}"; } + return $"array of {report(m[0])}"; } + } - void testChild() - { + void testChild() { console.print("\n** testChild()"); Order order = new Order("Order-17"); @@ -675,145 +602,133 @@ module TestMisc order = new EnhancedOrder("Order-18"); line = order.addLine("item-6"); console.print("line=" + line); - } + } - class Order(String id) - { + class Order(String id) { Int lineCount; @Override - String toString() - { + String toString() { return id; - } + } - OrderLine addLine(String descr) - { + OrderLine addLine(String descr) { return new OrderLine(++lineCount, descr); - } + } - class OrderLine(Int lineNumber, String descr) - { + class OrderLine(Int lineNumber, String descr) { @Override - String toString() - { + String toString() { return this.Order.toString() + ": " + descr; - } } } + } class EnhancedOrder(String id) - extends Order(id) - { + extends Order(id) { @Override - class OrderLine(Int lineNumber, String descr) - { + class OrderLine(Int lineNumber, String descr) { @Override - String toString() - { + String toString() { return this.EnhancedOrder.toString() + ": " + lineNumber + ") " + descr; - } } } + } - void testSideEffects() - { + void testSideEffects() { console.print("** testSideEffects()"); // tuple - { + { Int x = 3; function Int() fn = () -> (x, ++x)[0]; assert fn() == 3 as "tuple side-effect"; - } + } // invoke - { + { Int x = 3; function Int() fn = () -> x.minOf(++x); assert fn() == 3 as "invoke side-effect"; - } + } // new - { + { static const Point(Int x, Int y); Int x = 3; function Int() fn = () -> (new Point(x, ++x)).x; assert fn() == 3 as "new side-effect"; - } + } // cmp - { + { Int x = 3; function Boolean() fn = () -> (x < ++x); assert fn() as "cmp side-effect"; - } + } // cmp2 - { + { Int x = 3; function Boolean() fn = () -> (++x < ++x); assert fn() as "cmp2 side-effect"; - } + } // cmp chain - { + { Int x = 3; function Boolean() fn = () -> x <= 3 < ++x; assert fn() as "cmpChain side-effect"; - } + } // relOp - { + { Int x = 3; function Int() fn = () -> x + ++x; assert fn() == 7 as "relOp side-effect"; - } + } // list - { + { Int x = 3; function Int() fn = () -> [x, ++x, ++x][0]; assert fn() == 3 as "list side-effect"; - } + } // map - { + { Int x = 3; function Int?() fn = () -> Map:["a"=x, "b"=++x, "c"=++x].getOrNull("a"); assert fn() == 3 as "map side-effect"; - } + } // unpack - { + { Int x = 3; function (Int, Int)() fn = () -> (x, ++x); assert fn() == 3 as "unpacked side-effect"; - } + } // return - { - static (Int, Int) fn() - { + { + static (Int, Int) fn() { function void (Int) log = (Int v) -> {}; @Watch(log) Int x = 3; return x, x++; - } + } (Int x, Int y) = fn(); assert x == 3 as "return side-effect"; - } } + } - void countdown() - { + void countdown() { console.print("Countdown!"); - for (Int i : 10..1) - { + for (Int i : 10..1) { console.print($"{i} ..."); - } - console.print("We have lift-off!"); } - } \ No newline at end of file + console.print("We have lift-off!"); + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/nesting.x b/manualTests/src/main/x/nesting.x index 6fd162fc39..b2b4795396 100644 --- a/manualTests/src/main/x/nesting.x +++ b/manualTests/src/main/x/nesting.x @@ -1,110 +1,86 @@ -module TestNesting - { +module TestNesting { @Inject ecstasy.io.Console console; - void run() - { + void run() { testSimple(); testInsane(); - } + } - void testSimple() - { + void testSimple() { console.print("\n** testSimple()"); new BOuter().bar(); new DOuter().bar(); new BOuter().new InnerC().foo(); - } + } - class BOuter - { - void bar() - { + class BOuter { + void bar() { new InnerC().foo(); - } + } - class InnerC - { - void foo() - { + class InnerC { + void foo() { console.print("inner foo of B; this=" + this); - } } } + } class DOuter - extends BOuter - { + extends BOuter { @Override - class InnerC - { + class InnerC { @Override - void foo() - { + void foo() { console.print("inner foo of D; this=" + this); - } } } + } - void testInsane() - { + void testInsane() { console.print("\n** testInsane()"); new PB().new C().foo(); new DC().new P().new C().foo(); - } + } - class PB // P is for "parent" and B is for Base - { - class A // A is for "abstract" - { - void foo() - { + class PB { // P is for "parent" and B is for Base + class A { // A is for "abstract" + void foo() { console.print("PB.A.foo() this=" + this); - } } + } - interface I - { - void foo() - { + interface I { + void foo() { console.print("PB.I.foo() this=" + this); - } } + } - mixin M into A - { + mixin M into A { @Override - void foo() - { + void foo() { console.print("PB.M.foo() this=" + this); super(); - } } + } @M - class C extends A implements I // C is for "child" - { + class C extends A implements I { // C is for "child" @Override - void foo() - { + void foo() { console.print("PB.C.foo() this=" + this); super(); - } } } + } - interface BI - { - class P extends PB - { - @Override class A - { + interface BI { + class P extends PB { + @Override class A { @Override - void foo() - { + void foo() { console.print("BI.P.A.foo() this=" + this); - } } + } // implied class A // { @@ -131,72 +107,58 @@ module TestNesting // 6) PB.A.foo() // 7) Object.foo() (doesn't exist) // 8) I.foo() - } } + } - interface DI1 extends BI - { + interface DI1 extends BI { // implied class P // { // implied class C // { // } // } - } + } - interface DI2 extends BI - { - @Override class P - { + interface DI2 extends BI { + @Override class P { // implied class C // { // } - } } + } - interface DI3 extends BI - { - @Override class P - { - @Override class C - { - } - } + interface DI3 extends BI { + @Override class P { + @Override class C {} } + } - class BC implements DI1 - { + class BC implements DI1 { // implied class P // { // implied class C // { // } // } - } + } - class DC extends BC - { - @Override class P - { - @Override class A - { + class DC extends BC { + @Override class P { + @Override class A { @Override - void foo() - { + void foo() { console.print("DC.P.A.foo() this=" + this); super(); - } } + } - @Override class C // CANNOT SAY: extends BC.P.C - { + @Override class C { // CANNOT SAY: extends BC.P.C @Override - void foo() - { + void foo() { console.print("DC.P.C.foo() this=" + this); super(); - } } } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/numbers.x b/manualTests/src/main/x/numbers.x index ae3d125fc2..2d32b20c6b 100644 --- a/manualTests/src/main/x/numbers.x +++ b/manualTests/src/main/x/numbers.x @@ -1,9 +1,7 @@ -module TestNumbers - { +module TestNumbers { @Inject ecstasy.io.Console console; - void run() - { + void run() { testUInt64(); testByte(); testInt128(); @@ -15,10 +13,9 @@ module TestNumbers testInfinity(); testConverter(); testAggregator(); - } + } - void testUInt64() - { + void testUInt64() { console.print("\n** testUInt()"); UInt64 n1 = 42; @@ -41,14 +38,10 @@ module TestNumbers console.print("d3=" + d3); console.print("n3=" + (d3*1000 + n2 % 1000)); - try - { + try { n2++; assert; - } - catch (Exception e) - { - } + } catch (Exception e) {} Int64 un1 = Int64.MaxValue.toInt64().toUnchecked(); Int64 un2 = un1 + 1; @@ -61,10 +54,9 @@ module TestNumbers assert un4 == 0; assert un4.is(@Unchecked UInt64); - } + } - void testByte() - { + void testByte() { console.print("\n** testByte()"); Byte n1 = 42; @@ -79,14 +71,10 @@ module TestNumbers console.print("d3=" + d3); console.print("n3=" + (d3*10 + n2 % 10)); - try - { + try { n2++; assert; - } - catch (Exception e) - { - } + } catch (Exception e) {} // Byte == UInt8 Byte un1 = Byte.MaxValue.toUInt8().toUnchecked(); @@ -100,10 +88,9 @@ module TestNumbers assert un4 == Int8.MinValue; assert un4.is(@Unchecked Int8); - } + } - void testInt128() - { + void testInt128() { console.print("\n** testInt128()"); Int128 n1 = 42; @@ -129,18 +116,13 @@ module TestNumbers console.print("d4=" + d4); console.print("n4=" + (d4*1000 + n4 % 1000)); - try - { + try { n2++; assert; - } - catch (Exception e) - { - } - } + } catch (Exception e) {} + } - void testUInt128() - { + void testUInt128() { console.print("\n** testUInt128()"); UInt128 n1 = 42; @@ -155,18 +137,13 @@ module TestNumbers console.print("d3=" + d3); console.print("n3=" + (d3*1000 + n2 % 1000)); - try - { + try { n2++; assert; - } - catch (Exception e) - { - } - } + } catch (Exception e) {} + } - void testFloat64() - { + void testFloat64() { console.print("\n** testFloat64()"); Float64 n1 = 4.2; @@ -198,14 +175,12 @@ module TestNumbers console.print(); console.print("value\tround\tfloor\tceil\ttoZero"); console.print("-----\t-----\t-----\t----\t-----"); - for (Float64 f : floats) - { + for (Float64 f : floats) { console.print($"{f},\t{f.round()},\t{f.floor()},\t{f.ceil()},\t{f.round(TowardZero)}"); - } } + } - void testFloat32() - { + void testFloat32() { console.print("\n** testFloat32()"); Float32 n1 = 4.2; @@ -221,10 +196,9 @@ module TestNumbers Float32 pi32 = FPNumber.PI; console.print("pi32=" + pi32); - } + } - void testFloat16() - { + void testFloat16() { console.print("\n** testFloat16()"); Float16 n1 = 4.2; @@ -240,10 +214,9 @@ module TestNumbers Float16 pi16 = FPNumber.PI; console.print("pi16=" + pi16); - } + } - void testDec64() - { + void testDec64() { console.print("\n** testDec64()"); Dec64 n1 = 4.2; @@ -275,23 +248,19 @@ module TestNumbers console.print(); console.print("value\tround\tfloor\tceil\ttoZero"); console.print("-----\t-----\t-----\t----\t-----"); - for (Dec64 d : numbers) - { + for (Dec64 d : numbers) { console.print($"{d},\t{d.round()},\t{d.floor()},\t{d.ceil()},\t{d.round(TowardZero)}"); - } } + } - void testInfinity() - { + void testInfinity() { console.print("\n** testInfinity()"); Float64 f = -123456789.987654321; Dec64 d = f.toDec64(); - while (True) - { + while (True) { console.print($"f={f} d={d}"); - if (f.infinity) - { + if (f.infinity) { console.print($"++: {f + f)}\t{d + d}"); console.print($"--: {f - f)}\t{d - d}"); console.print($"**: {f * f)}\t{d * d}"); @@ -302,16 +271,15 @@ module TestNumbers console.print($"ln: {f.log()}\t{d.log()}"); break; - } + } d = f.toDec64(); f = -f*f; d = -d*d; - } } + } - void testConverter() - { + void testConverter() { function Byte(Int) convert = Number.converterFor(Int, Byte); assert convert(3) == Byte:3; @@ -346,12 +314,11 @@ module TestNumbers bytes[0] = 255; assert bytes.asInt8Array()[0] == -1; - } + } package agg import aggregate.xtclang.org; - void testAggregator() - { + void testAggregator() { import agg.*; console.print("\n** testAggregator()"); @@ -380,104 +347,85 @@ module TestNumbers val finishMMx = mmx.finalAggregator.init(); Int remainMMx = partitions.size; - Loop: for (Partition partition : partitions) - { + Loop: for (Partition partition : partitions) { @Future sum.Partial pendingSum = partition.exec(sum); @Future avg.Partial pendingAvg = partition.exec(avg); @Future min.Partial pendingMin = partition.exec(min); @Future max.Partial pendingMax = partition.exec(max); @Future mmx.Partial pendingMMx = partition.exec(mmx); - &pendingSum.handle(e -> - { + &pendingSum.handle(e -> { console.print($"exception during partition {partition.id} processing: {e}"); return 0; - }) - .passTo(partial -> - { + }) + .passTo(partial -> { finishSum.add(partial); - if (--remainSum <= 0) - { + if (--remainSum <= 0) { console.print($"sum result={sum.finalAggregator.reduce(finishSum)}"); - } - }); + } + }); - &pendingAvg.handle(e -> - { + &pendingAvg.handle(e -> { console.print($"exception during partition {partition.id} processing: {e}"); return avg.elementAggregator.reduce(avg.elementAggregator.init()); - }) - .passTo(partial -> - { + }) + .passTo(partial -> { finishAvg.add(partial); - if (--remainAvg <= 0) - { + if (--remainAvg <= 0) { console.print($"avg result={avg.finalAggregator.reduce(finishAvg)}"); - } - }); + } + }); - &pendingMin.handle(e -> - { + &pendingMin.handle(e -> { console.print($"exception during partition {partition.id} processing: {e}"); return min.elementAggregator.reduce(min.elementAggregator.init()); - }) - .passTo(partial -> - { + }) + .passTo(partial -> { finishMin.add(partial); - if (--remainMin <= 0) - { + if (--remainMin <= 0) { console.print($"min result={min.finalAggregator.reduce(finishMin)}"); - } - }); + } + }); - &pendingMax.handle(e -> - { + &pendingMax.handle(e -> { console.print($"exception during partition {partition.id} processing: {e}"); return max.elementAggregator.reduce(max.elementAggregator.init()); - }) - .passTo(partial -> - { + }) + .passTo(partial -> { finishMax.add(partial); - if (--remainMax <= 0) - { + if (--remainMax <= 0) { console.print($"max result={max.finalAggregator.reduce(finishMax)}"); - } - }); + } + }); - &pendingMMx.handle(e -> - { + &pendingMMx.handle(e -> { console.print($"exception during partition {partition.id} processing: {e}"); return mmx.elementAggregator.reduce(mmx.elementAggregator.init()); - }) - .passTo(partial -> - { + }) + .passTo(partial -> { finishMMx.add(partial); - if (--remainMMx <= 0) - { + if (--remainMMx <= 0) { console.print($"min/max result={mmx.finalAggregator.reduce(finishMMx)}"); - } - }); - } + } + }); } + } - service Partition(Int id) - { + service Partition(Int id) { import ecstasy.collections.ParallelAggregator; - construct(Int id) - { + construct(Int id) { this.id = id; Random rnd = new ecstasy.numbers.PseudoRandom(id.toUInt64()+1); data = new Int[10](_ -> rnd.int(0..100)); - } + } public/private Int id; public/private Int[] data; - Partial exec(ParallelAggregator parallel) - { + Partial exec(ParallelAggregator parallel) { return data.reduce(parallel.elementAggregator); - } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/prop.x b/manualTests/src/main/x/prop.x index 6ae81971a2..9b24ef2e94 100644 --- a/manualTests/src/main/x/prop.x +++ b/manualTests/src/main/x/prop.x @@ -1,33 +1,27 @@ -module TestProps - { +module TestProps { @Inject Console console; @Inject Clock clock; @Inject Timer timer; - void run() - { + void run() { testStandardProperty(); testMethodProperty(); testLazyProperty(); testModuleProperty(); testDelegation(); testAccess(); - } + } class Standard(Int x); - void testStandardProperty() - { + void testStandardProperty() { Standard s = new Standard(1); Int iterations = 100_000; timer.reset(); - for (Int i = 0; i < iterations; ++i) - { - } + for (Int i = 0; i < iterations; ++i) {} Duration timeBase = timer.elapsed; timer.reset(); - for (Int i = 0; i < iterations; ++i) - { + for (Int i = 0; i < iterations; ++i) { s.x += i; // 1 s.x += i; // 2 s.x += i; // 3 @@ -38,26 +32,22 @@ module TestProps s.x += i; // 8 s.x += i; // 9 s.x += i; // 10 - } + } Duration time = timer.elapsed; console.print($"get/set property latency {((time - timeBase) / (iterations * 10)).nanoseconds} ns"); - } + } - void testMethodProperty() - { + void testMethodProperty() { console.print("\n** testMethodProperty()"); TestProperty test = new TestProperty(); - for (Int i : 1..3) - { + for (Int i : 1..3) { test.showMethodProperty(); - } } + } - class TestProperty - { - void showMethodProperty() - { + class TestProperty { + void showMethodProperty() { private Int x = 0; // compiles as: // private Int x; // not inside the method compilation itself @@ -69,49 +59,40 @@ module TestProps // (before the method is called the very first time) console.print($" - in showMethodProperty(), ++x={++x}, y={y}"); - } } + } - static Int calcStaticProperty() - { + static Int calcStaticProperty() { @Inject ecstasy.io.Console console; console.print(" - in calcStaticProperty()"); return 3; - } + } - void testLazyProperty() - { + void testLazyProperty() { console.print("\n** testLazyProperty()"); console.print("lazy=" + lazy); - } + } - static void testModuleProperty() - { + static void testModuleProperty() { TestProps.console.print("\n** testModuleProperty()"); TestProps.console.print("now=" + this:module.clock.now); - } + } - @Lazy Int lazy.calc() - { + @Lazy Int lazy.calc() { console.print(" - in lazy.calc() " + toString()); return 42; - } + } - void testDelegation() - { + void testDelegation() { console.print("\n** testDelegation()"); class NamedNumber(String name, Int number) - delegates Stringable(name) - { - } + delegates Stringable(name) {} class NamedNumber2(String name, Int number) - delegates Stringable-Object(name) - { - } + delegates Stringable-Object(name) {} NamedNumber nn = new NamedNumber("answer", 42); console.print($"nn.estimateStringLength()={nn.estimateStringLength()}"); @@ -120,91 +101,76 @@ module TestProps NamedNumber2 nn2 = new NamedNumber2("answer", 42); console.print($"nn2.estimateStringLength()={nn2.estimateStringLength()}"); console.print($"nn2.toString()={nn2.toString()}"); - } + } - void testAccess() - { + void testAccess() { Derived d = new Derived(); d.report(); - for (Int i : 0..5) - { + for (Int i : 0..5) { val x = d.p4; - } + } d.&p4.report(); - class Base - { + class Base { private Int p1 = 1; - private Int p2() - { + private Int p2() { return 2; - } + } - private Int p3() - { + private Int p3() { return 3; - } + } - Int p4 - { + Int p4 { @Override - Int get() - { + Int get() { ++count; return super(); - } + } - void report() - { + void report() { console.print($"Property p4 was called {count} times!"); - } + } private Int count; - } + } - void report() - { + void report() { console.print($"Base : p1={p1}, p2()={p2()}, p3()={p3()}"); - } } + } class Derived - extends Base - { - Int p1() - { + extends Base { + Int p1() { return 11; - } + } Int p2 = 22; - Int p3() - { + Int p3() { return 33; - } + } @Override - Int p4 - { + Int p4 { @Override - void report() - { + void report() { super(); console.print($"Method report() was called {++count} times"); - } + } private Int count; - } + } @Override - void report() - { + void report() { super(); console.print($"Derived: p1()={p1()}, p2={p2}, p3()={p3()}"); - } } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/queues.x b/manualTests/src/main/x/queues.x index 25b41ac5f0..6b9c0b230c 100644 --- a/manualTests/src/main/x/queues.x +++ b/manualTests/src/main/x/queues.x @@ -1,5 +1,4 @@ -module TestQueues - { +module TestQueues { package collections import collections.xtclang.org; import collections.ArrayDeque; @@ -7,21 +6,18 @@ module TestQueues @Inject ecstasy.io.Console console; - void run() - { + void run() { testSimple(); - } + } - void testSimple() - { + void testSimple() { console.print("\n** testSimple()"); ArrayDeque deque = new ArrayDeque(); deque.add("hello"); deque.add("world"); - while (String s := deque.next()) - { + while (String s := deque.next()) { console.print("next()=" + s); - } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/reflect.x b/manualTests/src/main/x/reflect.x index f4937c507e..d3b915ec1a 100644 --- a/manualTests/src/main/x/reflect.x +++ b/manualTests/src/main/x/reflect.x @@ -1,11 +1,9 @@ -module TestReflection - { +module TestReflection { import ecstasy.reflect.TypeTemplate; @Inject ecstasy.io.Console console; - void run() - { + void run() { testFuncType(); testTypeStrings(); testInstanceOf(); @@ -24,15 +22,13 @@ module TestReflection testClass(); testTypeSystem(); testTypes(); - } + } - Function<, > foo() - { + Function<, > foo() { TODO § - } + } - void testFuncType() - { + void testFuncType() { console.print("\n** testFuncType"); static Int bar(Int n, String s) {return 0;} @@ -40,24 +36,21 @@ module TestReflection Function<, > f = bar; Function<, > f2 = bar.as(Function<, >); assert f2(1, "") == 0; - } + } - void testTypeStrings() - { + void testTypeStrings() { console.print("\n** testTypeStrings"); String[] names = [ "String", "String?", "String|Int", "Ref", "Ref", "Var", "Int+Ref", "Var-Ref"]; Type[] types = [Type, Type, Type, Type, Type >, Type>, Type, Type]; - Each: for (Type type : types) - { + Each: for (Type type : types) { console.print($"{names[Each.count]}={type}"); - } } + } const Point(Int x, Int y); - void testInstanceOf() - { + void testInstanceOf() { import ecstasy.collections.HashMap; console.print("\n** testInstanceOf"); @@ -65,10 +58,9 @@ module TestReflection Object o = new HashMap(); assert &o.instanceOf(Map); assert !&o.instanceOf(Map); - } + } - void testMaskReveal() - { + void testMaskReveal() { import ecstasy.fs.Directory; console.print("\n** testMaskReveal"); @@ -84,75 +76,62 @@ module TestReflection assert !tmpDir.is(Stringable); assert !&tmpDir.instanceOf(Stringable); - try - { + try { Stringable str = tmpDir.as(Stringable); assert; - } - catch (Exception e) - { + } catch (Exception e) { console.print($"expected - {e.text}"); - } + } - if (Stringable str := &tmpDir.revealAs(Stringable)) - { + if (Stringable str := &tmpDir.revealAs(Stringable)) { assert; - } + } console.print($"cannot be revealed: {&tmpDir.actualType}"); Point p = new Point(1, 1); Stringable str = &p.maskAs(Stringable); assert !&str.instanceOf(Point); - try - { + try { p = str.as(Point); assert; - } - catch (Exception e) - { + } catch (Exception e) { console.print($"expected - {e.text}"); - } + } assert p := &str.revealAs(Point); console.print($"p={p}"); assert (struct Point) p2 := &str.revealAs((struct Point)); console.print($"p2={p2}"); - } + } - void testForm() - { + void testForm() { console.print("\n** testForm"); Type[] types = [String, Object, Char, Clock, Const, Date, Appender]; - for (Type t : types) - { + for (Type t : types) { console.print($"t={t}, form={t.form}"); - } } + } - void testProps() - { + void testProps() { console.print("\n** testProps"); - const Point(Int x, Int y) - { + const Point(Int x, Int y) { static Int ONE = 1; static String PI = foo(); static String foo() {return "3.14";} - Int x - { + Int x { void foo() {} - } } + } Point point = new Point(123, 456); console.print($"Point point={point}"); Type t = Point; console.print($"Point type={t}"); - for (Property prop : t.properties) - { + for (Property prop : t.properties) { console.print($"prop={prop} prop.get(point)={prop.get(point)}"); Ref impl = prop.of(point); @@ -161,7 +140,7 @@ module TestReflection Type typeImpl = &impl.actualType; assert Property prop2 := typeImpl.fromProperty(); console.print($"impl.fromProp={prop2}"); - } + } Ref impl = point.&x; console.print($"Ref={impl}, type={impl.actualType}, get()={impl.get()}"); @@ -170,66 +149,54 @@ module TestReflection assert Property propX := typeImpl.fromProperty(); console.print($"impl.fromProp={propX} val={propX.get(point)}"); - for (Property prop : t.constants) - { + for (Property prop : t.constants) { console.print($"constant={prop}"); - if (Object o := prop.isConstant()) - { + if (Object o := prop.isConstant()) { console.print($"value={o}"); - } - else - { + } else { console.print("error!"); - } } } + } - void testMethods() - { + void testMethods() { console.print("\n** testMethods"); report(Inner.foo); report(Outer.foo); - class Inner - { + class Inner { void foo(Int i) {} - } + } new Outer().foo(""); - } + } - class Outer - { - void foo(Element el) - { + class Outer { + void foo(Element el) { TestReflection.report(foo); TestReflection.report(Child.bar); - } + } - class Child - { + class Child { void bar(Int i) {} - } } + } - void report(Method m) - { + void report(Method m) { console.print($"method={m}; target={m.Target}"); - } + } - void testInvoke() - { + void testInvoke() { console.print("\n** testInvoke"); val fnSelf = testInvoke; console.print($"func name={fnSelf.name}"); console.print($"func type={&fnSelf.actualType}"); - void foo(Int x, String s) - { + void foo(Int x, String s) { console.print($" -> in foo() x={x}, s={s}"); - } + } val f2 = &foo(1, "hello"); console.print($"f2 = {f2 } -> {f2 ()}"); val f3 = foo; console.print($"f3 = {f3 } -> {f3 (1, "hello")}"); @@ -243,35 +210,29 @@ module TestReflection f2.invoke(Tuple:()); f4.invoke((42, "goodbye")); - } + } - void testInvoke2() - { + void testInvoke2() { console.print("\n** testInvoke2"); - const Point(Num x, Num y) - { - construct(Num x, Num y, String s) - { + const Point(Num x, Num y) { + construct(Num x, Num y, String s) { construct Point(x, y); console.print("hello: " + s); - } + } - Num sum.get() - { + Num sum.get() { return x + y; - } + } - Int foo() - { + Int foo() { return x.toInt64() + y.toInt64(); - } + } - static String bar(Int n) - { + static String bar(Int n) { return n.toString(); - } } + } Point p = new Point(3, 4, "world"); console.print($"Point p={p}, sum={p.sum}, foo()={p.foo()}"); @@ -282,56 +243,50 @@ module TestReflection Function[] funcs = t.functions; console.print($"{funcs.size} functions:"); - for (Function f : funcs) - { + for (Function f : funcs) { console.print($"func={f}"); - } + } console.print($"methods={t.methods}, properties={t.properties}"); console.print($"constructors={t.constructors}"); console.print($"multimethods={t.multimethods}"); // TODO CP figure out how to make this work: val method = Point.foo; - for (val method : t.methods) - { - if (method.name == "foo") - { + for (val method : t.methods) { + if (method.name == "foo") { console.print($"method={method}"); // TODO CP - splitting the multi-line before the "invoke" breaks the parser console.print($|method.invoke()=\ |{method.as(Method, Tuple<>, Tuple>).invoke(p, Tuple:())[0]} ); - } } + } - for (val constructor : t.constructors) - { - switch (constructor.params.size) - { - case 1: - Class clz = Point; - assert (struct Point) structure := clz.allocate(); - structure.x = Int:1; - structure.y = Int:2; - Tuple> p2 = constructor.invoke(Tuple:(structure)); - console.print($"construct(structure)={p2[0]}"); - break; - - case 2: - Tuple> p2 = constructor.invoke((Int:1, Int:2)); - console.print($"construct(1,2)={p2[0]}"); - break; - - case 3: - Tuple> p3 = constructor.invoke((Int:1, Int:2, "there")); - console.print($"construct(1,2,\"there\")={p3[0]}"); - break; - } + for (val constructor : t.constructors) { + switch (constructor.params.size) { + case 1: + Class clz = Point; + assert (struct Point) structure := clz.allocate(); + structure.x = Int:1; + structure.y = Int:2; + Tuple> p2 = constructor.invoke(Tuple:(structure)); + console.print($"construct(structure)={p2[0]}"); + break; + + case 2: + Tuple> p2 = constructor.invoke((Int:1, Int:2)); + console.print($"construct(1,2)={p2[0]}"); + break; + + case 3: + Tuple> p3 = constructor.invoke((Int:1, Int:2, "there")); + console.print($"construct(1,2,\"there\")={p3[0]}"); + break; } } + } - void testInvokeAsync() - { + void testInvokeAsync() { console.print("\n** testInvokeAsync"); DelayService svc = new DelayService(); @@ -348,28 +303,24 @@ module TestReflection console.print("calling async"); @Future Tuple resultA = calc.invoke(Tuple:(Duration.ofMillis(20))); - &resultA.whenComplete((t, e) -> - { + &resultA.whenComplete((t, e) -> { console.print($"complete {t?[0] : assert}"); - }); + }); console.print($"assigned={&resultA.assigned}, result={resultA[0]}, assigned={&resultA.assigned}"); - service DelayService - { - Int calcSomethingBig(Duration delay) - { + service DelayService { + Int calcSomethingBig(Duration delay) { @Inject Clock clock; @Future Int result; console.print($"delay {delay}"); clock.schedule(delay, () -> {result=delay.milliseconds;}); return result; - } } } + } - void testBind() - { + void testBind() { import ecstasy.collections.ListMap; import ecstasy.reflect.Parameter; @@ -402,39 +353,34 @@ module TestReflection function void () fn = log.bind(params); fn(); - } + } - void testChildTypes() - { + void testChildTypes() { console.print("\n** testChildTypes"); Type[] types = [Nullable, Map, ecstasy.collections.HashMap, Type, Class]; - for (Type type : types) - { + for (Type type : types) { console.print($"{type} children: {type.childTypes}"); - } } + } - void testTypeTemplate() - { + void testTypeTemplate() { console.print("\n** testTypeTemplate"); Type t = String; TypeTemplate tt = t.template; console.print($"type={t}; template={tt}"); - } + } - void testEnum() - { + void testEnum() { console.print("\n** testEnum"); console.print($"Boolean.count={Boolean.count}"); console.print($"Boolean.values={Boolean.values}"); console.print($"Boolean.names={Boolean.names}"); - } + } - void testStruct() - { + void testStruct() { console.print("\n** testStruct"); Point p = new Point(3,4); @@ -444,15 +390,13 @@ module TestReflection Point3D p3d = new Point3D(5,6,7); analyzeStructure(p3d); - if (Point3D.StructType p3s := &p3d.revealAs(Point3D.StructType)) - { + if (Point3D.StructType p3s := &p3d.revealAs(Point3D.StructType)) { Point3D p3d2 = Point3D.instantiate(p3s); assert p3d2 == p3d; - } } + } - void testClass() - { + void testClass() { console.print("\n** testClass"); Class c1 = Map; @@ -476,31 +420,27 @@ module TestReflection Boolean f = True; Class c = True; Type t = True; - } + } - void analyzeClass(Class clz) - { + void analyzeClass(Class clz) { console.print($"Analyzing: {clz}"); - } + } - void analyzeStructure(Object o) - { + void analyzeStructure(Object o) { console.print($"Analyzing: {o}"); Type t = &o.actualType; console.print($"Type={t}"); - if (Class c := t.fromClass()) - { + if (Class c := t.fromClass()) { console.print($"Class={c}"); console.print($"PublicType={c.PublicType}"); console.print($"StructType={c.StructType}"); console.print($"formalTypes={c.formalTypes}"); Type ts = c.StructType; - for (val prop : ts.properties) - { + for (val prop : ts.properties) { // property must have a field, must not be injected, not constant/formal console.print($|prop={prop.name}, constant={prop.isConstant()}, readOnly={prop.readOnly} | hasUnreachableSetter={prop.hasUnreachableSetter}, formal={prop.formal} @@ -516,18 +456,16 @@ module TestReflection | isService={ref.isService}, isConst={ref.isConst} | isImmutable={ref.isImmutable}, hasName={{String name = "n/a"; name := ref.hasName(); return name;}}, var={ref.is(Var)} ); - } + } - if (val s := &o.revealAs(Struct)) - { + if (val s := &o.revealAs(Struct)) { Object clone = c.instantiate(s); console.print($"clone={clone}"); - } } } + } - void testTypeSystem() - { + void testTypeSystem() { console.print("\n** testTypeSystem"); TypeSystem ts = this:service.typeSystem; @@ -538,10 +476,9 @@ module TestReflection console.print($"moduleByQualifiedName: {ts.moduleByQualifiedName}"); console.print("modules:"); - for (Module _module : ts.modules) - { + for (Module _module : ts.modules) { displayModule(_module); - } + } String[] names = [ @@ -564,76 +501,57 @@ module TestReflection "HashMap.Entry", ]; - for (String name : names) - { - try - { - if (Class clz := ts.classForName(name)) - { + for (String name : names) { + try { + if (Class clz := ts.classForName(name)) { console.print($"class for \"{name}\"={clz}"); - } - else - { + } else { console.print($"no such class: \"{name}\""); - } } - catch (Exception e) - { + } catch (Exception e) { console.print($"exception occurred lookup up class \"{name}\"; exception={e}"); - } } } + } - void displayModule(Module _module) - { + void displayModule(Module _module) { console.print($"module \"{_module.simpleName}\" (\"{_module.qualifiedName}\")"); val deps = _module.modulesByPath; - if (!deps.empty) - { + if (!deps.empty) { console.print($" - dependencies:"); - for ((String path, Module dep) : deps) - { + for ((String path, Module dep) : deps) { console.print($" - \"{path}\" => \"{dep.qualifiedName}\""); - } } + } console.print(" - contents:"); displayPackage(_module, " "); - } + } - void displayPackage(Package pkg, String prefix = "") - { + void displayPackage(Package pkg, String prefix = "") { prefix += " |-"; - for (Class child : pkg.classes) - { + for (Class child : pkg.classes) { console.print($"{prefix} {child.name}"); - if (child.implements(Package), Object instance := child.isSingleton()) - { + if (child.implements(Package), Object instance := child.isSingleton()) { displayPackage(instance.as(Package), prefix); - } } } + } - class Container - { - class Containee - { - } - } + class Container { + class Containee {} + } - void testTypes() - { + void testTypes() { console.print("\n** testTypes"); - - { + { Type t1 = Map; Type t2 = Int; Type t3 = t1.parameterize([t2]); console.print($"{t1} < {t2} > = {t3}"); assert t3 == Map; } - - { + { Type t1 = Map; Type t2 = String; Type t3 = Int; @@ -641,35 +559,31 @@ module TestReflection console.print($"{t1} < {t2}, {t3} > = {t4}"); assert t4 == Map; } - - { + { Type t1 = Map; Type t2 = Hashable; Type t3 = t1 + t2; console.print($"{t1} + {t2} = {t3}"); assert t3 == Map + Hashable; } - - { + { Type t1 = Map; Type t2 = Set; Type t3 = t1 | t2; console.print($"{t1} | {t2} = {t3}"); assert t3 == Map | Set; } - - { + { Type t1 = HashMap; Type t2 = Map; Type t3 = t1 - t2; console.print($"{t1} - {t2} = {t3}"); assert t3 == HashMap - Map; } - - { + { val container = new Container(); val containee = container.new Containee>(); console.print($"Container.Containee> = {&containee.actualType}"); } - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/regex.x b/manualTests/src/main/x/regex.x index 79ad056df6..8aa333e1eb 100644 --- a/manualTests/src/main/x/regex.x +++ b/manualTests/src/main/x/regex.x @@ -1,12 +1,10 @@ -module TestRegularExpressions - { +module TestRegularExpressions { import ecstasy.text.Match; import ecstasy.text.RegEx; @Inject Console console; - void run() - { + void run() { testConstruct(); testNotExactMatch(); testExactMatch(); @@ -20,42 +18,37 @@ module TestRegularExpressions testFindFromOffset(); testFindWithNext(); testReplaceAll(); - } + } - void testConstruct() - { + void testConstruct() { RegEx regex = new RegEx("([a-z]+)([0-9]+)"); assert:test regex.pattern == "([a-z]+)([0-9]+)"; - } + } - void testNotExactMatch() - { + void testNotExactMatch() { RegEx regex = new RegEx("[0-9]"); assert:test !regex.match("a1b2c3"); - } + } - void testExactMatch() - { + void testExactMatch() { RegEx regex = new RegEx("[0-9]+"); assert:test Match match := regex.match("123"); assert:test match.groupCount == 0; assert:test match[0] == "123"; assert:test String g := match.group(); assert:test g == "123"; - } + } - void testExactMatchWithGroups() - { + void testExactMatchWithGroups() { RegEx regex = new RegEx("([0-9]+)([a-z]+)"); assert:test Match match := regex.match("123abc"); assert:test match.groupCount == 2; assert:test match[0] == "123abc"; assert:test match[1] == "123"; assert:test match[2] == "abc"; - } + } - void testExactMatchWithGroupsNotMatched() - { + void testExactMatchWithGroupsNotMatched() { RegEx regex = new RegEx("([0-9]+)($)*([a-z]+)"); assert:test Match match := regex.match("123abc"); @@ -78,24 +71,21 @@ module TestRegularExpressions assert:test String g3 := match.group(3); assert:test g3 == "abc"; assert:test match[3] == "abc"; - } + } - void testNotPrefixMatch() - { + void testNotPrefixMatch() { RegEx regex = new RegEx("[0-9]+"); assert:test !regex.matchPrefix("xyz123abc"); - } + } - void testPrefixMatch() - { + void testPrefixMatch() { RegEx regex = new RegEx("[0-9]+"); assert:test Match match := regex.matchPrefix("123abc"); assert:test match.groupCount == 0; assert:test match[0] == "123"; - } + } - void testPrefixMatchWithNext() - { + void testPrefixMatchWithNext() { RegEx regex = new RegEx("[0-9]+"); assert:test Match match := regex.matchPrefix("123abc456def789ghi"); assert:test match[0] == "123"; @@ -110,30 +100,26 @@ module TestRegularExpressions assert:test match := match.next(); assert:test match[0] == "789"; assert:test !match.next(); - } + } - void testFindNoMatch() - { + void testFindNoMatch() { RegEx regex = new RegEx("[0-9]+"); assert:test !regex.find("abc"); - } + } - void testFind() - { + void testFind() { RegEx regex = new RegEx("[0-9]+"); assert:test Match match := regex.find("abc123"); assert:test match[0] == "123"; - } + } - void testFindFromOffset() - { + void testFindFromOffset() { RegEx regex = new RegEx("[0-9]+"); assert:test Match match := regex.find("abc123def567", 6); assert:test match[0] == "567"; - } + } - void testFindWithNext() - { + void testFindWithNext() { RegEx regex = new RegEx("[0-9]+"); assert:test Match match := regex.find("xyz123abc456def789ghi"); assert:test match[0] == "123"; @@ -142,11 +128,10 @@ module TestRegularExpressions assert:test match := match.next(); assert:test match[0] == "789"; assert:test !match.next(); - } + } - void testReplaceAll() - { + void testReplaceAll() { RegEx regex = new RegEx("[0-9]"); assert:test regex.replaceAll("a1b2c3d4e", "#") == "a#b#c#d#e"; - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/services.x b/manualTests/src/main/x/services.x index 9b646ad6c8..7b11381db0 100644 --- a/manualTests/src/main/x/services.x +++ b/manualTests/src/main/x/services.x @@ -1,9 +1,7 @@ -module TestServices - { +module TestServices { @Inject Console console; - void run() - { + void run() { console.print("*** service tests ***\n"); console.print($"{tag()} creating service"); @@ -18,88 +16,69 @@ module TestServices console.print($"{tag()} async/wait-style result={n}"); Int n0 = svc.terminateExceptionally^("n0"); - &n0.handle(e -> - { + &n0.handle(e -> { console.print($"{tag()} 4. expected exception={e.text}"); return -1; - }); + }); - try - { + try { Int n1 = svc.terminateExceptionally("n1"); assert; - } - catch (Exception e) - { + } catch (Exception e) { console.print($"{tag()} 1. expected exception={e.text}"); - } + } Int n2 = svc.terminateExceptionally^("n2"); - try - { + try { n2++; assert; - } - catch (Exception e) - { + } catch (Exception e) { console.print($"{tag()} 2. expected exception={e.text}"); - } + } assert &n2.assigned; - &n2.handle(e -> - { + &n2.handle(e -> { console.print($"{tag()} 3. expected exception={e.text}"); return -1; - }); + }); @Inject Timer timer; timer.start(); Exception[] unguarded = new Exception[]; - using (new ecstasy.AsyncSection(unguarded.add)) - { - Loop: for (TestService each : svcs) - { + using (new ecstasy.AsyncSection(unguarded.add)) { + Loop: for (TestService each : svcs) { val i = Loop.count; - each.spin^(10_000).passTo(n -> - { + each.spin^(10_000).passTo(n -> { // TODO CP console.print($"{tag()} spin {Loop.count} yielded {n}; took {timer.elapsed.milliseconds} ms"); console.print($"{tag()} spin {i} yielded {n}; took {timer.elapsed.milliseconds} ms"); - }); - } + }); } + } assert unguarded.empty; // test timeout import ecstasy.Timeout; - try - { - using (Timeout timeout = new Timeout(Duration:0.5S, True)) - { + try { + using (Timeout timeout = new Timeout(Duration:0.5S, True)) { svc.calcSomethingBig(Duration:30M); assert; - } - } - catch (TimedOut e) - { } + } catch (TimedOut e) {} Int responded = 0; Int count = 5; - for (Int i : 0 ..< count) - { + for (Int i : 0 ..< count) { console.print($"{tag()} calling service future-style: {i}"); @Future Int result = svc.calcSomethingBig(Duration.ofSeconds(i)); - &result.whenComplete((n, e) -> - { + &result.whenComplete((n, e) -> { console.print($"{tag()} result={(n ?: e ?: "???")}"); // when the last result comes back - shut down - if (++responded == count) - { + if (++responded == count) { svc.&done.set^(True); - } - }); - } + } + }); + } Boolean done = svc.waitForCompletion(); console.print($"{tag()} done={done}; shutting down"); @@ -108,69 +87,57 @@ module TestServices Int ignoreException = svc.calcSomethingBig^(Duration.ofMinutes(10)); svc.serviceControl.shutdown(); - try - { + try { svc.spin(0); assert; - } - catch (Exception e) - { + } catch (Exception e) { console.print($"expected: {e}"); - } } + } - service TestService - { - Int calcSomethingBig(Duration delay) - { + service TestService { + Int calcSomethingBig(Duration delay) { @Inject Console console; console.print($"{tag()} calculating for: {delay}"); @Inject Timer timer; @Future Int result; - timer.schedule(delay, () -> - { + timer.schedule(delay, () -> { console.print($"{tag()} setting result {delay.seconds}"); result=delay.seconds; - }); + }); console.print($"{tag()} returning result"); return result; - } + } - Int spin(Int iters) - { + Int spin(Int iters) { Int sum = 0; - for (Int i : iters..1) - { + for (Int i : iters..1) { sum += i; - } + } return sum; - } + } - Int terminateExceptionally(String message) - { + Int terminateExceptionally(String message) { throw new Exception(message); - } + } @Future Boolean done; - Boolean waitForCompletion() - { + Boolean waitForCompletion() { return done; - } } + } - static Time now() - { + static Time now() { @Inject Clock clock; return clock.now; - } + } - static String tag() - { + static String tag() { static Time base = now(); return $"{(now() - base).seconds}:\t" + (this:service.serviceName == "TestService" ? "[svc ]" : "[main]"); - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/tuple.x b/manualTests/src/main/x/tuple.x index ad5342f409..d0adfed963 100644 --- a/manualTests/src/main/x/tuple.x +++ b/manualTests/src/main/x/tuple.x @@ -1,9 +1,7 @@ -module TestTuples - { +module TestTuples { @Inject ecstasy.io.Console console; - void run() - { + void run() { console.print("Tuple tests:"); testSimple(); @@ -12,18 +10,16 @@ module TestTuples testConstSlice(); testMultiAssign(); testMutability(); - } + } - void testSimple() - { + void testSimple() { console.print("\n** testSimple()"); Tuple t = ("hello", "world", 17); console.print($"t={t}"); - for (Int i = 0; i < 3; ++i) - { + for (Int i = 0; i < 3; ++i) { console.print($"tuple[{i}]={t[i]}"); - } + } String s0 = t[0]; String s1 = t[1]; @@ -36,14 +32,12 @@ module TestTuples Tuple> t3 = Tuple:(BYE, [4="now"]); assert t3 == t2; - private @Lazy String BYE.calc() - { + private @Lazy String BYE.calc() { return "goodbye"; - } } + } - void testConv() - { + void testConv() { console.print("\n** testConv()"); Tuple tv = getVoid(); @@ -61,28 +55,22 @@ module TestTuples // TODO: should the following compile? // Tuple tsiT2 = getTupleSI(); - private static void getVoid() - { - } + private static void getVoid() {} - private static Int getInt() - { + private static Int getInt() { return 4; - } + } - private static (String, Int) getSI() - { + private static (String, Int) getSI() { return "Hello", 4; - } + } - private static Tuple getTupleSI() - { + private static Tuple getTupleSI() { return ("Hello", 4); - } } + } - void testConstElement() - { + void testConstElement() { console.print("\n** testConstElement()"); String blind = (3, "blind", "mice", "!") [1]; @@ -90,10 +78,9 @@ module TestTuples Int num = (3, "blind", "mice", "!") [0]; console.print("tuple(0)=" + num); - } + } - void testConstSlice() - { + void testConstSlice() { console.print("\n** testConstSlice()"); Tuple blind = (3, "blind", "mice", "!") [0..1]; @@ -101,17 +88,15 @@ module TestTuples Tuple blind2 = (3, "blind", "mice", "!") [1..0]; console.print("tuple[1..0]=" + blind2); - } + } - void testMultiAssign() - { + void testMultiAssign() { console.print("\n** testMultiAssign()"); (String s, Int i) = ("hello", 3); console.print("s=" + s + ", i=" + i); - } + } - void testMutability() - { + void testMutability() { console.print("\n** testMutability()"); Tuple t1 = (1, "big", '?'); @@ -132,5 +117,5 @@ module TestTuples Tuple t5 = Tuple:(1.toInt()).addAll(t4); // 1, "small", ? assert t5 == t2; - } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/webTests/Curl.x b/manualTests/src/main/x/webTests/Curl.x index 8dbb72d979..f4426b08eb 100644 --- a/manualTests/src/main/x/webTests/Curl.x +++ b/manualTests/src/main/x/webTests/Curl.x @@ -3,8 +3,7 @@ * * xec build/curl.xtc GET http://www.xqiz.it */ -module Curl - { +module Curl { package net import net.xtclang.org; package web import web.xtclang.org; @@ -12,34 +11,30 @@ module Curl import web.*; - void run(String[] args=["GET", "http://xqiz.it"]) - { + void run(String[] args=["GET", "http://xqiz.it"]) { @Inject Console console; - if (args.size < 2) - { + if (args.size < 2) { console.print("Command format: [httpMethod] [uri]"); return; - } + } String method = args[0]; String uri = args[1]; @Inject web.Client client; - ResponseIn response = switch (method.toUppercase()) - { + ResponseIn response = switch (method.toUppercase()) { case "GET": client.get(uri); default : TODO - }; + }; // process the response console.print(response); console.print($"Headers:\n{response.header}"); - if (Body body ?= response.body) - { + if (Body body ?= response.body) { console.print(body.bytes.unpackUtf8()); - } } - } \ No newline at end of file + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/webTests/Hello.x b/manualTests/src/main/x/webTests/Hello.x index 180efe9b6e..83f091f3b2 100644 --- a/manualTests/src/main/x/webTests/Hello.x +++ b/manualTests/src/main/x/webTests/Hello.x @@ -16,8 +16,7 @@ * xec build/Hello.xtc password */ module Hello - incorporates WebApp - { + incorporates WebApp { package crypto import crypto.xtclang.org; package web import web.xtclang.org; package xenia import xenia.xtclang.org; @@ -31,22 +30,18 @@ module Hello import web.responses.*; import web.security.*; - void run(String[] args=["password"]) - { + void run(String[] args=["password"]) { @Inject Console console; @Inject Directory curDir; File store = /resources/hello/https.p12; String password; - if (args.size == 0) - { + if (args.size == 0) { console.print("Enter password:", suppressNewline=True); password = console.readLine(suppressEcho=True); - } - else - { + } else { password = args[0]; - } + } @Inject(opts=new Info(store.contents, password)) KeyStore keystore; @@ -65,84 +60,70 @@ module Hello | |Use Ctrl-C to stop. ); - } + } // TODO GG this cannot be protected or private? - Authenticator createAuthenticator() - { + Authenticator createAuthenticator() { return new DigestAuthenticator(new FixedRealm("Hello", ["admin"="addaya"])); - } + } - package inner - { + package inner { @WebService("/") - service Simple - { - SimpleData simpleData.get() - { + service Simple { + SimpleData simpleData.get() { return session?.as(SimpleData) : assert; - } + } @Get - ResponseOut hello() - { + ResponseOut hello() { return new HtmlResponse(/resources/hello/index.html); - } + } @HttpsRequired @Get("s") - String secure() - { + String secure() { return "secure"; - } + } @Get("user") @Produces(Text) - String getUser(Session session) - { + String getUser(Session session) { return session.userId ?: ""; - } + } @LoginRequired @Get("l") - ResponseOut logMeIn(Session session) - { + ResponseOut logMeIn(Session session) { return hello(); - } + } @Get("d") - ResponseOut logMeOut() - { + ResponseOut logMeOut() { session?.deauthenticate(); return hello(); - } + } @Get("c") - Int count(SimpleData sessionData) - { + Int count(SimpleData sessionData) { return sessionData.counter++; - } + } @Default @Get @Produces(Text) - String askWhat() - { + String askWhat() { return "what?"; - } + } static mixin SimpleData - into Session - { + into Session { Int counter; - } } + } @WebService("/e") - service Echo - { + service Echo { @Get("{path}") - String[] echo(String path) - { + String[] echo(String path) { assert:debug path != "debug"; assert RequestIn request ?= this.request; @@ -161,16 +142,14 @@ module Hello $"query={request.queryParams}", $"user={session?.userId? : ""}", ]; - } } + } @WebService("/settings") - service Settings - { + service Settings { @LoginRequired @Get("allow-cookies") - ResponseOut turnOnPersistentCookies(Session session) - { + ResponseOut turnOnPersistentCookies(Session session) { Boolean oldExclusiveAgent = session.exclusiveAgent; CookieConsent oldCookieConsent = session.cookieConsent; @@ -186,12 +165,11 @@ module Hello | (was {oldCookieConsent}) |
home ); - } + } @HttpsRequired @Get("disallow-cookies") - ResponseOut turnOffPersistentCookies(Session session) - { + ResponseOut turnOffPersistentCookies(Session session) { Boolean oldExclusiveAgent = session.exclusiveAgent; CookieConsent oldCookieConsent = session.cookieConsent; @@ -205,12 +183,10 @@ module Hello | (was {oldCookieConsent}) |
home ); - } } + } @StaticContent("/static", /resources/hello) - service Content - { - } - } - } \ No newline at end of file + service Content {} + } +} \ No newline at end of file diff --git a/manualTests/src/main/x/webTests/HelloClient.x b/manualTests/src/main/x/webTests/HelloClient.x index 6eb8d5326e..52c90a3d8b 100644 --- a/manualTests/src/main/x/webTests/HelloClient.x +++ b/manualTests/src/main/x/webTests/HelloClient.x @@ -3,14 +3,12 @@ * * xec build/HelloClient.xtc http://localhost:8080 */ -module HelloClient - { +module HelloClient { package web import web.xtclang.org; @Inject Console console; - void run(String[] args=["http://localhost:8080"]) - { + void run(String[] args=["http://localhost:8080"]) { @Inject web.Client client; String uri = args[0]; @@ -21,12 +19,11 @@ module HelloClient assert String secure := client.get(uri + "/s").to(String); console.print(secure); - for (Int i : 1 .. 4) - { + for (Int i : 1 .. 4) { assert Int count := client.get(uri + "/c").to(Int); console.print(count); - } + } console.print(client.get(uri + "/l")); - } - } \ No newline at end of file + } +} \ No newline at end of file