Spicy
string.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <string>
6 #include <vector>
7 
8 #include <hilti/ast/builder/expression.h>
9 #include <hilti/ast/operators/common.h>
10 #include <hilti/ast/types/bool.h>
11 #include <hilti/ast/types/bytes.h>
12 #include <hilti/ast/types/string.h>
13 
14 namespace hilti {
15 namespace operator_ {
16 
17 STANDARD_OPERATOR_2(string, Equal, type::Bool(), type::String(), type::String(),
18  "Compares two strings lexicographically.")
19 STANDARD_OPERATOR_2(string, Unequal, type::Bool(), type::String(), type::String(),
20  "Compares two strings lexicographically.")
21 STANDARD_OPERATOR_1(string, Size, type::UnsignedInteger(64), type::String(),
22  "Returns the number of characters the string contains.");
23 STANDARD_OPERATOR_2(string, Sum, type::String(), type::String(), type::String(),
24  "Returns the concatenation of two strings.");
25 
26 BEGIN_METHOD(string, Encode)
27  auto signature() const {
28  return Signature{.self = type::constant(type::String()),
29  .result = type::Bytes(),
30  .id = "encode",
31  .args = {{.id = "charset",
32  .type = type::Enum(type::Wildcard()),
33  .default_ = builder::id("hilti::Charset::UTF8")}},
34  .doc =
35  R"(
36 Converts the string into a binary representation encoded with the given character set.
37 )"};
38  }
39 END_METHOD
40 
41 BEGIN_OPERATOR_CUSTOM(string, Modulo)
42  Type result(const std::vector<Expression>& /* ops */) const { return type::String(); }
43 
44  bool isLhs() const { return false; }
45 
46  std::vector<Operand> operands() const { return {{.type = type::String()}, {.type = type::Any()}}; }
47 
48  void validate(const expression::ResolvedOperator& /* i */, operator_::position_t /* p */) const {
49  // TODO(robin): Not sure if we need this restriction. Let's try without.
50  //
51  // if ( i.op1().type().isA<type::Tuple>() && ! i.op1().isA<expression::Ctor>() )
52  // p.node.addError("tuple argument to '%' must a be constant");
53  }
54 
55  std::string doc() const { return "Renders a printf-style format string."; }
56 END_OPERATOR_CUSTOM
57 
58 } // namespace operator_
59 } // namespace hilti