Parser.swift 5.46 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2016 Anarchy Tools Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
import Foundation
16

David Owens II's avatar
David Owens II committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
public enum ParseError: ErrorType {
    case InvalidPackageFile
    case ExpectedTokenType(TokenType, Token?)
    case InvalidTokenForValueType(Token?)
}

public enum ParseValue {
    case StringLiteral(String)
    case IntegerLiteral(Int)
    case FloatLiteral(Double)
    case BoolLiteral(Bool)
    
    case Map([String:ParseValue])
    case Vector([ParseValue])
}

33
extension ParseValue {
34
    public var string: String? {
35 36 37 38
        if case let .StringLiteral(value) = self { return value }
        return nil
    }
    
39
    public var integer: Int? {
40 41 42 43
        if case let .IntegerLiteral(value) = self { return value }
        return nil
    }

44
    public var float: Double? {
45 46 47 48
        if case let .FloatLiteral(value) = self { return value }
        return nil
    }

49
    public var bool: Bool? {
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
        if case let .BoolLiteral(value) = self { return value }
        return nil
    }
    
    public var map: [String:ParseValue]? {
        if case let .Map(value) = self { return value }
        return nil
    }
    
    public var vector: [ParseValue]? {
        if case let .Vector(value) = self { return value }
        return nil
    }
}


66
final public class ParseType {
David Owens II's avatar
David Owens II committed
67 68 69 70
    public var name: String = ""
    public var properties: [String:ParseValue] = [:]
}

71
final public class Parser {
David Owens II's avatar
David Owens II committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    let lexer: Lexer
    
    private func next() -> Token? {
        while true {
            guard let token = lexer.next() else { return nil }
            if token.type != .Comment && token.type != .Terminal {
                return lexer.peek()
            }
        }
    }
    
    public init?(filepath: String) {
        guard let content = try? NSString(contentsOfFile: filepath, encoding: NSUTF8StringEncoding) else {
            return nil
        }
        
        let scanner = Scanner(content: content as String)
        self.lexer = Lexer(scanner: scanner)
    }
    
    public func parse() throws -> ParseType {
        guard let token = next() else { throw ParseError.InvalidPackageFile }
        
        if token.type == .OpenParen {
            return try parseType()
        }
        else {
            throw ParseError.ExpectedTokenType(.OpenParen, token)
        }
    }
    
    private func parseType() throws -> ParseType {
        let type = ParseType()
        type.name = try parseIdentifier()
        
        type.properties = try parseKeyValuePairs()
        return type
    }
    
    private func parseKeyValuePairs() throws -> [String:ParseValue] {
        var pairs: [String:ParseValue] = [:]

        while let token = next() where token.type != .CloseParen && token.type != .CloseBrace {
            lexer.stall()
            
            let key = try parseKey()
            let value = try parseValue()
            
            pairs[key] = value
        }
        lexer.stall()

        return pairs
    }
    
    private func parseKey() throws -> String {
        let colon = next()
        if colon?.type != .Colon { throw ParseError.ExpectedTokenType(.Colon, lexer.peek()) }
        
        return try parseIdentifier()
    }
    
    private func parseIdentifier() throws -> String {
        guard let identifier = next() else { throw ParseError.ExpectedTokenType(.Identifier, lexer.peek()) }
        if identifier.type != .Identifier { throw ParseError.ExpectedTokenType(.Identifier, lexer.peek()) }
        
        return identifier.value
    }
    
    private func parseValue() throws -> ParseValue {
        guard let token = next() else { throw ParseError.InvalidTokenForValueType(nil) }
        
        switch token.type {
        case .OpenBrace: lexer.stall(); return try parseMap()
        case .OpenBracket: lexer.stall(); return try parseVector()
        case .StringLiteral: return .StringLiteral(token.value)
148 149
        case .Identifier where token.value == "true": return .BoolLiteral(true)
        case .Identifier where token.value == "false": return .BoolLiteral(false)
David Owens II's avatar
David Owens II committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        default: throw ParseError.InvalidTokenForValueType(token)
        }
    }
    
    private func parseVector() throws -> ParseValue {
        if let token = next() where token.type != .OpenBracket { throw ParseError.ExpectedTokenType(.OpenBracket, token) }
        var items: [ParseValue] = []
        
        while let token = next() where token.type != .CloseBracket {
            lexer.stall()
            items.append(try parseValue())
        }
        lexer.stall()

        if let token = next() where token.type != .CloseBracket { throw ParseError.ExpectedTokenType(.CloseBracket, token) }

        return .Vector(items)
    }
    
    private func parseMap() throws -> ParseValue {
        if let token = next() where token.type != .OpenBrace { throw ParseError.ExpectedTokenType(.OpenBrace, token) }
        let items = try parseKeyValuePairs()
        if let token = next() where token.type != .CloseBrace { throw ParseError.ExpectedTokenType(.CloseBrace, token) }
        
        return .Map(items)
    }
}