JintWhileStatement.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using Jint.Native;
  2. using Jint.Runtime.Interpreter.Expressions;
  3. namespace Jint.Runtime.Interpreter.Statements;
  4. /// <summary>
  5. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.2
  6. /// </summary>
  7. internal sealed class JintWhileStatement : JintStatement<WhileStatement>
  8. {
  9. private string? _labelSetName;
  10. private ProbablyBlockStatement _body;
  11. private JintExpression _test = null!;
  12. public JintWhileStatement(WhileStatement statement) : base(statement)
  13. {
  14. }
  15. protected override void Initialize(EvaluationContext context)
  16. {
  17. _labelSetName = _statement.LabelSet?.Name;
  18. _body = new ProbablyBlockStatement(_statement.Body);
  19. _test = JintExpression.Build(_statement.Test);
  20. }
  21. protected override Completion ExecuteInternal(EvaluationContext context)
  22. {
  23. var v = JsValue.Undefined;
  24. while (true)
  25. {
  26. if (context.DebugMode)
  27. {
  28. context.Engine.Debugger.OnStep(_test._expression);
  29. }
  30. var jsValue = _test.GetValue(context);
  31. if (!TypeConverter.ToBoolean(jsValue))
  32. {
  33. return new Completion(CompletionType.Normal, v, _statement);
  34. }
  35. var completion = _body.Execute(context);
  36. if (!completion.Value.IsEmpty)
  37. {
  38. v = completion.Value;
  39. }
  40. if (completion.Type != CompletionType.Continue || !string.Equals(context.Target, _labelSetName, StringComparison.Ordinal))
  41. {
  42. if (completion.Type == CompletionType.Break && (context.Target == null || string.Equals(context.Target, _labelSetName, StringComparison.Ordinal)))
  43. {
  44. return new Completion(CompletionType.Normal, v, _statement);
  45. }
  46. if (completion.Type != CompletionType.Normal)
  47. {
  48. return completion;
  49. }
  50. }
  51. }
  52. }
  53. }