stan-dev / stanc3

The Stan transpiler (from Stan to C++ and beyond).
BSD 3-Clause "New" or "Revised" License
140 stars 44 forks source link

[FR] `--standalone-functions` change auto return to plain type? #1312

Closed andrjohns closed 1 year ago

andrjohns commented 1 year ago

The --standalone-functions flag currently produces functions with an auto return type, but this needs to be replaced with a plain return type for compatibility with exposing functions through Rcpp (Rcpp generates intermediate definitions/functions which don't always play nicely with auto).

We're currently parsing the rest of the c++ to extract the plain type and replace auto. But this causes failures if the specification of plain types in the rest of the generated c++ changes in stanc3 versions (this is the cause of one of the current cmdstanr failures with 2.32).

Would it be possible to change this behaviour in stanc3 so that the plain type is returned instead of auto?

If there's a preference to keep the auto return as an option for propagating expressions, there could be an additional flag requesting plain types instead (e.g., --standalone-functions --plain-return, or similar)?

As concrete examples, the function:

functions {
  matrix ret_matrix(matrix x) { return x; }
}

Currently becomes:

auto ret_matrix(const Eigen::Matrix<double, -1, -1>& x, 
                std::ostream* pstream__ = nullptr)  {
 return dummy_model_namespace::ret_matrix(x, pstream__);
}

With the desired c++ instead being:

Eigen::Matrix<double, -1, -1> ret_matrix(const Eigen::Matrix<double, -1, -1>& x, 
                                         std::ostream* pstream__ = nullptr)  {
 return dummy_model_namespace::ret_matrix(x, pstream__);
}
WardBrian commented 1 year ago

Would it be possible to change this behaviour in stanc3 so that the plain type is returned instead of auto? If there's a preference to keep the auto return as an option for propagating expressions, there could be an additional flag requesting plain types instead (e.g., --standalone-functions --plain-return, or similar)?

I think this is reasonable. UDFs don't return Eigen expressions, to my knowledge.

I suspect the auto was there for ease-of-implementation rather than any specific advantage it provided, so I don't think we'd need to hide it behind a flag.