<commit_before>/*
 *  Copyright 2008 <NAME> <<EMAIL>>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.ringojs.tools;

import jline.Completor;
import jline.ConsoleReader;
import jline.History;
import org.ringojs.engine.ModuleScope;
import org.ringojs.engine.RhinoEngine;
import org.ringojs.repository.Repository;
import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.ToolErrorReporter;

import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.security.CodeSource;
import java.security.CodeSigner;

/**
 * RingoShell is a simple interactive shell that provides the
 * additional global functions implemented by Ringo.
 */
public class RingoShell {

    RingoConfiguration config;
    RhinoEngine engine;
    Scriptable scope;
    boolean silent;
    File history;
    CodeSource codeSource = null;

    public RingoShell(RhinoEngine engine) throws IOException {
        this(engine, null, false);
    }

    public RingoShell(RhinoEngine engine, File history, boolean silent)
            throws IOException {
        this.config = engine.getConfiguration();
        this.engine = engine;
        this.history = history;
    	this.scope = engine.getShellScope();
        this.silent = silent;
        // FIXME give shell code a trusted code source in case security is on
        if (config.isPolicyEnabled()) {
            Repository modules = config.getRingoHome().getChildRepository("modules");
            codeSource = new CodeSource(modules.getUrl(), (CodeSigner[])null);
        }
    }

    public void run() throws IOException {
        if (silent) {
            // bypass console if running with redirected stdin or stout
            runSilently();
            return;
        }
        ConsoleReader reader = new ConsoleReader();
        reader.setBellEnabled(false);
        // reader.setDebug(new PrintWriter(new FileWriter("jline.debug")));
        reader.addCompletor(new JSCompletor());
        if (history == null) {
            history = new File(System.getProperty("user.home"), ".ringo-history");
        }
        reader.setHistory(new History(history));
        PrintWriter out = new PrintWriter(System.out);
        int lineno = 0;
        repl: while (true) {
            Context cx = engine.getContextFactory().enterContext();
            cx.setErrorReporter(new ToolErrorReporter(false, System.err));
            cx.setOptimizationLevel(-1);
            String source = "";
            String prompt = ">> ";
            while (true) {
                String newline = reader.readLine(prompt);
                if (newline == null) {
                    // NULL input, if e.g. Ctrl-D was pressed
                    out.println();
                    out.flush();
                    break repl;
                }
                source = source + newline + "\n";
                lineno++;
                if (cx.stringIsCompilableUnit(source)) {
                    break;
                }
                prompt = ".. ";
            }
            try {
                Object result = cx.evaluateString(scope, source, "<stdin>", lineno, codeSource);
                // Avoid printing out undefined or function definitions.
                if (result != Context.getUndefinedValue()) {
                    out.println(Context.toString(result));
                }
                out.flush();
                lineno++;
            } catch (Exception ex) {
                RingoRunner.reportError(ex, System.out, config.isVerbose());
            } finally {
                Context.exit();
            }
        }
        System.exit(0);
    }

    private void runSilently() throws IOException {
        int lineno = 0;
        outer: while (true) {
            Context cx = engine.getContextFactory().enterContext();
            cx.setErrorReporter(new ToolErrorReporter(false, System.err));
            cx.setOptimizationLevel(-1);
            String source = "";
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String line = reader.readLine();<commit_msg>Do not hardcode optimization level in shell, trigger GC every 10 lines<commit_after>/*
 *  Copyright 2008 <NAME> <<EMAIL>>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.ringojs.tools;

import jline.Completor;
import jline.ConsoleReader;
import jline.History;
import org.ringojs.engine.ModuleScope;
import org.ringojs.engine.RhinoEngine;
import org.ringojs.repository.Repository;
import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.ToolErrorReporter;

import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.security.CodeSource;
import java.security.CodeSigner;

/**
 * RingoShell is a simple interactive shell that provides the
 * additional global functions implemented by Ringo.
 */
public class RingoShell {

    RingoConfiguration config;
    RhinoEngine engine;
    Scriptable scope;
    boolean silent;
    File history;
    CodeSource codeSource = null;

    public RingoShell(RhinoEngine engine) throws IOException {
        this(engine, null, false);
    }

    public RingoShell(RhinoEngine engine, File history, boolean silent)
            throws IOException {
        this.config = engine.getConfiguration();
        this.engine = engine;
        this.history = history;
    	this.scope = engine.getShellScope();
        this.silent = silent;
        // FIXME give shell code a trusted code source in case security is on
        if (config.isPolicyEnabled()) {
            Repository modules = config.getRingoHome().getChildRepository("modules");
            codeSource = new CodeSource(modules.getUrl(), (CodeSigner[])null);
        }
    }

    public void run() throws IOException {
        if (silent) {
            // bypass console if running with redirected stdin or stout
            runSilently();
            return;
        }
        ConsoleReader reader = new ConsoleReader();
        reader.setBellEnabled(false);
        // reader.setDebug(new PrintWriter(new FileWriter("jline.debug")));
        reader.addCompletor(new JSCompletor());
        if (history == null) {
            history = new File(System.getProperty("user.home"), ".ringo-history");
        }
        reader.setHistory(new History(history));
        PrintWriter out = new PrintWriter(System.out);
        int lineno = 0;
        repl: while (true) {
            Context cx = engine.getContextFactory().enterContext();
            cx.setErrorReporter(new ToolErrorReporter(false, System.err));
            String source = "";
            String prompt = ">> ";
            while (true) {
                String newline = reader.readLine(prompt);
                if (newline == null) {
                    // NULL input, if e.g. Ctrl-D was pressed
                    out.println();
                    out.flush();
                    break repl;
                }
                source = source + newline + "\n";
                lineno++;
                if (cx.stringIsCompilableUnit(source)) {
                    break;
                }
                prompt = ".. ";
            }
            try {
                Script script = cx.compileString(source, "<stdin>", lineno, codeSource);
                Object result = script.exec(cx, scope);
                // Avoid printing out undefined or function definitions.
                if (result != Context.getUndefinedValue()) {
                    out.println(Context.toString(result));
                }
                out.flush();
                lineno++;
                // trigger GC once in a while - if we run in non-interpreter mode
                // we generate a lot of classes to unload
                if (lineno % 10 == 0) {
                    System.gc();
                }
            } catch (Exception ex) {
                RingoRunner.reportError(ex, System.out, config.isVerbose());
            } finally {
                Context.exit();
            }
        }
        System.exit(0);
    }

    private void runSilently() throws IOException {
        int lineno = 0;
        outer: while (true) {
            Context cx = engine.getContextFactory().enterContext();
            cx.setErrorReporter(new ToolErrorReporter(false, System.err));
            cx.setOptimizationLevel(-1);
            String source = "";
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String line = reader.readLine();
{'fraction_non_alphanumeric': 0.09809376609994848, 'fraction_numerical': 0.0030911901081916537, 'mean_word_length': 2.053161371500472, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1672859', 'n_tokens_mistral': 2531, 'n_tokens_neox': 2432, 'n_words': 719}