Safe damage formula environment?

Hello, I'm looking for a way to make the item and skill damage formula "safe" to evaluate.
By safe I mean limiting as much as possible out-of-scope effects like variable modifications, attributes changes and state addition.
The reason behind my issue is that in my script, there is a preview damage system used both by the interface to show an estimation of the item effects and by the computer-controlled units to rate the efficiency of their actions and choose one.

The preview can be called many times during the process.

I'm aware that by the nature of eval as it runs script commands, it's impossible to predict everything and the user of the script should ensure that they don't do out-of-scope effects in their damage formula. Still I think creating a somewhat safe environment could be helpful.

Here is my current code:
Ruby:
#==============================================================================
# Game_SafeVariables
#------------------------------------------------------------------------------
# Temporary class to handle variables and be discarded right after
#==============================================================================
class Game_SafeVariables < Game_Variables
  #--------------------------------------------------------------------------
  # override method initialize -> copy data object
  #--------------------------------------------------------------------------
  def initialize(game_variables)
    super()
    @data = game_variables.instance_variable_get(:@data).dup
  end
  #--------------------------------------------------------------------------
  # override method: on_change -> do nothing
  #--------------------------------------------------------------------------
  def on_change; end
end #Game_SafeVariables

class Game_Battler
  #--------------------------------------------------------------------------
  # overwrite method: preview_damage_eval
  #--------------------------------------------------------------------------
  def preview_damage_eval(user, item)
    gsv = Game_SafeVariables.new($game_variables)
    item.damage.eval(user.clone, self.clone, gsv)
    #original code:
    #item.damage.eval(user, self, $game_variables)
  end
end #Game_Battler

I guess I should also make some Game_SafeActor and Game_SafeEnemy to clone the battlers as shallow copies won't make them safe from state changes. Or I could add a temporary boolean to $game_temp to disable methods for Game_Actor and Game_Enemy (and in fact Game_Variables too).
I remember that in the Yanfly Engine Ace script, we had this :
Code:
class Game_Action

[...]

  alias evaluate_item_with_target_abe evaluate_item_with_target
  def evaluate_item_with_target(target)
    $game_temp.evaluating = true
    result = evaluate_item_with_target_abe(target)
    $game_temp.evaluating = false
    return result
  end

end # Game_Action

So all you had to do was check the status of $game_temp.evaluating to know if an action modifying the game status could be performed.

Code:
class Game_Battler < Game_BattlerBase

  #Shorthand methods to add buff to a battler in a damage formula.
  #  makes also sure that buffs are not applied during evaluation.
  def a_b(param_id, turns) #a_b for add_buff
    add_buff(param_id, turns) unless $game_temp.evaluating
  end

[...]

My two cents.
Just my thoughts on this matter.

The only valid reason to block features from being altered or even accessed by eval would be actual security concerns.

As an experiment, you may go down this rabbit hole as far as you can. Just don't ever think you're doing that because you wanna make it safe. What you're actually doing is limiting the power and potential of evaluating damage formulas for the sake of it for personal reasons. And that's fine as a pet project, but it's not any safer than a script call that seals or unseals a skill type. Besides, storing values in a game variable or game switch should not be considered an issue at all. There's no need for reinventing the wheel, right?

To make eval safe for damage formula usage, you'd need to focus on stuff like always returning an integer. Or even executing dangerous code like calls to delete or download or read any files. There might be more stuff that could or should be blocked by a project like yours, but I guess you got the point by now.

If you pretend to focus on safety, you better keep in mind what I said above. Otherwise, it'd be better to advertise it as self imposed feature limitations for very specific purposes.
So all you had to do was check the status of $game_temp.evaluating to know if an action modifying the game status could be performed.
Thanks, I will investigate it, I guess it would go down to this check.
As an experiment, you may go down this rabbit hole as far as you can. Just don't ever think you're doing that because you wanna make it safe. What you're actually doing is limiting the power and potential of evaluating damage formulas for the sake of it for personal reasons. And that's fine as a pet project, but it's not any safer than a script call that seals or unseals a skill type. Besides, storing values in a game variable or game switch should not be considered an issue at all. There's no need for reinventing the wheel, right?
This is a good point, I don't think this is a good idea to limit the eval, because it's here and it would cost too much time and efforts.

The issue that I have, is that I use the formula to "predict" the result if the skill or item was used on a specific target. This, as I said, fills two purposes, one to give a prediction in the menu to the user/player of the skill effects, the other to allow ais to choose the right action.
Because of this, the use of the formula (and the eval) is expanded outside of the context of using the skill directly. This creates behaviors that feels unwanted I believe? If as a user (here a maker), I write in my formula "a.add_state(2); a.atk - b.def" I would expect the addition of the state to trigger only when I use the skill. BUT because of my script, this state addition would trigger as long as the script considers the formula, which might happen a lot. (same for changing variables and switches)

I could just say, "don't do anything out of scope in your formulas if you use the script", but this would limit a lot their use (and one would need to use the call event anytime they want extra stuff). I don't think this is a limit that I want to introduce. Hence why I wanted to create this "safe environment" when (and only when) my script uses the formula.

A potential "fix" would be to add a user-provided safe formula as an input (like a notetag addition or something), that way they can ensure which formula is run by my script. This feels like the best solution that I can think of, the only issue is that it requires more parametrization by the user of the script.

Maybe something inbetween would be preferable? By default some calls would be "deactivated" when my script runs the formula (like changing variables, adding states etc.) so I can list what is automatically handled, and the user can provide an alternative formula that is run by my script when their original formula gets too complex for the script?
perhaps my script and this post from Sixth will help.
Hey,

I believe Yanfly has also made a blogpost about this topic here.

While you can try to predict what a user might put into their damage formulas, it might also help to obfuscate actually problematic formulas.
For example, if a user puts an array into one of their variables and modifies it, the changes would escape the safe environment as it stands now. If you copy too much (e.g. using Marshal.dump(DataManager.createSaveContents)), you might run into compatibility problems when you have to restore references to shared data.

On the other hand, if a user wants to use damage predictions in their game, they will probably be open to do a bit more work and rework some problematic damage formulas when given an easy option.
I don't quite remember which scripts for VXAce would feature scripted item effects in note tags for example, but such a feature should be very easy to implement if needed.
My suggestion would be to selectively parse certain portions of the code instead of evaluating everything as it usually does. This way you'd avoid reinventing the wheel, partially at least. So you could parse the add_state call instead of interpreting it directly.
Thank you all for your answers and suggestions!
perhaps my script and this post from Sixth will help.
Thanks for the share, this was an interesting read alongside Another Fen's addition. By the way the link to your script in the thread is broken (I managed to find it in your github).

I don't quite remember which scripts for VXAce would feature scripted item effects in note tags for example, but such a feature should be very easy to implement if needed
I recall Yanfly providing "lunatic" effects for vx ace, I did write a naïve semi-compatibility patch with my script so I will look into this a bit further to see what it can do.

So you could parse the add_state call instead of interpreting it directly.
I'm afraid this could easily go down a rabbit hole as I would need to divide the formula into each instructions, then look for problematic calls and remove instructions with them, but this parsing might turn out to be some self-made interpreter (mostly regarding variables/switches handling or weirder method calls with return values if they exist).
it seems easier to go along with TG22 suggestion by disabling the problematic methods themselves during the preview.


Overall, I think I will go for a "lazy" system where I give the option to provide a preview-version of the formula in the notetags where the user should enter a safe formula in it and otherwise call the damage formula when none is provided. It feels more versatile by giving more power to the user. If I happen to write many weird formulas in my own game (assuming I do work on said game project ahah), I will add TG22 suggestion to hijack the relevant script calls.
Nah, your approach is still relatively complicated, IMHO. Yet, I can't say there's really a "lazy" approach at all he, he. Any path or solution might cause some (unforeseen) issues at some point.

Testing anything actor or enemy related is as easy to implement as using a clone from the very beginning.

Yes, the real issue are those parts that I told you that should be parsed without executing them. The only thing that has crossed my mind so far would be creating a single $game_temp flag that could prevent those specific methods from being executed. How many methods would you need to alias? Who knows?
Edit: Decided to edit this post, I responded a bit quickly and got lost in thoughts ahah.
Overall, I think I will go for a "lazy" system where I give the option to provide a preview-version of the formula in the notetags where the user should enter a safe formula in it and otherwise call the damage formula when none is provided.
I like that solution too.
It also allows the user to replace unrepeatable instructions like "rand" or hide certain interactions when desired.

Original thread: https://forums.rpgmakerweb.com/threads/safe-damage-formula-environment.181120/