MLIR 24.0.0git
DialectImplementation.h
Go to the documentation of this file.
1//===- DialectImplementation.h ----------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains utilities classes for implementing dialect attributes and
10// types.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef MLIR_IR_DIALECTIMPLEMENTATION_H
15#define MLIR_IR_DIALECTIMPLEMENTATION_H
16
18#include <type_traits>
19
20namespace {
21
22// reference https://stackoverflow.com/a/16000226
23template <typename T, typename = void>
24struct HasStaticDialectName : std::false_type {};
25
26template <typename T>
27struct HasStaticDialectName<
28 T, typename std::enable_if<
29 std::is_same<::llvm::StringLiteral,
30 std::decay_t<decltype(T::dialectName)>>::value,
31 void>::type> : std::true_type {};
32
33} // namespace
34
35namespace mlir {
36
37//===----------------------------------------------------------------------===//
38// DialectAsmPrinter
39//===----------------------------------------------------------------------===//
40
41/// This is a pure-virtual base class that exposes the asmprinter hooks
42/// necessary to implement a custom printAttribute/printType() method on a
43/// dialect.
45public:
48};
49
50//===----------------------------------------------------------------------===//
51// DialectAsmParser
52//===----------------------------------------------------------------------===//
53
54/// The DialectAsmParser has methods for interacting with the asm parser when
55/// parsing attributes and types.
57public:
60
61 /// Returns the full specification of the symbol being parsed. This allows for
62 /// using a separate parser if necessary.
63 virtual StringRef getFullSymbolSpec() const = 0;
64};
65
66//===----------------------------------------------------------------------===//
67// Parse Fields
68//===----------------------------------------------------------------------===//
69
70/// Provide a template class that can be specialized by users to dispatch to
71/// parsers. Auto-generated parsers generate calls to `FieldParser<T>::parse`,
72/// where `T` is the parameter storage type, to parse custom types.
73///
74/// A parser is key-value compositional only if it consumes exactly one value
75/// and leaves the comma separating the next key unconsumed. For example, an
76/// undelimited array parser for `values = 1, 2, next = 9` cannot distinguish
77/// its element commas from the comma before `next` and may try to parse `next`
78/// as another element. Marking it non-compositional lets a keyed property list
79/// use a self-delimiting attribute such as `array<i64: 1, 2>` instead.
80/// Specializations with this behavior, or that may succeed without consuming a
81/// token, should define `isKeyValueCompositional` as false.
82template <typename T, typename = T>
84
85/// Parse an attribute.
86template <typename AttributeT>
88 AttributeT, std::enable_if_t<std::is_base_of<Attribute, AttributeT>::value,
89 AttributeT>> {
90 static FailureOr<AttributeT> parse(AsmParser &parser) {
91 if constexpr (HasStaticDialectName<AttributeT>::value) {
92 parser.getContext()->getOrLoadDialect(AttributeT::dialectName);
93 }
94 AttributeT value;
95 if (parser.parseCustomAttributeWithFallback(value))
96 return failure();
97 return value;
98 }
99};
100
101/// Parse a type.
102template <typename TypeT>
104 TypeT, std::enable_if_t<std::is_base_of<Type, TypeT>::value, TypeT>> {
105 static FailureOr<TypeT> parse(AsmParser &parser) {
106 TypeT value;
107 if (parser.parseCustomTypeWithFallback(value))
108 return failure();
109 return value;
110 }
111};
112
113/// Parse an optional plain `char` as a single-character keyword-or-string.
114/// Identifier characters (e.g. `A`) are accepted as bare keywords; all other
115/// values use a quoted+escaped string with two-digit hex escapes (e.g. `"\0A"`
116/// for newline), covering all 256 byte values. Named escapes such as `\n` are
117/// also accepted as input but are not the canonical printed form. Returns
118/// `std::nullopt` if no keyword or string is present.
119template <>
120struct FieldParser<std::optional<char>> {
121 static constexpr bool isKeyValueCompositional = false;
122
123 static FailureOr<std::optional<char>> parse(AsmParser &parser) {
124 std::string str;
125 SMLoc loc = parser.getCurrentLocation();
126 if (failed(parser.parseOptionalKeywordOrString(&str)))
127 return {std::nullopt};
128 if (str.size() != 1)
129 return parser.emitError(loc, "expected a single character");
130 return {std::optional<char>(str[0])};
131 }
132};
133
134/// Parse a plain `char` as a single-character keyword-or-string, see
135/// `FieldParser<std::optional<char>>`.
136template <>
137struct FieldParser<char> {
138 static FailureOr<char> parse(AsmParser &parser) {
139 std::string str;
140 SMLoc loc = parser.getCurrentLocation();
141 if (failed(parser.parseKeywordOrString(&str)))
142 return failure();
143 if (str.size() != 1)
144 return parser.emitError(loc, "expected a single character");
145 return str[0];
146 }
147};
148
149/// Parse any integer.
150template <typename IntT>
151struct FieldParser<IntT, std::enable_if_t<(std::is_integral<IntT>::value ||
152 std::is_same_v<IntT, llvm::APInt>),
153 IntT>> {
154 static FailureOr<IntT> parse(AsmParser &parser) {
155 IntT value{};
156 if (parser.parseInteger(value))
157 return failure();
158 return value;
159 }
160};
161
162/// Parse a string.
163template <>
164struct FieldParser<std::string> {
165 static FailureOr<std::string> parse(AsmParser &parser) {
166 std::string value;
167 if (parser.parseString(&value))
168 return failure();
169 return value;
170 }
171};
172
173/// Parse an Optional attribute.
174template <typename AttributeT>
176 std::optional<AttributeT>,
177 std::enable_if_t<std::is_base_of<Attribute, AttributeT>::value,
178 std::optional<AttributeT>>> {
179 static constexpr bool isKeyValueCompositional = false;
180
181 static FailureOr<std::optional<AttributeT>> parse(AsmParser &parser) {
182 if constexpr (HasStaticDialectName<AttributeT>::value) {
183 parser.getContext()->getOrLoadDialect(AttributeT::dialectName);
184 }
185 AttributeT attr;
187 if (result.has_value()) {
188 if (succeeded(*result))
189 return {std::optional<AttributeT>(attr)};
190 return failure();
191 }
192 return {std::nullopt};
193 }
194};
195
196/// Parse an Optional integer.
197template <typename IntT>
199 std::optional<IntT>,
200 std::enable_if_t<std::is_integral<IntT>::value, std::optional<IntT>>> {
201 static constexpr bool isKeyValueCompositional = false;
202
203 static FailureOr<std::optional<IntT>> parse(AsmParser &parser) {
204 IntT value;
206 if (result.has_value()) {
207 if (succeeded(*result))
208 return {std::optional<IntT>(value)};
209 return failure();
210 }
211 return {std::nullopt};
212 }
213};
214
215namespace detail {
216template <typename T>
217using has_push_back_t = decltype(std::declval<T>().push_back(
218 std::declval<typename T::value_type &&>()));
219
220template <typename StorageType, typename = void>
221struct HasFieldParser : std::false_type {};
222
223template <typename StorageType>
224struct HasFieldParser<StorageType,
225 std::void_t<decltype(sizeof(FieldParser<StorageType>)),
226 decltype(FieldParser<StorageType>::parse(
227 std::declval<OpAsmParser &>()))>>
228 : std::true_type {};
229
230template <typename ContainerT, typename = void>
231struct HasFieldParserContainer : std::false_type {};
232
233template <typename ContainerT>
234struct HasFieldParserContainer<ContainerT,
235 std::void_t<has_push_back_t<ContainerT>>>
236 : HasFieldParser<typename ContainerT::value_type> {};
237
238template <typename Parser, typename = void>
239struct IsKeyValueCompositional : std::true_type {};
240
241template <typename Parser>
243 Parser, std::void_t<decltype(Parser::isKeyValueCompositional)>>
244 : std::bool_constant<Parser::isKeyValueCompositional> {};
245
246/// Whether the selected FieldParser consumes exactly one value in a keyed
247/// property list. Parser specializations may set isKeyValueCompositional to
248/// false if they can succeed without consuming a token or consume an
249/// undelimited comma-separated list.
250template <typename StorageType>
252 : std::conjunction<HasFieldParser<StorageType>,
253 IsKeyValueCompositional<FieldParser<StorageType>>> {};
254} // namespace detail
255
256/// Parse any container that supports back insertion as a list.
257template <typename ContainerT>
259 ContainerT,
260 std::enable_if_t<detail::HasFieldParserContainer<ContainerT>::value,
261 ContainerT>> {
262 static constexpr bool isKeyValueCompositional = false;
263
264 using ElementT = typename ContainerT::value_type;
265 static FailureOr<ContainerT> parse(AsmParser &parser) {
266 ContainerT elements;
267 auto elementParser = [&]() {
268 auto element = FieldParser<ElementT>::parse(parser);
269 if (failed(element))
270 return failure();
271 elements.push_back(std::move(*element));
272 return success();
273 };
274 if (parser.parseCommaSeparatedList(elementParser))
275 return failure();
276 return elements;
277 }
278};
279
280/// Parse an affine map.
281template <>
283 static FailureOr<AffineMap> parse(AsmParser &parser) {
284 AffineMap map;
285 if (failed(parser.parseAffineMap(map)))
286 return failure();
287 return map;
288 }
289};
290
291namespace detail {
292/// Parse a property with its FieldParser when one is available, otherwise
293/// fall back to the property's attribute conversion.
294template <typename StorageType, typename ConvertFromAttribute>
295ParseResult
296parsePropertyWithFallback(OpAsmParser &parser, StorageType &storage,
297 ConvertFromAttribute convertFromAttribute) {
299 auto value = FieldParser<StorageType>::parse(parser);
300 if (failed(value))
301 return failure();
302 storage = std::move(*value);
303 return success();
304 } else {
305 Attribute attr;
306 if (parser.parseAttribute(attr))
307 return failure();
308 return convertFromAttribute(storage, attr);
309 }
310}
311} // namespace detail
312
313} // namespace mlir
314
315#endif // MLIR_IR_DIALECTIMPLEMENTATION_H
return success()
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual OptionalParseResult parseOptionalInteger(APInt &result)=0
Parse an optional integer value from the stream.
AsmParser()=default
virtual ParseResult parseOptionalKeywordOrString(std::string *result)=0
Parse an optional keyword or string.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
ParseResult parseKeywordOrString(std::string *result)
Parse a keyword or a quoted string.
virtual ParseResult parseAffineMap(AffineMap &map)=0
Parse an affine map instance into 'map'.
virtual ParseResult parseCustomAttributeWithFallback(Attribute &result, Type type, function_ref< ParseResult(Attribute &result, Type type)> parseAttribute)=0
Parse a custom attribute with the provided callback, unless the next token is #, in which case the ge...
ParseResult parseString(std::string *string)
Parse a quoted string token.
virtual ParseResult parseCustomTypeWithFallback(Type &result, function_ref< ParseResult(Type &result)> parseType)=0
Parse a custom type with the provided callback, unless the next token is #, in which case the generic...
virtual OptionalParseResult parseOptionalAttribute(Attribute &result, Type type={})=0
Parse an arbitrary optional attribute of a given type and return it in result.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
AsmPrinter(Impl &impl)
Initialize the printer with the given internal implementation.
Attributes are known-constant values of operations.
Definition Attributes.h:25
The DialectAsmParser has methods for interacting with the asm parser when parsing attributes and type...
virtual StringRef getFullSymbolSpec() const =0
Returns the full specification of the symbol being parsed.
~DialectAsmParser() override
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
~DialectAsmPrinter() override
AsmPrinter(Impl &impl)
Initialize the printer with the given internal implementation.
T * getOrLoadDialect()
Get (or create) a dialect for the given derived dialect type.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
This class implements Optional functionality for ParseResult.
This class implement support for parsing global entities like attributes and types.
Definition Parser.h:27
decltype(std::declval< T >().push_back( std::declval< typename T::value_type && >())) has_push_back_t
ParseResult parsePropertyWithFallback(OpAsmParser &parser, StorageType &storage, ConvertFromAttribute convertFromAttribute)
Parse a property with its FieldParser when one is available, otherwise fall back to the property's at...
Include the generated interface declarations.
LogicalResult convertFromAttribute(int64_t &storage, Attribute attr, function_ref< InFlightDiagnostic()> emitError)
Convert an IntegerAttr attribute to an int64_t, or return an error if the attribute isn't an IntegerA...
static FailureOr< AffineMap > parse(AsmParser &parser)
static FailureOr< char > parse(AsmParser &parser)
static FailureOr< std::optional< char > > parse(AsmParser &parser)
static FailureOr< std::string > parse(AsmParser &parser)
Provide a template class that can be specialized by users to dispatch to parsers.
Whether the selected FieldParser consumes exactly one value in a keyed property list.