Swift AST written in Swift. Part 6 of ∞

Alexey Demedeckiy
2 min readMar 23, 2017

--

In previous part I have covered enum declaration, and found that there is two different enums in swift.

In this one I will cover two entities at one time: struc and class. They are pretty similar to each other. But serving different roles at runtime.

Struct

Let’s start, as usuall, from look on grammar:

A lot of this fields already covered in previous parts, so we should just build it from Lego bricks. We will flatten this type, and replace struct-body with array of struct-member

struct StructDeclaration {
let attributes: [Attribute]
let accessLevel: AccessLevelModifier?
let name: Identifier
let genericParameters: GenericParameterClause?
let typeInheritance: TypeInheritanceClause?
let genericConstraints: GenericWhereClause?
let members: [StructMember]
}
enum StructMember {
case declaration(Declaration)
case compilerStatement(CompilerControlStatement)
}

As member of struct we can have either some declaration, or some compiler directive.

Class

Class grammar is pretty similar:

Only major difference from struct option to add final directive. It can be after or before access level modifier. Because of this there is two class declaration. We will skip this difference and always assume that final may go only after access level modifier.

struct ClassDeclaration {
let attributes: [Attribute]
let accessLevel: AccessLevelModifier?
let final: Final?
let name: Identifier
let genericParameters: GenericParameterClause?
let typeInheritance: TypeInheritanceClause?
let genericConstraints: GenericWhereClause?
let members: [ClassMember]
}
enum Final { case final }enum ClassMember {
case declaration(Declaration)
case compilerStatement(CompilerControlStatement)
}

As we can see, class and structure are pretty similar in terms of grammar. However, there is one thing that look strange to me. open presented as another access level modifier and not like opposite to final so, accordingly to grammar, I can write open struct ... and open final class. It is fine)

In next part I will describe protocol declaration structure.

--

--