Skip to content

[Macros] Copy the evaluated source into an owned memory buffer. #62440

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 8, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/Sema/TypeCheckMacros.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,9 @@ Expr *swift::expandMacroExpr(

// Create a new source buffer with the contents of the expanded macro.
auto macroBuffer =
llvm::MemoryBuffer::getMemBuffer(evaluatedSource, bufferName);
llvm::MemoryBuffer::getMemBufferCopy(evaluatedSource, bufferName);
unsigned macroBufferID = sourceMgr.addNewSourceBuffer(std::move(macroBuffer));
free((void*)evaluatedSource.data());
Copy link
Member

@rintaro rintaro Dec 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We know it works. But still a little scary.

It would be great if there's a way to pass C++ lambda to swift_ASTGen_evaluateMacro where

  • the lambda receives a temporary C string (i.e. handler callback)
    swift_ASTGen_evaluateMacro( ..., [&](unsigned char *utf8Start, size_t length) {
      // utf8Start is valid only while this lambda.
      macroBuffer = llvm::MemoryBuffer::getMemBufferCopy({utf8Start, length});
    });
  • or, the lambda receives a size and returns a buffer pointer of the size (i.e. factory)
    swift_ASTGen_evaluateMacro( ..., [&](size_t utf8Length) {
      macroBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(utf8Length + 1, bufferIdentifier);
      return macroBuffer->getBufferStart();
      // the caller initializes the buffer.
    });

So the size that allocates the memory has the responsibility to free it.

But I guess there's no way to pass C++ lambda to Swift, at this point?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can pass through a C function pointer and a context pointer, which would eliminate a copy and not have a malloc/free pair across languages.


// Create a source file to hold the macro buffer. This is automatically
// registered with the enclosing module.
Expand Down