HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
predicateExpressionParser.h
Go to the documentation of this file.
1 //
2 // Copyright 2023 Pixar
3 //
4 // Licensed under the Apache License, Version 2.0 (the "Apache License")
5 // with the following modification; you may not use this file except in
6 // compliance with the Apache License and the following modification to it:
7 // Section 6. Trademarks. is deleted and replaced with:
8 //
9 // 6. Trademarks. This License does not grant permission to use the trade
10 // names, trademarks, service marks, or product names of the Licensor
11 // and its affiliates, except as required to comply with Section 4(c) of
12 // the License and to reproduce the content of the NOTICE file.
13 //
14 // You may obtain a copy of the Apache License at
15 //
16 // http://www.apache.org/licenses/LICENSE-2.0
17 //
18 // Unless required by applicable law or agreed to in writing, software
19 // distributed under the Apache License with the above modification is
20 // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
21 // KIND, either express or implied. See the Apache License for the specific
22 // language governing permissions and limitations under the Apache License.
23 //
24 
25 #ifndef PXR_USD_SDF_PREDICATE_EXPRESSION_PARSER_H
26 #define PXR_USD_SDF_PREDICATE_EXPRESSION_PARSER_H
27 
28 #include "pxr/pxr.h"
29 #include "pxr/usd/sdf/api.h"
30 
31 #include "pxr/base/tf/diagnostic.h"
32 #include "pxr/base/vt/value.h"
33 
34 #include "pxr/base/tf/pxrPEGTL/pegtl.h"
35 
36 #include <memory>
37 
39 
40 // fwd decl, from parserHelpers.cpp.
42 Sdf_EvalQuotedString(const char* x, size_t n,
43  size_t trimBothSides, unsigned int* numLines=NULL);
44 
46 {
48 
49  void PushOp(SdfPredicateExpression::Op op) { _stacks.back().PushOp(op); }
50 
52  _stacks.back().PushCall(
53  kind, std::move(_funcName), std::move(_funcArgs));
54  _funcName.clear();
55  _funcArgs.clear();
56  }
57 
58  void SetFuncName(std::string const &name) {
59  _funcName = name;
60  }
61 
62  void AddFuncArg(VtValue const &val) {
63  _funcArgs.push_back({ std::move(_funcKwArgName), val });
64  _funcKwArgName.clear();
65  }
66 
67  void SetFuncArgKWName(std::string const &kw) {
68  _funcKwArgName = kw;
69  }
70 
71  void OpenGroup() { _stacks.emplace_back(); }
72 
73  void CloseGroup() {
74  SdfPredicateExpression innerExpr = _stacks.back().Finish();
75  _stacks.pop_back();
76  _stacks.back().PushExpr(std::move(innerExpr));
77  }
78 
80  SdfPredicateExpression result = _stacks.back().Finish();
81  _stacks.clear();
82  _funcArgs.clear();
83  _funcName.clear();
84  return result;
85  }
86 
87 private:
88  struct _Stack {
89 
92  auto higherPrec = [](Op left, Op right) {
93  return (left < right) || (left == right && left != Op::Not);
94  };
95  // Reduce while prior ops have higher precendence.
96  while (!opStack.empty() && higherPrec(opStack.back(), op)) {
97  _Reduce();
98  }
99  opStack.push_back(op);
100  }
101 
103  std::string &&name,
104  std::vector<SdfPredicateExpression::FnArg> &&args) {
105  exprStack.push_back(
107  kind, std::move(name), std::move(args) }));
108  }
109 
110  void PushExpr(SdfPredicateExpression &&expr) {
111  exprStack.push_back(std::move(expr));
112  }
113 
115  while (!opStack.empty()) {
116  _Reduce();
117  }
118  SdfPredicateExpression ret = std::move(exprStack.back());
119  exprStack.clear();
120  return ret;
121  }
122 
123  private:
124  void _Reduce() {
125  SdfPredicateExpression::Op op = opStack.back();
126  opStack.pop_back();
127  SdfPredicateExpression right = std::move(exprStack.back());
128  exprStack.pop_back();
129 
130  if (op == SdfPredicateExpression::Not) {
131  // Not is the only unary op.
132  exprStack.push_back(
133  SdfPredicateExpression::MakeNot(std::move(right)));
134  }
135  else {
136  // All other ops are all binary.
137  SdfPredicateExpression left = std::move(exprStack.back());
138  exprStack.pop_back();
139  exprStack.push_back(
141  op, std::move(left), std::move(right))
142  );
143  }
144  }
145 
146  // Working space.
147  std::vector<SdfPredicateExpression::Op> opStack;
148  std::vector<SdfPredicateExpression> exprStack;
149  };
150 
151  std::vector<_Stack> _stacks;
152 
153  std::string _funcName;
154  std::string _funcKwArgName;
155  std::vector<SdfPredicateExpression::FnArg> _funcArgs;
156 };
157 
158 
159 
160 ////////////////////////////////////////////////////////////////////////
161 // Grammar.
162 
163 namespace {
164 
165 using namespace tao::TAO_PEGTL_NAMESPACE;
166 
167 template <class Rule, class Sep>
168 using LookaheadList = seq<Rule, star<at<Sep, Rule>, Sep, Rule>>;
169 
170 template <class Rule> using OptSpaced = pad<Rule, blank>;
171 
172 using OptSpacedComma = OptSpaced<one<','>>;
173 
174 ////////////////////////////////////////////////////////////////////////
175 // Predicate expression grammar.
176 
177 struct NotKW : keyword<'n','o','t'> {};
178 struct AndKW : keyword<'a','n','d'> {};
179 struct OrKW : keyword<'o','r'> {};
180 struct Inf : keyword<'i','n','f'> {};
181 struct True : keyword<'t','r','u','e'> {};
182 struct False : keyword<'f','a','l','s','e'> {};
183 struct ImpliedAnd : plus<blank> {};
184 
185 struct ReservedWord : sor<
186  NotKW, AndKW, OrKW, Inf, True, False> {};
187 
188 struct Digits : plus<range<'0','9'>> {};
189 
190 struct Exp : seq<one<'e','E'>, opt<one<'-','+'>>, must<Digits>> {};
191 struct Frac : if_must<one<'.'>, Digits> {};
192 struct PredArgFloat : seq<
193  opt<one<'-'>>, sor<Inf, seq<Digits, if_then_else<Frac, opt<Exp>, Exp>>>
194  > {};
195 struct PredArgInt : seq<opt<one<'-'>>, Digits> {};
196 
197 struct PredArgBool : sor<True, False> {};
198 
199 template <class Quote>
200 struct Escaped : sor<Quote, one<'\\', 'b', 'f', 'n', 'r', 't'>> {};
201 template <class Quote>
202 struct Unescaped : minus<utf8::range<0x20, 0x10FFFF>, Quote> {};
203 
204 template <class Quote>
205 struct StringChar : if_then_else<
206  one<'\\'>, must<Escaped<Quote>>, Unescaped<Quote>> {};
207 
208 struct QuotedString : sor<
209  if_must<one<'"'>, until<one<'"'>, StringChar<one<'"'>>>>,
210  if_must<one<'\''>, until<one<'\''>, StringChar<one<'\''>>>>
211  > {};
212 
213 struct UnquotedStringDelimiter : sor<blank, one<',', ')', '"', '\''>> {};
214 struct UnquotedString
215  : until<at<sor<UnquotedStringDelimiter, eolf>>,
216  StringChar<UnquotedStringDelimiter>> {};
217 
218 struct PredArgString : sor<QuotedString, UnquotedString> {};
219 
220 struct PredArgVal : sor<
221  PredArgFloat, PredArgInt, PredArgBool, PredArgString> {};
222 
223 struct PredKWArgName : minus<identifier, ReservedWord> {};
224 
225 struct PredKWArgPrefix : seq<PredKWArgName, OptSpaced<one<'='>>> {};
226 struct PredKWArg : if_must<PredKWArgPrefix, PredArgVal> {};
227 
228 struct PredParenPosArg : seq<not_at<PredKWArgPrefix>, PredArgVal> {};
229 
230 struct PredFuncName : minus<identifier, ReservedWord> {};
231 
232 struct PredParenArgs
233  : if_then_else<list<PredParenPosArg, OptSpacedComma>,
234  opt<OptSpacedComma, list<PredKWArg, OptSpacedComma>>,
235  opt<list<PredKWArg, OptSpacedComma>>>
236 {};
237 
238 struct PredColonArgs : list<PredArgVal, one<','>> {};
239 struct PredColonCall : if_must<seq<PredFuncName, one<':'>>, PredColonArgs> {};
240 struct PredParenCall : seq<
241  PredFuncName, OptSpaced<one<'('>>,
242  must<PredParenArgs, star<blank>, one<')'>>
243  >
244 {};
245 
246 struct PredBareCall : PredFuncName {};
247 
248 struct PredExpr;
249 
250 struct PredOpenGroup : one<'('> {};
251 struct PredCloseGroup : one<')'> {};
252 
253 struct PredAtom
254  : sor<
255  PredColonCall,
256  PredParenCall,
257  PredBareCall,
258  if_must<PredOpenGroup, OptSpaced<PredExpr>, PredCloseGroup>
259  >
260 {};
261 
262 struct PredFactor : seq<opt<OptSpaced<list<NotKW, plus<blank>>>>, PredAtom> {};
263 struct PredOperator : sor<OptSpaced<AndKW>, OptSpaced<OrKW>, ImpliedAnd> {};
264 struct PredExpr : LookaheadList<PredFactor, PredOperator> {};
265 
266 // Actions ///////////////////////////////////////////////////////////////
267 
268 template <class Rule>
269 struct PredAction : nothing<Rule> {};
270 
271 template <SdfPredicateExpression::Op op>
272 struct PredOpAction
273 {
274  template <class Input>
275  static void apply(Input const &in, SdfPredicateExprBuilder &builder) {
276  builder.PushOp(op);
277  }
278 };
279 
280 template <> struct PredAction<NotKW>
281  : PredOpAction<SdfPredicateExpression::Not> {};
282 template <> struct PredAction<AndKW>
283  : PredOpAction<SdfPredicateExpression::And> {};
284 template <> struct PredAction<OrKW>
285  : PredOpAction<SdfPredicateExpression::Or> {};
286 template <> struct PredAction<ImpliedAnd>
287  : PredOpAction<SdfPredicateExpression::ImpliedAnd> {};
288 
289 template <>
290 struct PredAction<PredOpenGroup>
291 {
292  template <class Input>
293  static void apply(Input const &in, SdfPredicateExprBuilder &builder) {
294  builder.OpenGroup();
295  }
296 };
297 
298 template <>
299 struct PredAction<PredCloseGroup>
300 {
301  template <class Input>
302  static void apply(Input const &in, SdfPredicateExprBuilder &builder) {
303  builder.CloseGroup();
304  }
305 };
306 
307 template <>
308 struct PredAction<PredFuncName>
309 {
310  template <class Input>
311  static void apply(Input const &in, SdfPredicateExprBuilder &builder) {
312  builder.SetFuncName(in.string());
313  }
314 };
315 
316 template <>
317 struct PredAction<PredArgInt>
318 {
319  template <class Input>
320  static bool apply(Input const &in, SdfPredicateExprBuilder &builder) {
321  bool outOfRange = false;
322  int64_t ival = TfStringToInt64(in.string(), &outOfRange);
323  if (outOfRange) {
324  return false;
325  }
326  builder.AddFuncArg(VtValue(ival));
327  return true;
328  }
329 };
330 
331 template <>
332 struct PredAction<PredArgBool>
333 {
334  template <class Input>
335  static void apply(Input const &in, SdfPredicateExprBuilder &builder) {
336  builder.AddFuncArg(VtValue(in.string()[0] == 't'));
337  }
338 };
339 
340 template <>
341 struct PredAction<PredArgFloat>
342 {
343  template <class Input>
344  static void apply(Input const &in, SdfPredicateExprBuilder &builder) {
345  std::string const &instr = in.string();
346  double fval;
347  if (instr == "inf") {
348  fval = std::numeric_limits<double>::infinity();
349  }
350  else if (instr == "-inf") {
351  fval = -std::numeric_limits<double>::infinity();
352  }
353  else {
354  fval = TfStringToDouble(instr);
355  }
356  builder.AddFuncArg(VtValue(fval));
357  }
358 };
359 
360 template <>
361 struct PredAction<PredArgString>
362 {
363  template <class Input>
364  static void apply(Input const &in, SdfPredicateExprBuilder &builder) {
365  std::string const &instr = in.string();
366  size_t trimAmount = 0;
367  if (instr.size() >= 2 &&
368  ((instr.front() == '"' && instr.back() == '"') ||
369  (instr.front() == '\'' && instr.back() == '\''))) {
370  trimAmount = 1;
371  }
372  builder.AddFuncArg(
374  instr.c_str(), instr.size(), trimAmount)));
375  }
376 };
377 
378 template <>
379 struct PredAction<PredKWArgName>
380 {
381  template <class Input>
382  static void apply(Input const &in, SdfPredicateExprBuilder &builder) {
383  builder.SetFuncArgKWName(in.string());
384  }
385 };
386 
387 template <SdfPredicateExpression::FnCall::Kind callKind>
388 struct PredCallAction
389 {
390  template <class Input>
391  static void apply(Input const &in, SdfPredicateExprBuilder &builder) {
392  builder.PushCall(callKind);
393  }
394 };
395 template <> struct PredAction<PredBareCall>
396  : PredCallAction<SdfPredicateExpression::FnCall::BareCall> {};
397 template <> struct PredAction<PredParenCall>
398  : PredCallAction<SdfPredicateExpression::FnCall::ParenCall> {};
399 template <> struct PredAction<PredColonCall>
400  : PredCallAction<SdfPredicateExpression::FnCall::ColonCall> {};
401 
402 template <class Grammar>
403 static void Analyze() {
404  static const size_t numIssues = analyze<Grammar>();
405  if (numIssues) {
406  TF_FATAL_ERROR("%zu issues found in '%s'", numIssues,
407  TF_FUNC_NAME().c_str());
408  }
409 }
410 
411 }
412 
414 
415 #endif // PXR_USD_SDF_PREDICATE_EXPRESSION_PARSER_H
GLint left
Definition: glcorearb.h:2005
GLsizei const GLchar *const * string
Definition: glcorearb.h:814
GLdouble right
Definition: glad.h:2817
static SDF_API SdfPredicateExpression MakeCall(FnCall &&call)
Produce a new expression containing just a the function call call.
TF_API double TfStringToDouble(const std::string &txt)
**But if you need a result
Definition: thread.h:613
void SetFuncArgKWName(std::string const &kw)
GLdouble n
Definition: glcorearb.h:2008
void PushCall(SdfPredicateExpression::FnCall::Kind kind)
void AddFuncArg(VtValue const &val)
PXR_NAMESPACE_OPEN_SCOPE std::string Sdf_EvalQuotedString(const char *x, size_t n, size_t trimBothSides, unsigned int *numLines=NULL)
#define TF_FATAL_ERROR
GLuint const GLchar * name
Definition: glcorearb.h:786
static SDF_API SdfPredicateExpression MakeOp(Op op, SdfPredicateExpression &&left, SdfPredicateExpression &&right)
GLint GLenum GLint x
Definition: glcorearb.h:409
PXR_NAMESPACE_CLOSE_SCOPE PXR_NAMESPACE_OPEN_SCOPE
Definition: path.h:1441
static SDF_API SdfPredicateExpression MakeNot(SdfPredicateExpression &&right)
Produce a new expression by prepending the 'not' operator onto right.
SdfPredicateExpression Finish()
GLuint GLfloat * val
Definition: glcorearb.h:1608
#define PXR_NAMESPACE_CLOSE_SCOPE
Definition: pxr.h:91
**If you just want to fire and args
Definition: thread.h:609
void PushOp(SdfPredicateExpression::Op op)
Op
Enumerant describing a subexpression operation.
TF_API int64_t TfStringToInt64(const std::string &txt, bool *outOfRange=NULL)
Definition: value.h:167
Type Exp(const Type &x)
Return ex.
Definition: Math.h:710
void SetFuncName(std::string const &name)