Skip to content

Commit a22dc1c

Browse files
committed
Added safe expression parsing and error handling
1 parent c757b99 commit a22dc1c

File tree

1 file changed

+60
-4
lines changed

1 file changed

+60
-4
lines changed

preview.m

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,75 @@
1616
(* Declare package context *)
1717
BeginPackage["preview`"]
1818

19-
(*TODO: Add error handling and check how it works with Lambda Feedback, check Phil's email on error handling*)
20-
PreviewFunction[response_] := Module[{result},
19+
PreviewFunction[response_] := Module[{parsedResponse, latexString, wolframString},
2120
Print["Running Preview Function"];
2221
Print["Preview Input:", response];
22+
23+
parsedResponse = SafeToExpression[response];
24+
25+
If[StringQ[parsedResponse] && StringStartsQ[parsedResponse, "Error:"],
26+
Return[
27+
<|
28+
"error" -> <|
29+
"message" -> "Unable to process expression",
30+
"error_thrown" -> parsedResponse
31+
|>
32+
|>
33+
]
34+
];
35+
36+
latexString = ToString[TeXForm[parsedResponse]];
37+
wolframString = ToString[InputForm[parsedResponse]];
38+
39+
(* Below is the current format expected by Lambda Feedback. Both the latex and sympy fields are currently required.
40+
To suggest that sympy gets renamed to parsed-expression or similar.*)
2341
<|
2442
"command" -> "preview",
2543
"result" -> <|
2644
"preview" -> <|
27-
"latex" -> response,
28-
"sympy" -> response
45+
"latex" -> latexString,
46+
"sympy" -> wolframString
2947
|>
3048
|>
3149
|>
3250
]
3351

52+
Begin["`Private`"]
53+
54+
SafeToExpression[str_String] :=
55+
Module[{expr, result},
56+
(* First check for obviously dangerous patterns in the raw string *)
57+
If[StringContainsQ[str,
58+
RegularExpression["\\b(Set|SetDelayed|Module|Block|Function|With|Do|For|While|RunProcess|Import|Export|DeleteFile|CreateFile|Get|Put|Install|Uninstall)\\b"]],
59+
Return["Error: Expression contains unsafe constructs"]
60+
];
61+
62+
(* Try to parse the expression safely *)
63+
result = Quiet @ Check[
64+
ToExpression[str, InputForm, Hold],
65+
Return["Error: Failed to parse expression"]
66+
];
67+
68+
(* If parsing succeeded, check the parsed structure *)
69+
If[MatchQ[result, Hold[_]],
70+
expr = First[result];
71+
72+
(* Check for unsafe constructs in the parsed expression *)
73+
If[!FreeQ[expr,
74+
Alternatives[
75+
Set, SetDelayed, Module, Block, Function, With,
76+
Do, For, While,
77+
RunProcess, Import, Export, DeleteFile, CreateFile,
78+
Get, Put, Install, Uninstall
79+
]],
80+
"Error: Expression contains unsafe constructs",
81+
expr (* safe expression *)
82+
],
83+
"Error: Unexpected parsing result"
84+
]
85+
]
86+
87+
88+
89+
End[]
3490
EndPackage[]

0 commit comments

Comments
 (0)