File: NinjaParser.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (381 lines) | stat: -rw-r--r-- 9,961 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
148
149
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//===--- NinjaParser.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import Foundation

struct NinjaParser {
  private let filePath: AbsolutePath
  private let fileReader: (AbsolutePath) throws -> Data
  private var lexer: Lexer

  private init(input: UnsafeRawBufferPointer, filePath: AbsolutePath, fileReader: @escaping (AbsolutePath) throws -> Data) throws {
    self.filePath = filePath
    self.fileReader = fileReader
    self.lexer = Lexer(ByteScanner(input))
  }

  static func parse(filePath: AbsolutePath, fileReader: @escaping (AbsolutePath) throws -> Data = { try $0.read() }) throws -> NinjaBuildFile {

    try fileReader(filePath).withUnsafeBytes { bytes in
      var parser = try Self(input: bytes, filePath: filePath, fileReader: fileReader)
      return try parser.parse()
    }
  }
}

fileprivate enum NinjaParseError: Error {
  case expected(NinjaParser.Lexeme)
}

fileprivate extension ByteScanner {
  mutating func consumeUnescaped(
    while pred: (Byte) -> Bool
  ) -> String? {
    let bytes = consume(using: { consumer in
      guard let c = consumer.peek, pred(c) else { return false }

      // Ninja uses '$' as the escape character.
      if c == "$" {
        switch consumer.peek(ahead: 1) {
        case "$", ":", \.isSpaceOrTab:
          // Skip the '$' and take the unescaped character.
          consumer.skip()
          return consumer.eat()
        case \.isNewline:
          // This is a line continuation, skip the newline, and strip any
          // following space.
          consumer.skip(untilAfter: \.isNewline)
          consumer.skip(while: \.isSpaceOrTab)
          return true
        default:
          // Unknown escape sequence, treat the '$' literally.
          break
        }
      }
      return consumer.eat()
    })
    return bytes.isEmpty ? nil : String(utf8: bytes)
  }
}

fileprivate extension NinjaParser {
  typealias Rule = NinjaBuildFile.Rule
  typealias BuildEdge = NinjaBuildFile.BuildEdge

  struct ParsedBinding: Hashable {
    var key: String
    var value: String
  }

  enum Lexeme: Hashable {
    case binding(ParsedBinding)
    case element(String)
    case rule
    case build
    case include
    case newline
    case colon
    case equal
    case pipe
    case doublePipe
  }

  struct Lexer {
    private var input: ByteScanner
    private(set) var lexeme: Lexeme?
    private(set) var isAtStartOfLine = true
    private(set) var leadingTriviaCount = 0

    init(_ input: ByteScanner) {
      self.input = input
      self.lexeme = lex()
    }
  }

  var peek: Lexeme? { lexer.lexeme }

  @discardableResult
  mutating func tryEat(_ lexeme: Lexeme) -> Bool {
    guard peek == lexeme else { return false }
    eat()
    return true
  }

  mutating func tryEatElement() -> String? {
    guard case .element(let str) = peek else { return nil }
    eat()
    return str
  }

  @discardableResult
  mutating func eat() -> Lexeme? {
    defer {
      lexer.eat()
    }
    return peek
  }
}

fileprivate extension Byte {
  var isNinjaOperator: Bool {
    switch self {
    case ":", "|", "=":
      true
    default:
      false
    }
  }
}

extension NinjaParser.Lexer {
  typealias Lexeme = NinjaParser.Lexeme

  private mutating func consumeOperator() -> Lexeme {
    switch input.eat() {
    case ":":
      return .colon
    case "=":
      return .equal
    case "|":
      if input.tryEat("|") {
        return .doublePipe
      }
      return .pipe
    default:
      fatalError("Invalid operator character")
    }
  }

  private mutating func consumeElement() -> String? {
    input.consumeUnescaped(while: { char in
      switch char {
      case \.isNinjaOperator, \.isSpaceTabOrNewline:
        false
      default:
        true
      }
    })
  }

  private mutating func tryConsumeBinding(key: String) -> Lexeme? {
    input.tryEating { input in
      input.skip(while: \.isSpaceOrTab)
      guard input.tryEat("=") else { return nil }
      input.skip(while: \.isSpaceOrTab)
      guard let value = input.consumeUnescaped(while: { !$0.isNewline }) else {
        return nil
      }
      return .binding(.init(key: key, value: value))
    }
  }

  private mutating func lex() -> Lexeme? {
    while true {
      isAtStartOfLine = input.previous?.isNewline ?? true
      leadingTriviaCount = input.eat(while: \.isSpaceOrTab)?.count ?? 0

      guard let c = input.peek else { return nil }
      if c == "#" {
        input.skip(untilAfter: \.isNewline)
        continue
      }
      if c.isNewline {
        input.skip(untilAfter: \.isNewline)
        if isAtStartOfLine {
          // Ignore empty lines, newlines are only semantically meaningful
          // when they delimit non-empty lines.
          continue
        }
        return .newline
      }
      if c.isNinjaOperator {
        return consumeOperator()
      }
      if isAtStartOfLine {
        // decl keywords.
        if input.tryEat(utf8: "build") {
          return .build
        }
        if input.tryEat(utf8: "rule") {
          return .rule
        }
        if input.tryEat(utf8: "include") {
          return .include
        }
      }
      guard let element = consumeElement() else { return nil }

      // If we're on a newline, check to see if we can lex a binding.
      if isAtStartOfLine {
        if let binding = tryConsumeBinding(key: element) {
          return binding
        }
      }
      return .element(element)
    }
  }

  @discardableResult
  mutating func eat() -> Lexeme? {
    defer {
      lexeme = lex()
    }
    return lexeme
  }
}

fileprivate extension NinjaParser {
  mutating func skipLine() {
    while let lexeme = eat(), lexeme != .newline {}
  }

  mutating func parseBinding() throws -> ParsedBinding? {
    guard case let .binding(binding) = peek else { return nil }
    eat()
    tryEat(.newline)
    return binding
  }

  /// ```
  /// rule rulename
  ///   command = ...
  ///   var = ...
  /// ```
  mutating func parseRule() throws -> Rule? {
    let indent = lexer.leadingTriviaCount
    guard tryEat(.rule) else { return nil }

    guard let ruleName = tryEatElement() else {
      throw NinjaParseError.expected(.element("<rule name>"))
    }
    guard tryEat(.newline) else {
      throw NinjaParseError.expected(.newline)
    }

    var bindings: [String: String] = [:]
    while indent < lexer.leadingTriviaCount, let binding = try parseBinding() {
      bindings[binding.key] = binding.value
    }

    return Rule(name: ruleName, bindings: bindings)
  }

  /// ```
  /// build out1... | implicit-out... : rulename input... | dep... || order-only-dep...
  ///   var = ...
  /// ```
  mutating func parseBuildEdge() throws -> BuildEdge? {
    let indent = lexer.leadingTriviaCount
    guard tryEat(.build) else { return nil }

    var outputs: [String] = []
    while let str = tryEatElement() {
      outputs.append(str)
    }

    // Ignore implicit outputs for now.
    if tryEat(.pipe) {
      while tryEatElement() != nil {}
    }

    guard tryEat(.colon) else {
      throw NinjaParseError.expected(.colon)
    }

    guard let ruleName = tryEatElement() else {
      throw NinjaParseError.expected(.element("<rule name>"))
    }

    var inputs: [String] = []
    while let str = tryEatElement() {
      inputs.append(str)
    }

    if ruleName == "phony" {
      skipLine()
      return .phony(for: outputs, inputs: inputs)
    }

    var dependencies: [String] = []
    while true {
      if let str = tryEatElement() {
        dependencies.append(str)
        continue
      }
      if tryEat(.pipe) || tryEat(.doublePipe) {
        // Currently we don't distinguish between implicit deps and order-only deps.
        continue
      }
      break
    }

    // We're done with the line, skip to the next.
    skipLine()

    var bindings: [String: String] = [:]
    while indent < lexer.leadingTriviaCount, let binding = try parseBinding() {
      bindings[binding.key] = binding.value
    }

    return BuildEdge(
      ruleName: ruleName,
      inputs: inputs,
      outputs: outputs,
      dependencies: dependencies,
      bindings: bindings
    )
  }

  /// ```
  /// include path/to/sub.ninja
  /// ```
  mutating func parseInclude() throws -> NinjaBuildFile? {
    guard tryEat(.include) else { return nil }

    guard let fileName = tryEatElement() else {
      throw NinjaParseError.expected(.element("<path>"))
    }

    let baseDirectory = self.filePath.parentDir!
    let path = AnyPath(fileName).absolute(in: baseDirectory)
    return try NinjaParser.parse(filePath: path, fileReader: fileReader)
  }

  mutating func parse() throws -> NinjaBuildFile {
    var bindings: [String: String] = [:]
    var rules: [String: Rule] = [:]
    var buildEdges: [BuildEdge] = []
    while peek != nil {
      if let rule = try parseRule() {
        rules[rule.name] = rule
        continue
      }
      if let edge = try parseBuildEdge() {
        buildEdges.append(edge)
        continue
      }
      if let binding = try parseBinding() {
        bindings[binding.key] = binding.value
        continue
      }
      if let included = try parseInclude() {
        bindings.merge(included.bindings.values, uniquingKeysWith: { _, other in other })
        rules.merge(included.rules, uniquingKeysWith: { _, other in other })
        buildEdges.append(contentsOf: included.buildEdges)
        continue
      }
      // Ignore unknown bits of syntax like 'subninja' for now.
      eat()
    }
    return NinjaBuildFile(bindings: bindings, rules: rules, buildEdges: buildEdges)
  }
}