|
38 | 38 | */
|
39 | 39 | package com.oracle.graal.python.builtins.modules;
|
40 | 40 |
|
| 41 | +import java.util.ArrayList; |
| 42 | +import java.util.List; |
| 43 | +import java.util.regex.Matcher; |
| 44 | +import java.util.regex.Pattern; |
| 45 | + |
| 46 | +import com.oracle.graal.python.builtins.Builtin; |
41 | 47 | import com.oracle.graal.python.builtins.CoreFunctions;
|
42 | 48 | import com.oracle.graal.python.builtins.PythonBuiltins;
|
| 49 | +import com.oracle.graal.python.builtins.objects.str.PString; |
43 | 50 | import com.oracle.graal.python.nodes.function.PythonBuiltinNode;
|
| 51 | +import com.oracle.graal.python.nodes.function.builtins.PythonUnaryBuiltinNode; |
| 52 | +import com.oracle.graal.python.runtime.exception.PythonErrorType; |
| 53 | +import com.oracle.truffle.api.CompilerDirectives; |
| 54 | +import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; |
| 55 | +import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; |
| 56 | +import com.oracle.truffle.api.dsl.Fallback; |
| 57 | +import com.oracle.truffle.api.dsl.GenerateNodeFactory; |
44 | 58 | import com.oracle.truffle.api.dsl.NodeFactory;
|
45 |
| - |
46 |
| -import java.util.ArrayList; |
47 |
| -import java.util.List; |
| 59 | +import com.oracle.truffle.api.dsl.Specialization; |
48 | 60 |
|
49 | 61 | @CoreFunctions(defineModule = "_sre")
|
50 | 62 | public class SREModuleBuiltins extends PythonBuiltins {
|
51 | 63 | @Override
|
52 | 64 | protected List<? extends NodeFactory<? extends PythonBuiltinNode>> getNodeFactories() {
|
53 | 65 | return new ArrayList<>();
|
54 | 66 | }
|
| 67 | + |
| 68 | + /** |
| 69 | + * Called from C when they actually want a {@code const char*} for a Python string |
| 70 | + */ |
| 71 | + @Builtin(name = "tregex_preprocess", fixedNumOfArguments = 1) |
| 72 | + @GenerateNodeFactory |
| 73 | + abstract static class TregexPreprocessNode extends PythonUnaryBuiltinNode { |
| 74 | + @CompilationFinal private Pattern pattern; |
| 75 | + |
| 76 | + @Specialization |
| 77 | + Object run(PString str) { |
| 78 | + return run(str.getValue()); |
| 79 | + } |
| 80 | + |
| 81 | + @Specialization |
| 82 | + Object run(String str) { |
| 83 | + str.replaceAll("[^\\[]?#[^\\]]*\n", ""); |
| 84 | + if (pattern == null) { |
| 85 | + CompilerDirectives.transferToInterpreterAndInvalidate(); |
| 86 | + pattern = Pattern.compile("(?<CMT>#[^\\]]*\n)"); |
| 87 | + } |
| 88 | + return replaceAll(str); |
| 89 | + } |
| 90 | + |
| 91 | + @TruffleBoundary |
| 92 | + private String replaceAll(String r) { |
| 93 | + Matcher matcher = pattern.matcher(r); |
| 94 | + return matcher.replaceAll(""); |
| 95 | + } |
| 96 | + |
| 97 | + @Fallback |
| 98 | + Object run(Object o) { |
| 99 | + throw raise(PythonErrorType.TypeError, "expected string, not %p", o); |
| 100 | + } |
| 101 | + |
| 102 | + } |
| 103 | + |
55 | 104 | }
|
0 commit comments