D std.regex - return as text - regex

Is there a possibility to return text which was used to create regular expression?
Something like this:
auto r = regex(r"[0-9]", "g"); // create regular expression
writeln(r.dumpAsText()); // this would write: [0-9]
There is nothing in http://dlang.org/phobos/std_regex.html on this. (or at least I did not notice)

No, because it compiles the regex, and I don't believe it even stores the string after compilation.
The best thing to do is just to store the string yourself on creation.
Source for struct Regex
As you can see, it doesn't store the pattern string, only the bytecode.

Typically using a subtype would work, but unfortunately ti doesn't due to failed template constraints. E.g. a plausible solution (that doesn't work right now) would be to wrap the regex as a subtype:
auto myregex(string arg1, string arg2)
{
struct RegexWrap
{
Regex!char reg;
alias reg this;
string dumpAsText;
}
return RegexWrap(regex(arg1, arg2), arg1);
}
void main()
{
auto r = myregex(r"[0-9]", "g"); // create regular expression
writeln(r.dumpAsText); // this would write: [0-9]
writeln(match("12345", r)); // won't work
}
The match function in std.regex won't work with this wrapper struct even when using a subtype, because it fails this template constraint:
public auto match(R, RegEx)(R input, RegEx re)
is(RegEx == Regex!(BasicElementOf!R)
Even if you changed the header to this, it still won't work:
public auto match(R)(R input, Regex!(BasicElementOf!R) re)
The only way it would work is if the type was explicit so the subtype could be passed:
public auto match(R)(R input, Regex!char re)
I find this to be an awkward part of D that could be improved.

Related

(clang AST matchers) How to match consecutive statements?

I'm planning a bunch of refactorings on a large code base that I'd like to automate using Clang tooling. For this, I'm trying to write a Clang AST Matcher expression.
Specifically, I'm trying to match pairs of statements that I'd like to replace with something else, like
a(); => a_and_b(x);
b(x);
So I'm trying to match an a callExpr() followed by a b callExpr() (but could be any statement, really). I have constructed matchers for the first and the second statements, independently, let's call them aMatcher() and bMatcher() but haven't found how to combine them so that they match only if they're back-to-back, something like bMatcher(follows(aMatcher()). None of the existing matchers seems to be pertinent (looked for "next", "prev", "position", ...).
How do I go about this the correct way, please?
The implementation of UseAnyOfAllOfCheck contains a private nextStmt matcher:
/// Matches a Stmt whose parent is a CompoundStmt, and which is directly
/// followed by a Stmt matching the inner matcher.
AST_MATCHER_P(Stmt, nextStmt, ast_matchers::internal::Matcher<Stmt>,
InnerMatcher) {
DynTypedNodeList Parents = Finder->getASTContext().getParents(Node);
if (Parents.size() != 1)
return false;
auto *C = Parents[0].get<CompoundStmt>();
if (!C)
return false;
const auto *I = llvm::find(C->body(), &Node);
assert(I != C->body_end() && "C is parent of Node");
if (++I == C->body_end())
return false; // Node is last statement.
return InnerMatcher.matches(**I, Finder, Builder);
}
I don't know how robust that is, but I'll try to use it and report back.

How to replace #include <optional>

I come to you today with another question that my brain can't process by itself:
I got a cpp file that includes optional as a header file. Unfortunately, this works only on c++17 forwards, and I'm trying to compile it in c++14. This cpp file uses optional like this
std::optional<std::string> GetStringPropertyValueFromJson(const std::string& Property, const web::json::value& Json)
{
if (Json.has_field(utility::conversions::to_string_t(Property)))
{
auto& propertyValue = Json.at(utility::conversions::to_string_t(Property));
if (propertyValue.is_string())
{
return std::optional<std::string>{utility::conversions::to_utf8string(propertyValue.as_string())};
}
}
return std::nullopt;
}
and then the function is used to assign values like this:
std::string tokenType = GetStringPropertyValueFromJson("token_type", responseContent).value_or("");
std::string accessToken = GetStringPropertyValueFromJson("access_token", responseContent).value_or("");
Please help me with a proper substitution for OPTIONAL. Thanks and much love
PS: From what i've read, you can replace optional with pair somehow in order to get a similar result, but I don't really know how exactly.
PPS: I am new here so any tips on how to better write my questions or anything else are greatly appreciated :)
I guess in C++14 the optional header could be included by #include <experimental/optional>.
Change your method signature to
std::string GetStringPropertyValueFromJson(const std::string& Property, const web::json::value& Json)
and in the end just return the empty string
return "";
Then later in your code use it without std::optional::value_or:
std::string tokenType = GetStringPropertyValueFromJson("token_type", responseContent);
The logic is exactly the same and you don't use std::optional.
I see now your other question about possibility to use std::pair. Yes, you could also change your method to:
std::pair<std::string, bool> GetStringPropertyValueFromJson(const std::string& Property, const web::json::value& Json)
and return std::make_pair(valueFromJson, true) in case your json property has been found, or std::make_pair("", false) in case it was not. This also solves the problem with empty (but existing) json property.
A poor mans optional string that should be sufficient for your code is this:
struct my_nullopt {};
struct my_optional {
private:
std::string value;
bool has_value = false;
public:
my_optional(my_nullopt) {}
my_optional(const std::string& v) : value(v),has_value(true) {}
T value_or(const std::string& v) {
return has_value ? value : v;
}
};
Its a rather limited interface, for example it is not possible to set the value after construction. But it appears that you do not need that.
Alternatively you can use boost/optional.
Note that the tip you got about using a pair is just what I did above: The value and a bool. Just that std::pair is for cases where you cannot give better names than first and second (eg in generic code), but it is simple to provide a better interface than std::pair does here. With a pair the value_or would be something along the line of x.first ? x.second : "".
PS: Only in the end I realized that the code you present does not actually make use of what std::optional has to offer. As you are calling value_or(""), you cannot distinguish between a field with value "" or "" because the optional had no value. Because of that, the most simple solution is to use a plain std::string and return "" instead of std::nullopt.

Is there a less verbose idiom for unpacking an optional in C++?

In the project I am currently working on I find myself writing a lot of code that looks like the following, where, get_optional_foo is returning an std::optional:
//...
auto maybe_foo = get_optional_foo(quux, ...)
if (!maybe_foo.has_value())
return {};
auto foo = maybe_foo.value()
//...
// continue on, doing things with foo...
I want to bail out of the function if I get a null option; otherwise, I want to assign a non-optional variable to the value. I've started using the convention of naming the optional with a maybe_ prefix but am wondering if there is some way of doing this such that I don't need to use a temporary for the optional at all? This variable is only ever going to be used to check for a null option and dereference if there is a value.
You don't need an intermediate object. std::optional supports a pointer interface to access it so you can just use it like:
//...
auto foo = get_optional_foo(quux, ...)
if (!foo)
return {};
//...
foo->some_member;
(*foo).some_member;
Slightly different than what you are asking, but consider:
if (auto foo = get_optional_foo(1)) {
// ...
return foo->x;
} else {
return {};
}
This places the main body of the function in an if() block, which may be more readable.
Shortest I can think of:
auto maybe_foo = get_optional_foo(quux, ...)
if (!maybe_foo) return {};
auto &foo = *maybe_foo; // alternatively, use `*maybe_foo` below
If you have multiple optionals in the function and it's very unlikely they'll be empty you can wrap the whole thing with a try - catch.
try {
auto &foo = get_optional_foo(quux, ...).value();
auto &bar = get_optional_bar(...).value();
...
} catch (std::bad_optional_access &e) {
return {};
}

Tagging std::function with a name?

I'm working on a parser combinator library, and I'd really like my parser to simply be some callable object:
typedef std::function<parse_result(parse_stream)> parser;
Which makes the parser combinators nice, eg:
parser operator &(parser a, parser b) { return both(a,b); }
but I'd like two features:
1) I'd like string literals to get promoted to a parser automatically so you can do things like:
parser option = "<" & regexp("[^+>]+");
2) I'd like a parser to have a name that I can use for error formatting. In the case of the "both" parser above, I could print that I expected a.name() and b.name() for example.
The two options I've tried so far are
a parser class that's callable, this lets me build from strings and std::function instances but a general callable has to be converted to a std::function first and from there to a parser, and C++ won't do two implicit conversions
Inheriting from std::function so I can implicitly convert the functions, but this seems to have a lot of gotchas in terms of only converting callables into a parser.
Does anyone have any thoughts on how to structure this?
You don't want a raw typedef of std function; your parser is more than a any std function.
struct parser: std::function<parse_result(parse_stream)>{
using base = std::function<parse_result(parse_stream)>;
using base::base;
};
this should permit
parser p = []( parse_stream str ) { return parse_result(7); };
as we use inheriting constructors to expose the raw std::function ctors in parser.
While you can override:
parser operator&(parser a, parser b) { return both(a,b); }
with the typedef version by putting & in the namespace of parse_result or parse_stream, I'd advise against it; there has been chat in the standarizatoin to restrict that kind of template-argument ADL. With a bare parser type, the spot to put such operator overloads is clear.
In addition some types cannot be overloaded outside of the class, like &=. With a struct you can do it in there.
None of this fixes
parser option = "<" & regexp("[^+>]+");
as the problem here is that the right hand side has no idea what the left hand side is doing (unless regexp is a function returing a parser).
First do this:
struct parser: std::function<parse_result(parse_stream)>{
using base = std::function<parse_result(parse_stream)>;
parser( char const* str ):
base( [str=std::string(str)](parse_stream stream)->parse_result { /* do work */ } )
{}
parser( char c ):
base( [c](parse_stream str)->parse_result { /* do work */ } )
{}
using base::base;
};
then you can add
namespace parsing {
// parser definition goes here
inline namespace literals {
inline parser operator""_p( char const* str ) { return str; }
}
}
and using namespace parsing::literals means "hello"_p is a parser that attempts to parse the string "hello".

How can I get a clang::QualType from a string?

I'm working on a custom checker for the clang static analyzer that checks for incorrect use of CPython APIs. I've made some progress, but I'm stuck: how can I get a clang::QualType value given the name of a type?
For example, I'd like to write something like this:
QualType ty = findTheTypeNamed("Py_ssize_t");
I've spent time looking at the code for clang::ASTContext and clang::QualType, but I'm lost.
How can I get a clang::QualType from the name of a type?
The asString narrowing matcher turns a string into a qualtype.
Here is the associated documentation :
Matches if the matched type is represented by the given string.
Given
class Y { public: void x(); };
void z() { Y* y; y->x(); }
cxxMemberCallExpr(on(hasType(asString("class Y *"))))
matches y->x()