Add parseSourceString method to make it easy for clients to parse a string to a module.

PiperOrigin-RevId: 211354628
diff --git a/include/mlir/Parser.h b/include/mlir/Parser.h
index 0c4a7b9..c5b5e06 100644
--- a/include/mlir/Parser.h
+++ b/include/mlir/Parser.h
@@ -23,7 +23,9 @@
 #define MLIR_PARSER_H
 
 namespace llvm {
-  class SourceMgr;
+class SourceMgr;
+class SMDiagnostic;
+class StringRef;
 } // end namespace llvm
 
 namespace mlir {
@@ -35,6 +37,11 @@
 /// the error handler registered in the context, and a null pointer is returned.
 Module *parseSourceFile(llvm::SourceMgr &sourceMgr, MLIRContext *context);
 
+/// This parses the module string to a MLIR module if it was valid.  If not, the
+/// error message is emitted through / the error handler registered in the
+/// context, and a null pointer is returned.
+Module *parseSourceString(llvm::StringRef moduleStr, MLIRContext *context);
+
 } // end namespace mlir
 
 #endif // MLIR_PARSER_H
diff --git a/lib/Parser/Parser.cpp b/lib/Parser/Parser.cpp
index 1de8a52..154a24c 100644
--- a/lib/Parser/Parser.cpp
+++ b/lib/Parser/Parser.cpp
@@ -35,9 +35,13 @@
 #include "mlir/IR/StmtVisitor.h"
 #include "mlir/IR/Types.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/PrettyStackTrace.h"
+#include "llvm/Support/SMLoc.h"
 #include "llvm/Support/SourceMgr.h"
+
 using namespace mlir;
+using llvm::MemoryBuffer;
 using llvm::SMLoc;
 using llvm::SourceMgr;
 
@@ -3030,3 +3034,15 @@
 
   return module.release();
 }
+
+/// This parses the program string to a MLIR module if it was valid. If not, it
+/// emits diagnostics and returns null.
+Module *mlir::parseSourceString(StringRef moduleStr, MLIRContext *context) {
+  auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr);
+  if (!memBuffer)
+    return nullptr;
+
+  SourceMgr sourceMgr;
+  sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
+  return parseSourceFile(sourceMgr, context);
+}