Skip to content

Commit

Permalink
String -> Str (#435)
Browse files Browse the repository at this point in the history
* Streamline format
  • Loading branch information
JSAbrahams committed Jan 21, 2023
1 parent ef7ee64 commit 57cb174
Show file tree
Hide file tree
Showing 37 changed files with 82 additions and 92 deletions.
24 changes: 12 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,22 +84,22 @@ We can do the same for any field. We showcase this using a simple dummy `Server`
```mamba
from ipaddress import IPv4Address
class ServerError(def message: String): Exception(message)
class ServerError(def message: Str): Exception(message)
def fin always_the_same_message := "Connected!"
class MyServer(def ip_address: IPv4Address)
def is_connected: Bool := False
def _last_message: String := "temp"
def is_connected: Bool := False
def _last_message: Str := "temp"
def last_sent(fin self) -> String raise [ServerError] =>
def last_sent(fin self) -> Str raise [ServerError] =>
self._last_message
def connect(self) =>
self.is_connected := True
print(always_the_same_message)
def send(self, message: String) raise [ServerError] =>
def send(self, message: Str) raise [ServerError] =>
if self.is_connected then
self._last_message := message
else
Expand Down Expand Up @@ -139,26 +139,26 @@ from ipaddress import IPv4Address
type ConnMyServer: MyServer when self.is_connected
type DisConnMyServer: MyServer when not self.is_connected
class ServerErr(def message: String): Exception(message)
class ServerErr(def message: Str): Exception(message)
class MyServer(self: DisConnMyServer, def ip_address: IPv4Address)
def is_connected: Bool := False
def _last_message: String? := None
def is_connected: Bool := False
def _last_message: Str? := None
def last_sent(self) -> String raise [ServerErr] =>
def last_sent(self) -> Str raise [ServerErr] =>
if self.last_message != None then
self._last_message
else
raise ServerError("No last message!")
def connect(self: DisConnMyServer) => self.is_connected := True
def send(self: ConnMyServer, message: String) => self._last_message := message
def send(self: ConnMyServer, message: Str) => self._last_message := message
def disconnect(self: ConnMyServer) => self.is_connected := False
```

Within the then branch of the if statement, we know that `self._last_message` is a `String`.
Within the then branch of the if statement, we know that `self._last_message` is a `Str`.
This is because we performed a check in the if condition.

Also Notice how above, we define the type of `self`.
Expand Down Expand Up @@ -196,7 +196,7 @@ def factorial(x: PosInt) -> PosInt => match x
```

In short, types allow us to specify the domain and co-domain of functions with regards to the type of input, say, `Int`
or `String`. During execution, a check is done to verify that the variable does conform to the requirements of the
or `Str`. During execution, a check is done to verify that the variable does conform to the requirements of the
refined type. If it does not, an exception is raised.

Type refinement allows us to do some additional things:
Expand Down
11 changes: 4 additions & 7 deletions src/check/context/clss/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ impl TryFrom<&AST> for GenericClass {
})
.flat_map(|(pos, parent)| {
if temp_parents.contains(&parent) {
Some((pos, format!("Duplicate parent: {}", parent)))
Some((pos, format!("Duplicate parent: {parent}")))
} else {
temp_parents.insert(parent);
None
Expand All @@ -178,10 +178,8 @@ impl TryFrom<&AST> for GenericClass {
if class_args.is_empty() {
class_args.append(&mut function.arguments.clone())
} else {
return Err(vec![TypeErr::new(
class.pos,
"Cannot have constructor and class arguments",
)]);
let msg = "Cannot have constructor and class arguments";
return Err(vec![TypeErr::new(class.pos, &msg)]);
}
}

Expand Down Expand Up @@ -298,8 +296,7 @@ fn get_fields_and_functions(

for generic_field in &stmt_fields {
if generic_field.ty.is_none() {
let msg =
format!("Class field '{}' was not assigned a type", generic_field.name);
let msg = format!("Class field '{}' was not assigned a type", generic_field.name);
return Err(vec![TypeErr::new(generic_field.pos, &msg)]);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/check/context/clss/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::common::position::Position;

pub const INT: &str = "Int";
pub const FLOAT: &str = "Float";
pub const STRING: &str = "String";
pub const STRING: &str = "Str";
pub const BOOL: &str = "Bool";
pub const ENUM: &str = "Enum";
pub const COMPLEX: &str = "Complex";
Expand Down
6 changes: 3 additions & 3 deletions src/check/context/clss/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl GetField<FieldUnion> for ClassUnion {
self.union.iter().map(|c| c.field(name, ctx, pos)).collect::<Result<_, _>>()?;

if union.is_empty() {
let msg = format!("'{}' does not define attribute '{}'", Name::from(self), name);
let msg = format!("'{}' does not define attribute '{name}'", Name::from(self));
return Err(vec![TypeErr::new(pos, &msg)]);
}

Expand All @@ -69,7 +69,7 @@ impl GetFun<FunUnion> for ClassUnion {
self.union.iter().map(|c| c.fun(name, ctx, pos)).collect::<Result<_, _>>()?;

if union.is_empty() {
let msg = format!("'{}' does not define function '{}'", Name::from(self), name);
let msg = format!("'{}' does not define function '{name}'", Name::from(self));
return Err(vec![TypeErr::new(pos, &msg)]);
}
Ok(FunUnion::from(&union))
Expand Down Expand Up @@ -137,7 +137,7 @@ impl LookupClass<&Name, ClassUnion> for Context {
/// If NameUnion is empty.
fn class(&self, name: &Name, pos: Position) -> TypeResult<ClassUnion> {
if name.is_empty() {
return Err(vec![TypeErr::new(pos, &format!("Unexpected '{}'", name))]);
return Err(vec![TypeErr::new(pos, &format!("Unexpected '{name}'"))]);
}

let union = name.names.iter().map(|n| self.class(n, pos)).collect::<Result<_, _>>()?;
Expand Down
4 changes: 2 additions & 2 deletions src/check/context/field/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub struct Field {
impl Display for Field {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let ty = if self.ty.is_empty() { String::new() } else { format!(": {}", self.ty) };
write!(f, "{}{}", &self.name, ty)
write!(f, "{}{ty}", &self.name)
}
}

Expand All @@ -42,7 +42,7 @@ impl LookupField<&str, Field> for Context {
let generics = HashMap::new();
Field::try_from((generic_field, &generics, pos))
} else {
let msg = format!("Field {} is undefined.", field);
let msg = format!("Field {field} is undefined.");
Err(vec![TypeErr::new(pos, &msg)])
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/check/context/field/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl TryFromPos<&FieldUnion> for Field {
if field_union.union.len() == (1_usize) {
Ok(field_union.union.iter().next().unwrap().clone())
} else {
let msg = format!("Expected single field but was {}", field_union);
let msg = format!("Expected single field but was {field_union}");
Err(vec![TypeErr::new(pos, &msg)])
}
}
Expand Down
7 changes: 2 additions & 5 deletions src/check/context/function/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,8 @@ impl TryFrom<&AST> for GenericFunction {
let mut has_default = false;
for arg in args.clone() {
if has_default && !arg.has_default {
return Err(vec![TypeErr::new(
arg.pos,
"Cannot have argument with default followed by argument with \
no default.",
)]);
let msg = "Cannot have argument with default followed by argument with no default.";
return Err(vec![TypeErr::new(arg.pos, &msg)]);
}
has_default = arg.has_default;
}
Expand Down
6 changes: 3 additions & 3 deletions src/check/context/function/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ mod test {

#[test]
fn from_py() {
let source = "def f(a: int, b, c: str, d: str = 'default') -> complex: pass";
let source = "def f(a: int, b, c: Str, d: Str = 'default') -> complex: pass";
let (_, statements) =
python_parser::file_input(python_parser::make_strspan(&source)).expect("parse source");

Expand All @@ -121,12 +121,12 @@ mod test {
assert!(generic_function.arguments[1].mutable);

assert_eq!(generic_function.arguments[2].name, String::from("c"));
assert_eq!(generic_function.arguments[2].ty, Some(Name::from("String")));
assert_eq!(generic_function.arguments[2].ty, Some(Name::from("Str")));
assert!(!generic_function.arguments[2].has_default);
assert!(generic_function.arguments[2].mutable);

assert_eq!(generic_function.arguments[3].name, String::from("d"));
assert_eq!(generic_function.arguments[3].ty, Some(Name::from("String")));
assert_eq!(generic_function.arguments[3].ty, Some(Name::from("Str")));
assert!(generic_function.arguments[3].has_default);
assert!(generic_function.arguments[3].mutable);
}
Expand Down
2 changes: 1 addition & 1 deletion src/check/context/function/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl TryFromPos<&FunUnion> for Function {
if fun_union.union.len() == (1_usize) {
Ok(fun_union.union.iter().next().unwrap().clone())
} else {
let msg = format!("Expected single function but was {}", fun_union);
let msg = format!("Expected single function but was {fun_union}");
Err(vec![TypeErr::new(pos, &msg)])
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/check/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ mod tests {
let context = Context::try_from(files.as_slice()).unwrap();
let context = context.into_with_primitives().unwrap();

context.class(&StringName::from("String"), Position::default()).unwrap();
context.class(&StringName::from("Str"), Position::default()).unwrap();
context.class(&StringName::from("Bool"), Position::default()).unwrap();
context.class(&StringName::from("Float"), Position::default()).unwrap();
context.class(&StringName::from("Int"), Position::default()).unwrap();
Expand All @@ -159,7 +159,7 @@ mod tests {
assert_eq!(args.len(), 2);
assert_eq!(args[0].ty.clone().unwrap(), Name::from("Int"));
assert_eq!(args[1].ty.clone().unwrap(), Name::from("Int")
.union(&Name::from("String"))
.union(&Name::from("Str"))
.union(&Name::from("Float")));
}

Expand All @@ -173,7 +173,7 @@ mod tests {

assert_eq!(int_fun.arguments.len(), 1);
assert_eq!(int_fun.arguments[0].ty.clone().unwrap(), Name::from("Int")
.union(&Name::from("String"))
.union(&Name::from("Str"))
.union(&Name::from("Float")));

assert_eq!(int_fun.ret_ty, Name::from("Int"))
Expand Down
6 changes: 1 addition & 5 deletions src/check/context/parameter/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,7 @@ impl Display for GenericParameter {
f,
"{}{}",
self.name,
if let Some(parent) = &self.parent {
format!(" isa {}", parent)
} else {
String::new()
}
if let Some(parent) = &self.parent { format!(" isa {parent}") } else { String::new() }
)
}
}
4 changes: 2 additions & 2 deletions tests/resource/valid/class/assign_to_nullable_field.mamba
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class MyServer()
def _message: String? := None
def _message: Str? := None

def send(self, x: String) =>
def send(self, x: Str) =>
self._message := x
4 changes: 2 additions & 2 deletions tests/resource/valid/class/class_super_one_line_init.mamba
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class MyType(def super_field: String)
class MyType(def super_field: Str)

class MyClass2: MyType("the quick brown fox jumped over the slow donkey")
def fin z_modified: String := "asdf"
def fin z_modified: Str := "asdf"
def other_field: Int := 10

def init(self, other_field: Int, z: Int) => self.other_field := z + other_field
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type MyType
def abstract_fun(my_arg: Int) -> String
def abstract_fun(my_arg: Int) -> Str

def concrete_fun(x: Int) -> Int => return x + 10
8 changes: 4 additions & 4 deletions tests/resource/valid/class/generics.mamba
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
class Err1(msg: String): Exception(msg)
class Err2(msg: String): Exception(msg)
class Err1(msg: Str): Exception(msg)
class Err2(msg: Str): Exception(msg)

class MyType[A: MyGeneric, C](def super_field: String)
class MyType[A: MyGeneric, C](def super_field: Str)

class MyClass2[C, A: MyGeneric]: MyType[A, C]("the quick brown fox jumped over the slow donkey")
def fin z_modified: String := "asdf"
def fin z_modified: Str := "asdf"
def other_field: Int := 10

def init(self, other_field: Int, z: Int) raise [Err1] =>
Expand Down
4 changes: 2 additions & 2 deletions tests/resource/valid/class/multiple_parent.mamba
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class MyType(a: String)
class MyType2(b: String)
class MyType(a: Str)
class MyType2(b: Str)

class MyClass1: MyType("asdf"), MyType2("qwerty")
def other: Int
2 changes: 1 addition & 1 deletion tests/resource/valid/class/tuple_as_class.mamba
Original file line number Diff line number Diff line change
@@ -1 +1 @@
class MyTuple: (Int, Int, String)
class MyTuple: (Int, Int, Str)
6 changes: 3 additions & 3 deletions tests/resource/valid/class/types.mamba
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class MyGeneric: String
class MyType(def some_field: String)
class MyGeneric: Str
class MyType(def some_field: Str)

type SomeState: MyClass when self.private_field > 2
type OtherState: MyClass when
Expand All @@ -15,7 +15,7 @@ type MyInterface: SuperInterface
def higher_order(self) -> int

# some class
class MyClass(def my_field: Int, other_field: String := "Hello"): MyType(other_field), MyInterface
class MyClass(def my_field: Int, other_field: Str := "Hello"): MyType(other_field), MyInterface
def required_field: Int := 100
def private_field: Int := 20

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
def x: {Range, String} := "MyString"
def x: {Range, Str} := "MyString"

for i in x do
print(i)
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
def send(message: String) =>
def _message: String? := None
def send(message: Str) =>
def _message: Str? := None
_message := message
2 changes: 1 addition & 1 deletion tests/resource/valid/definition/assign_tuples.mamba
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
def a := (2, 3)
def b: (Int, Int) := (3, 5)

def c: (Int, Int, String) := (3, 4, "Hello")
def c: (Int, Int, Str) := (3, 4, "Hello")
2 changes: 1 addition & 1 deletion tests/resource/valid/error/exception_in_fun_super.mamba
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class MyException(msg: String): Exception(msg)
class MyException(msg: Str): Exception(msg)

def g() -> Int raise [MyException] =>
raise MyException("A")
Expand Down
2 changes: 1 addition & 1 deletion tests/resource/valid/error/handle.mamba
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class MyErr1: Exception("Something went wrong")
class MyErr2(msg: String): Exception(msg)
class MyErr2(msg: Str): Exception(msg)

def f(x: Int) -> Int raise [MyErr1, MyErr2] =>
if x < 0 then
Expand Down
2 changes: 1 addition & 1 deletion tests/resource/valid/error/handle_only_id.mamba
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class MyErr1: Exception("Something went wrong")
class MyErr2(msg: String): Exception(msg)
class MyErr2(msg: Str): Exception(msg)

def f(x: Int) -> Int raise [MyErr1, MyErr2] => x

Expand Down
2 changes: 1 addition & 1 deletion tests/resource/valid/error/handle_var_usable_after.mamba
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class MyErr(def message: String): Exception
class MyErr(def message: Str): Exception

def function_may_throw_err() -> Int raise [MyErr] => 10

Expand Down
4 changes: 2 additions & 2 deletions tests/resource/valid/error/nested_exception.mamba
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class MyException1(msg: String): Exception(msg)
class MyException2(msg: String): Exception(msg)
class MyException1(msg: Str): Exception(msg)
class MyException2(msg: Str): Exception(msg)

def f(x: Int) -> Int raise [MyException1, MyException2] =>
match x
Expand Down
2 changes: 1 addition & 1 deletion tests/resource/valid/error/raise.mamba
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class Err(def msg: String): Exception(msg)
class Err(def msg: Str): Exception(msg)

def f(x: Int) -> Int raise[Err] => if x > 0 then return 10 else raise Err("Expected positive number.")

Expand Down
8 changes: 4 additions & 4 deletions tests/resource/valid/function/definition.mamba
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ def fun_b(b: Int) => print(b)

def fun_c_1(b: (Int, Int)) => print(b)

def fun_c_2(b: (Int) -> String) => print(b)
def fun_c_2(b: (Int) -> Str) => print(b)

def fun_d(h: (String, String) -> Int) -> Int? => return h("hello", "world")
def fun_d(h: (Str, Str) -> Int) -> Int? => return h("hello", "world")

def fun_e(m: Int, o: (String, String), r: (Int, (String, String)) -> Int) -> Int => return r(m, o)
def fun_e(m: Int, o: (Str, Str), r: (Int, (Str, Str)) -> Int) -> Int => return r(m, o)

def fun_v(y: String, ab: String -> String -> Bool) -> String -> Bool => return ab(y)
def fun_v(y: Str, ab: Str -> Str -> Bool) -> Str -> Bool => return ab(y)

class MyClass(def a: Int, def b: Int)
def some_function(self, c: Int) -> Int =>
Expand Down
Loading

0 comments on commit 57cb174

Please sign in to comment.