Skip to content

Commit

Permalink
More compact computed properties
Browse files Browse the repository at this point in the history
Single-line set/get properties.
  • Loading branch information
helje5 committed Nov 10, 2024
1 parent 5c3a333 commit a782b99
Showing 1 changed file with 41 additions and 24 deletions.
65 changes: 41 additions & 24 deletions Plugins/Libraries/LighterCodeGenAST/Generation/GenFunctions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -272,38 +272,55 @@ public extension CodeGenerator {
append(string(for: value.type))

let allowSingleReturn = true // make an option?
if allowSingleReturn && value.statements.count == 1,
value.setStatements.isEmpty,
let statement = value.statements.first,
case .return(let expression) = statement
{
append(" { ")
appendExpression(expression)
append(" }")
appendEOL()
}
else {
if value.setStatements.isEmpty {
indentedCodeBlock {
generateStatements(value.statements, allowSingleReturn: true)

func genStatements(_ statements: [ Statement ]) {
if allowSingleReturn && statements.count == 1,
let statement = statements.first,
case .return(let expression) = statement
{
append(" { ")
appendExpression(expression)
append(" }")
appendEOL()
}
else if statements.count == 1,
let statement = statements.first,
case .variableAssignment(let instance, let name, let value)
= statement
{
append(" { ")
if let instance = instance {
append(instance) // "self" can be used here
append(".")
}
append(tickedWhenReserved(name))
append(configuration.propertyValueSeparator) // " = "
appendExpression(value)
append(" }")
appendEOL()
}
else {
indentedCodeBlock {
appendIndent()
append("set")
indentedCodeBlock {
generateStatements(value.setStatements, allowSingleReturn: true)
}
appendIndent()
append("get")
indentedCodeBlock {
generateStatements(value.statements, allowSingleReturn: true)
}
generateStatements(statements, allowSingleReturn: allowSingleReturn)
}
}
}

if value.setStatements.isEmpty {
genStatements(value.statements)
}
else {
indentedCodeBlock {
appendIndent()
append("set")
genStatements(value.setStatements)

appendIndent()
append("get")
genStatements(value.statements)
}
}

if let ( major, minor ) = value.minimumSwiftVersion {
assert(major >= 5)
writeln("#endif // swift(>=\(major).\(minor))")
Expand Down

0 comments on commit a782b99

Please sign in to comment.