|
24 | 24 | #include "swift/AST/LayoutConstraint.h"
|
25 | 25 | #include "swift/AST/ParseRequests.h"
|
26 | 26 | #include "swift/AST/Pattern.h"
|
| 27 | +#include "swift/AST/SourceFile.h" |
27 | 28 | #include "swift/AST/Stmt.h"
|
28 | 29 | #include "swift/Basic/OptionSet.h"
|
29 | 30 | #include "swift/Config.h"
|
@@ -1325,6 +1326,49 @@ class Parser {
|
1325 | 1326 | /// Get the location for a type error.
|
1326 | 1327 | SourceLoc getTypeErrorLoc() const;
|
1327 | 1328 |
|
| 1329 | + /// Callback function used for creating a C++ AST from the syntax node at the given source location. |
| 1330 | + /// |
| 1331 | + /// The arguments to this callback are the source file to pass into ASTGen (the exported source file) |
| 1332 | + /// and the source location pointer to pass into ASTGen (to find the syntax node). |
| 1333 | + /// |
| 1334 | + /// The callback returns the new AST node and the ending location of the syntax node. If the AST node |
| 1335 | + /// is NULL, something went wrong. |
| 1336 | + template<typename T> |
| 1337 | + using ASTFromSyntaxTreeCallback = std::pair<T*, const void *>( |
| 1338 | + void *sourceFile, const void *sourceLoc |
| 1339 | + ); |
| 1340 | + |
| 1341 | + /// Parse by constructing a C++ AST node from the Swift syntax tree via ASTGen. |
| 1342 | + template<typename T> |
| 1343 | + ParserResult<T> parseASTFromSyntaxTree( |
| 1344 | + llvm::function_ref<ASTFromSyntaxTreeCallback<T>> body |
| 1345 | + ) { |
| 1346 | + if (!Context.LangOpts.hasFeature(Feature::ASTGenTypes)) |
| 1347 | + return nullptr; |
| 1348 | + |
| 1349 | + auto exportedSourceFile = SF.exportedSourceFile; |
| 1350 | + if (!exportedSourceFile) |
| 1351 | + return nullptr; |
| 1352 | + |
| 1353 | + // Perform the translation. |
| 1354 | + auto sourceLoc = Tok.getLoc().getOpaquePointerValue(); |
| 1355 | + T* astNode; |
| 1356 | + const void *endLocPtr; |
| 1357 | + std::tie(astNode, endLocPtr) = body(exportedSourceFile, sourceLoc); |
| 1358 | + |
| 1359 | + if (!astNode) { |
| 1360 | + assert(false && "Could not build AST node from syntax tree"); |
| 1361 | + return nullptr; |
| 1362 | + } |
| 1363 | + |
| 1364 | + // Spin the lexer until we get to the ending location. |
| 1365 | + while (Tok.getLoc().getOpaquePointerValue() < endLocPtr && |
| 1366 | + !Tok.is(tok::eof)) |
| 1367 | + consumeToken(); |
| 1368 | + |
| 1369 | + return makeParserResult(astNode); |
| 1370 | + } |
| 1371 | + |
1328 | 1372 | //===--------------------------------------------------------------------===//
|
1329 | 1373 | // Type Parsing
|
1330 | 1374 |
|
|
0 commit comments