26#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/Support/SourceMgr.h"
34using llvm::MemoryBuffer;
41class CustomDialectAsmParser :
public AsmParserImpl<DialectAsmParser> {
43 CustomDialectAsmParser(StringRef fullSpec, Parser &parser)
44 : AsmParserImpl<DialectAsmParser>(parser.getToken().getLoc(), parser),
46 ~CustomDialectAsmParser()
override =
default;
50 StringRef getFullSymbolSpec()
const override {
return fullSpec; }
67 bool &isCodeCompletion) {
76 assert(*curPtr ==
'<');
78 const char *codeCompleteLoc =
state.lex.getCodeCompleteLoc();
81 auto emitPunctError = [&] {
82 return emitError() <<
"unbalanced '" << nestedPunctuation.back()
83 <<
"' character in pretty dialect name";
86 auto checkNestedPunctuation = [&](
char expectedToken) -> ParseResult {
87 if (nestedPunctuation.back() != expectedToken)
88 return emitPunctError();
89 nestedPunctuation.pop_back();
92 const char *curBufferEnd =
state.lex.getBufferEnd();
96 if (curPtr == codeCompleteLoc) {
97 isCodeCompletion =
true;
98 nestedPunctuation.clear();
102 if (curBufferEnd == curPtr) {
103 if (!nestedPunctuation.empty())
104 return emitPunctError();
105 return emitError(
"unexpected nul or EOF in pretty dialect name");
111 if (!nestedPunctuation.empty())
112 return emitPunctError();
113 return emitError(
"unexpected nul or EOF in pretty dialect name");
118 nestedPunctuation.push_back(c);
123 if (curPtr != curBufferEnd && *curPtr ==
'>')
128 if (failed(checkNestedPunctuation(
'<')))
132 if (failed(checkNestedPunctuation(
'[')))
136 if (failed(checkNestedPunctuation(
'(')))
140 if (failed(checkNestedPunctuation(
'{')))
146 curPtr =
state.curToken.getEndLoc().getPointer();
150 if (
state.curToken.isCodeCompletion()) {
151 isCodeCompletion =
true;
152 nestedPunctuation.clear();
157 if (
state.curToken.isNot(Token::string))
165 }
while (!nestedPunctuation.empty());
171 unsigned length = curPtr - body.begin();
172 body = StringRef(body.data(), length);
177template <
typename Symbol,
typename SymbolAliasMap,
typename CreateFn>
179 SymbolAliasMap &aliases,
180 CreateFn &&createSymbol) {
184 StringRef identifier = tok.
getSpelling().drop_front();
194 auto [dialectName, symbolData] = identifier.split(
'.');
195 bool isPrettyName = !symbolData.empty() || identifier.back() ==
'.';
199 bool hasTrailingData =
205 if (!hasTrailingData && !isPrettyName) {
207 auto aliasIt = aliases.find(identifier);
208 if (aliasIt == aliases.end())
213 if constexpr (std::is_same_v<Symbol, Type>)
218 return aliasIt->second;
226 symbolData = StringRef(dialectName.end(), 0);
229 bool isCodeCompletion =
false;
232 symbolData = symbolData.drop_front();
236 if (!isCodeCompletion)
237 symbolData = symbolData.drop_back();
239 loc = SMLoc::getFromPointer(symbolData.data());
247 return createSymbol(dialectName, symbolData, loc);
261 *
this,
state.asmState,
state.symbols.attributeAliasDefinitions,
262 [&](StringRef dialectName, StringRef symbolData, SMLoc loc) ->
Attribute {
264 Type attrType = type;
265 if (consumeIf(Token::colon) && !(attrType = parseType()))
269 if (Dialect *dialect =
270 builder.getContext()->getOrLoadDialect(dialectName)) {
272 const char *curLexerPos = getToken().getLoc().getPointer();
273 resetToken(symbolData.data());
276 CustomDialectAsmParser customParser(symbolData, *this);
277 Attribute attr = dialect->parseAttribute(customParser, attrType);
278 resetToken(curLexerPos);
283 return OpaqueAttr::getChecked(
284 [&] { return emitError(loc); }, StringAttr::get(ctx, dialectName),
285 symbolData, attrType ? attrType : NoneType::get(ctx));
289 auto typedAttr = dyn_cast_or_null<TypedAttr>(attr);
290 if (type && typedAttr && typedAttr.getType() != type) {
291 emitError(
"attribute type different than expected: expected ")
292 << type <<
", but got " << typedAttr.getType();
308 *
this,
state.asmState,
state.symbols.typeAliasDefinitions,
309 [&](StringRef dialectName, StringRef symbolData, SMLoc loc) ->
Type {
311 if (auto *dialect = ctx->getOrLoadDialect(dialectName)) {
313 const char *curLexerPos = getToken().getLoc().getPointer();
314 resetToken(symbolData.data());
317 CustomDialectAsmParser customParser(symbolData, *this);
318 Type type = dialect->parseType(customParser);
319 resetToken(curLexerPos);
324 return OpaqueType::getChecked([&] { return emitError(loc); },
325 StringAttr::get(ctx, dialectName),
336template <
typename T,
typename ParserFn>
338 size_t *numReadOut,
bool isKnownNullTerminated,
339 ParserFn &&parserFn) {
343 isKnownNullTerminated
344 ? MemoryBuffer::getMemBuffer(inputStr,
346 : MemoryBuffer::getMemBufferCopy(inputStr, inputStr);
348 sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
351 ParserState state(sourceMgr, config, aliasState,
nullptr,
356 T symbol = parserFn(parser);
363 endTok.
getLoc().getPointer() - startTok.
getLoc().getPointer();
365 *numReadOut = numRead;
366 }
else if (numRead != inputStr.size()) {
368 << inputStr.drop_front(numRead) <<
"'";
375 Type type,
size_t *numRead,
376 bool isKnownNullTerminated) {
378 attrStr, context, numRead, isKnownNullTerminated,
381Type
mlir::parseType(StringRef typeStr, MLIRContext *context,
size_t *numRead,
382 bool isKnownNullTerminated) {
static Symbol parseExtendedSymbol(Parser &p, AsmParserState *asmState, SymbolAliasMap &aliases, CreateFn &&createSymbol)
Parse an extended dialect symbol.
static T parseSymbol(StringRef inputStr, MLIRContext *context, size_t *numReadOut, bool isKnownNullTerminated, ParserFn &&parserFn)
Parses a symbol, of type 'T', and returns it if parsing was successful.
This class represents state from a parsed MLIR textual format string.
void addTypeAliasUses(StringRef name, SMRange locations)
void addAttrAliasUses(StringRef name, SMRange locations)
Attributes are known-constant values of operations.
MLIRContext is the top-level object for a collection of MLIR operations.
This class represents a configuration for the MLIR assembly parser.
This represents a token in the MLIR syntax.
SMRange getLocRange() const
bool isCodeCompletion() const
Returns true if the current token represents a code completion.
StringRef getSpelling() const
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides the implementation of the generic parser methods within AsmParser.
This class implement support for parsing global entities like attributes and types.
Type parseType()
Parse an arbitrary type.
Type parseExtendedType()
Parse an extended type.
InFlightDiagnostic emitError(const Twine &message={})
Emit an error and return failure.
ParserState & state
The Parser is subclassed and reinstantiated.
Attribute parseAttribute(Type type={})
Parse an arbitrary attribute with an optional type.
StringRef getTokenSpelling() const
void consumeToken()
Advance the current lexer onto the next token.
ParseResult parseDialectSymbolBody(StringRef &body, bool &isCodeCompletion)
Parse the body of a dialect symbol, which starts and ends with <>'s, and may be recursive.
InFlightDiagnostic emitWrongTokenError(const Twine &message={})
Emit an error about a "wrong token".
void resetToken(const char *tokPos)
Reset the parser to the given lexer position.
const Token & getToken() const
Return the current token the parser is inspecting.
Attribute parseExtendedAttr(Type type)
Parse an extended attribute.
MLIRContext * getContext() const
Attribute codeCompleteDialectSymbol(const llvm::StringMap< Attribute > &aliases)
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
Attribute parseAttribute(llvm::StringRef attrStr, MLIRContext *context, Type type={}, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR attribute to an MLIR context if it was valid.
Type parseType(llvm::StringRef typeStr, MLIRContext *context, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR type to an MLIR context if it was valid.
This class refers to all of the state maintained globally by the parser, such as the current lexer po...
This class contains record of any parsed top-level symbols.