File: TestLocationScanner.swift

package info (click to toggle)
swiftlang 6.1.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,604 kB
  • sloc: cpp: 9,901,740; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (173 lines) | stat: -rw-r--r-- 5,171 bytes parent folder | download | duplicates (2)
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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

/// A builder object for scanning source files for TestLocations specified in /*inline comments*/.
///
/// The scanner searches source files for inline comments /*foo*/ and builds up a mapping from name
/// (the contents of the inline comment) to the location in the source file that it was found.
///
/// For example:
///
/// ```
/// var scanner = TestLocationScanner()
/// scanner.scan("""
///   func /*foo:def*/foo() {}
///   """, url: myURL)
/// scanner.result == ["foo:def": TestLocation(url: myURL, line: 1, column: 17)]
/// ```
///
/// ## Special Syntax
///
/// If the location starts with `<', it will be the location of the start of the
/// comment instead of the end. E.g.
///
/// ```
/// /*a*/   // column 6
/// /*<b*/  // column 1
/// ```
public struct TestLocationScanner {

  /// The result of the scan (so far), mapping name to test location.
  public var result: [String: TestLocation] = [:]

  public init() {}

  public enum Error: Swift.Error {
    case noSuchFileOrDirectory(URL)

    /// The sources contained a `/*/*nested*/*/` inline comment, which is not supported.
    case nestedComment(TestLocation)

    /// The same test location name was used in multiple places.
    case duplicateKey(String, TestLocation, TestLocation)
  }

  public mutating func scan(_ str: String, url: URL) throws {
    if str.count < 4 {
      return
    }

    enum State {
      /// Outside any comment.
      case normal(prev: Character)

      /// Inside a comment. The payload contains the previous character and the index of the first
      /// character after the '*' (i.e. the start of the comment body).
      ///
      ///       bodyStart
      ///       |
      ///     /*XXX*/
      ///       ^^^
      case comment(bodyStart: String.Index, prev: Character)
    }

    var state = State.normal(prev: "_")
    var i = str.startIndex
    var line = 1
    var lineStart = i

    while i != str.endIndex {
      let c = str[i]

      switch (state, c) {
      case (.normal("/"), "*"):
        state = .comment(bodyStart: str.index(after: i), prev: "_")
      case (.normal(_), _):
        state = .normal(prev: c)

      case (.comment(let start, "*"), "/"):
        let nameStart: String.Index
        let locIndex: String.Index
        if str[start] == "<" {
          nameStart = str.index(after: start)
          locIndex = str.index(start, offsetBy: -2) // subtract '/' and '*'
        } else {
          nameStart = start
          locIndex = str.index(after: i) // after trailing '/'
        }

        let name = String(str[nameStart..<str.index(before: i)])

        let loc = TestLocation(
          url: url,
          line: line,
          utf8Column: 1 + str.utf8.distance(from: lineStart, to: locIndex),
          utf16Column: 1 + str.utf16.distance(from: lineStart, to: locIndex))

        if let prevLoc = result.updateValue(loc, forKey: name) {
          throw Error.duplicateKey(name, prevLoc, loc)
        }

        state = .normal(prev: "_")

      case (.comment(_, "/"), "*"):
        throw Error.nestedComment(TestLocation(
          url: url,
          line: line,
          utf8Column: 1 + str.utf8.distance(from: lineStart, to: i),
          utf16Column: 1 + str.utf16.distance(from: lineStart, to: i)))

      case (.comment(let start, _), _):
        state = .comment(bodyStart: start, prev: c)
      }

      i = str.index(after: i)

      if c == "\n" {
        line += 1
        lineStart = i
      }
    }
  }

  public mutating func scan(file: URL, sourceCache: SourceFileCache) throws {
    let content = try sourceCache.get(file)
    try scan(content, url: file)
  }

  public mutating func scan(rootDirectory: URL, sourceCache: SourceFileCache) throws {
    let fm = FileManager.default

    guard let generator = fm.enumerator(at: rootDirectory, includingPropertiesForKeys: []) else {
      throw Error.noSuchFileOrDirectory(rootDirectory)
    }

    while let url = generator.nextObject() as? URL {
      if isSourceFileExtension(url.pathExtension) {
        try scan(file: url, sourceCache: sourceCache)
      }
    }
  }
}

/// Scans `rootDirectory` for test locations, returning a mapping from name to location.
///
/// See TestLocationScanner.
public func scanLocations(
  rootDirectory: URL,
  sourceCache: SourceFileCache
) throws -> [String: TestLocation] {
  var scanner = TestLocationScanner()
  try scanner.scan(rootDirectory: rootDirectory, sourceCache: sourceCache)
  return scanner.result
}

func isSourceFileExtension(_ ext: String) -> Bool {
  switch ext {
    case "swift", "c", "cpp", "m", "mm", "h", "hpp":
      return true
    default:
      return false
  }
}