1+ using JetBrains . Annotations ;
2+ using SER . Code . ContextSystem . BaseContexts ;
3+ using SER . Code . ContextSystem . Interfaces ;
4+ using SER . Code . ContextSystem . Structures ;
5+ using SER . Code . Extensions ;
6+ using SER . Code . Helpers . ResultSystem ;
7+ using SER . Code . TokenSystem . Tokens ;
8+ using SER . Code . TokenSystem . Tokens . VariableTokens ;
9+ using SER . Code . ValueSystem ;
10+ using SER . Code . VariableSystem . Bases ;
11+ using SER . Code . VariableSystem . Variables ;
12+
13+ namespace SER . Code . ContextSystem . Contexts . Control ;
14+
15+ [ UsedImplicitly ]
16+ public class CatchStatement : StatementContext , IStatementExtender , IKeywordContext , IAcceptOptionalVariableDefinitionsContext
17+ {
18+ public string KeywordName => "catch" ;
19+ public string Description => "Catches an exception thrown inside of a " +
20+ typeof ( TryStatement ) . FriendlyTypeName ( true ) ;
21+ public string [ ] Arguments => [ ] ;
22+ public string ? Example =>
23+ """
24+ &collection = EmptyCollection
25+ try
26+ Print {CollectionFetch &collection 2}
27+ # throws because there's nothing at index 2
28+ catch
29+ with *exception
30+
31+ Print "Error!: {ExceptionInfo *exception message}"
32+ end
33+ """ ;
34+
35+ public IExtendableStatement . Signal Extends => IExtendableStatement . Signal . ThrewException ;
36+ protected override string FriendlyName => "'catch' statement" ;
37+
38+ public Exception ? Exception
39+ {
40+ get ;
41+ set
42+ {
43+ if ( field is not null )
44+ return ;
45+ field = value ;
46+ }
47+ }
48+ private VariableToken ? _variableToken ;
49+ private Variable ? _variable ;
50+
51+ public override TryAddTokenRes TryAddToken ( BaseToken token )
52+ {
53+ return TryAddTokenRes . Error ( $ "A { FriendlyName } does not expect any arguments.") ;
54+ }
55+
56+ public override Result VerifyCurrentState ( )
57+ {
58+ return true ;
59+ }
60+
61+ public Result SetOptionalVariables ( params VariableToken [ ] variableTokens )
62+ {
63+ if ( variableTokens . Length > 1 )
64+ return $ "Too many arguments provided for { FriendlyName } , only 1 is allowed.";
65+ var token = variableTokens . FirstOrDefault ( ) ;
66+ if ( token is null ) return true ;
67+
68+ if ( token is not ReferenceVariableToken )
69+ return $ "Variable { token . RawRepr } cannot be used for a { FriendlyName } as it's not a " +
70+ $ "{ typeof ( ReferenceVariable ) . FriendlyTypeName ( true ) } .";
71+
72+ _variableToken = token ;
73+ return true ;
74+ }
75+
76+ protected override IEnumerator < float > Execute ( )
77+ {
78+ if ( _variableToken is not null )
79+ {
80+ _variable = Variable . Create ( _variableToken . Name , Value . Parse ( Exception ! , Script ) ) ;
81+ Script . AddLocalVariable ( _variable ) ;
82+ }
83+
84+ var coro = RunChildren ( ) ;
85+ while ( coro . MoveNext ( ) )
86+ yield return coro . Current ;
87+
88+ if ( _variable is not null ) Script . RemoveLocalVariable ( _variable ) ;
89+ }
90+ }
0 commit comments