Skip to content

Commit

Permalink
refactor(codegen): 💄 Add parentheses to toString generation
Browse files Browse the repository at this point in the history
All printing ambiguity for ADTs is gone, at the cost of some redundant parens here and there
  • Loading branch information
bristermitten committed Jun 2, 2024
1 parent 9452cc7 commit 6e35e1b
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/Elara/Emit/ADT.hs
Original file line number Diff line number Diff line change
Expand Up @@ -143,20 +143,25 @@ generateADTClasses (CoreTypeDecl name kind tvs (CoreDataDecl ctors)) = do
createMethodWithCodeBuilder thisName (NamedMethodDescriptor [] (TypeReturn $ ObjectFieldType "java/lang/String")) [MPublic] "toString" $ do
emit $ New (ClassInfoType "java/lang/StringBuilder")
emit Dup
emit $ LDC (LDCString $ ctorName ^. unqualified)
emit $ LDC (LDCString $ ctorName ^. unqualified <> " (")
emit $ InvokeSpecial (ClassInfoType "java/lang/StringBuilder") "<init>" (MethodDescriptor [ObjectFieldType "java/lang/String"] VoidReturn)

for_ (zip fields [0 ..]) $ \(field, i) -> do
-- add whitespace
emit $ LDC (LDCString " ")
emit $ InvokeVirtual (ClassInfoType "java/lang/StringBuilder") "append" (MethodDescriptor [ObjectFieldType "java/lang/String"] (TypeReturn $ ObjectFieldType "java/lang/StringBuilder"))
when (i /= 0) $ do
emit $ LDC (LDCString " ")
emit $ InvokeVirtual (ClassInfoType "java/lang/StringBuilder") "append" (MethodDescriptor [ObjectFieldType "java/lang/String"] (TypeReturn $ ObjectFieldType "java/lang/StringBuilder"))
-- get the field
emit $ ALoad 0
emit $ GetField (ClassInfoType thisName) ("field" <> show i) (generateFieldType field)
-- toString it
emit $ InvokeVirtual (ClassInfoType "java/lang/Object") "toString" (MethodDescriptor [] (TypeReturn $ ObjectFieldType "java/lang/String"))
-- append it to the StringBuilder
emit $ InvokeVirtual (ClassInfoType "java/lang/StringBuilder") "append" (MethodDescriptor [ObjectFieldType "java/lang/String"] (TypeReturn $ ObjectFieldType "java/lang/StringBuilder"))

-- add closing bracket
emit $ LDC (LDCString ")")
emit $ InvokeVirtual (ClassInfoType "java/lang/StringBuilder") "append" (MethodDescriptor [ObjectFieldType "java/lang/String"] (TypeReturn $ ObjectFieldType "java/lang/StringBuilder"))
emit $ InvokeVirtual (ClassInfoType "java/lang/StringBuilder") "toString" (MethodDescriptor [] (TypeReturn $ ObjectFieldType "java/lang/String"))

-- generate the match impl
Expand Down

0 comments on commit 6e35e1b

Please sign in to comment.