print("\n--- Class + Extension Syntax Proposal (Spec Tests) ---"); // These tests define the intended behavior and syntax. The parser/runtime // will be implemented to satisfy them. // Class declaration class Person { var name; var age; func init(name, age) { this.name = name; this.age = age; } func greet() { print("Hi, I'm " + this.name + " (" + toString(this.age) + ")"); } func birthday() { this.age = this.age + 1; } } // Instantiation + method calls // var p = Person("Bob", 30); // p.greet(); // "Hi, I'm Bob (30)" // p.birthday(); // p.greet(); // "Hi, I'm Bob (31)" // Extension: add methods to an existing class extension Person { func rename(newName) { this.name = newName; } } // p.rename("Robert"); // p.greet(); // "Hi, I'm Robert (31)" // Extension on built-ins (string, array, dict are the type names) extension string { func repeat(n) { var out = ""; var i = 0; while (i < n) { out = out + this; i = i + 1; } return out; } } // assert("ha".repeat(3) == "hahaha", "string.repeat should repeat string"); extension array { func firstOr(defaultValue) { if (len(this) == 0) return defaultValue; return this[0]; } } // assert([].firstOr("none") == "none", "array.firstOr should return default on empty"); // Extension on any: adds a method to all objects extension any { func debug() { return type(this) + ":" + toString(this); } } // assert(42.debug() == "number:42", "any.debug should work on numbers"); // assert("x".debug() == "string:x", "any.debug should work on strings"); print("Class + Extension spec tests defined (pending parser/runtime support).");