Exemplo n.º 1
0
def generate_code(result: QualityResult):
    if result.prediction_result is not None:
        result.codes["cpp"] = apply_clang(
            CPP.default_code_generator(
                CodeGenArgs(CPP_TEMPLATE, result.prediction_result.format,
                            result.constant_set, CodeStyleConfig())))
        result.codes["java"] = apply_clang(
            JAVA.default_code_generator(
                CodeGenArgs(JAVA_TEMPLATE, result.prediction_result.format,
                            result.constant_set, CodeStyleConfig())))
        result.codes["rust"] = apply_clang(
            RUST.default_code_generator(
                CodeGenArgs(RUST_TEMPLATE, result.prediction_result.format,
                            result.constant_set, CodeStyleConfig())))
Exemplo n.º 2
0
    def _compile_and_run(self, lang, format, template_file,
                         expected_generated_code_file, input_file):
        code_file = os.path.join(self.temp_dir, lang.source_code_name("main"))
        exec_file, exec_args = self._exec_file_and_args(lang)
        compile_cmd = self._compile_command(lang, code_file)
        args = CodeGenArgs(template=load_text_file(template_file),
                           format_=format,
                           constants=ProblemConstantSet(123, "yes", "NO"),
                           config=CodeStyleConfig(lang=lang.name))
        code = lang.default_code_generator(args)
        # to remove version strings from test resources
        code = re.sub(r'Generated by \d+.\d+.\d+', 'Generated by x.y.z', code)
        self.compare_two_texts_ignoring_trailing_spaces(
            load_text_file(expected_generated_code_file), code)
        create_code(code, code_file)
        try:
            print("Executing:", compile_cmd)
            print(run_command(compile_cmd, self.temp_dir))

            print("Run program:", [exec_file] + exec_args)
            exec_result = run_program(exec_file, input_file, 2, exec_args,
                                      self.temp_dir)
        finally:
            self._clean_up(lang)

        print("== stdout ==")
        print(exec_result.output)
        print("== stderr ==")
        print(exec_result.stderr)

        self.assertEqual(exec_result.status.NORMAL, exec_result.status)
        return exec_result
Exemplo n.º 3
0
    def _compile_and_run(self, lang, format, template_file,
                         expected_generated_code_file, input_file):
        code_file = os.path.join(self.temp_dir, lang.source_code_name("main"))
        exec_file, exec_args = self._exec_file_and_args(lang)
        compile_cmd = self._compile_command(lang, code_file)

        args = CodeGenArgs(template=load_text_file(template_file),
                           format_=format,
                           constants=ProblemConstantSet(123, "yes", "NO"),
                           config=CodeStyleConfig())

        code = lang.default_code_generator(args)
        self.compare_two_texts_ignoring_trailing_spaces(
            load_text_file(expected_generated_code_file), code)
        create_code(code, code_file)
        print(run_command(compile_cmd, self.temp_dir))
        exec_result = run_program(exec_file, input_file, 2, exec_args,
                                  self.temp_dir)
        print("== stdout ==")
        print(exec_result.output)
        print("== stderr ==")
        print(exec_result.stderr)

        self.assertEqual(exec_result.status.NORMAL, exec_result.status)
        return exec_result
Exemplo n.º 4
0
def generate_code(result: QualityResult):
    if result.prediction_result is None:
        result_format = None
    else:
        result_format = result.prediction_result.format

    result.codes["cpp"] = apply_clang(
        CPP.default_code_generator(
            CodeGenArgs(CPP_TEMPLATE, result_format, result.constant_set,
                        CodeStyleConfig(lang=CPP.name))))
    result.codes["java"] = JAVA.default_code_generator(
        CodeGenArgs(JAVA_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=JAVA.name)))
    result.codes["rust"] = RUST.default_code_generator(
        CodeGenArgs(RUST_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=RUST.name)))
    result.codes["python"] = PYTHON.default_code_generator(
        CodeGenArgs(PYTHON_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=PYTHON.name)))
    result.codes["d"] = DLANG.default_code_generator(
        CodeGenArgs(D_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=DLANG.name)))
    result.codes["nim"] = NIM.default_code_generator(
        CodeGenArgs(NIM_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=NIM.name)))
    result.codes["csharp"] = CSHARP.default_code_generator(
        CodeGenArgs(CSHARP_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=CSHARP.name)))
Exemplo n.º 5
0
def generate_code(atcoder_client: AtCoderClient, problem_url: str,
                  config: Config, output_file: IOBase):
    problem = get_problem_from_url(problem_url)
    template_code_path = config.code_style_config.template_file
    lang = config.code_style_config.lang

    def emit_error(text):
        logging.error(with_color(text, Fore.RED))

    def emit_warning(text):
        logging.warning(text)

    def emit_info(text):
        logging.info(text)

    emit_info('{} is used for template'.format(template_code_path))

    # Fetch problem data from the statement
    try:
        content = atcoder_client.download_problem_content(problem)
    except InputFormatDetectionError as e:
        emit_error("Failed to download input format.")
        raise e
    except SampleDetectionError as e:
        emit_error("Failed to download samples.")
        raise e

    try:
        prediction_result = predict_format(content)
        emit_info(with_color("Format prediction succeeded",
                             Fore.LIGHTGREEN_EX))
    except (NoPredictionResultError, MultiplePredictionResultsError) as e:
        prediction_result = FormatPredictionResult.empty_result()
        if isinstance(e, NoPredictionResultError):
            msg = "No prediction -- Failed to understand the input format"
        else:
            msg = "Too many prediction -- Failed to understand the input format"
        emit_warning(with_color(msg, Fore.LIGHTRED_EX))

    constants = predict_constants(content.original_html)
    code_generator = config.code_style_config.code_generator
    with open(template_code_path, "r") as f:
        template = f.read()

    output_splitter()

    output_file.write(
        code_generator(
            CodeGenArgs(template, prediction_result.format, constants,
                        config.code_style_config)))
Exemplo n.º 6
0
 def verify(self,
            response: Response,
            py_test_name: str,
            lang: Language,
            template_type: str = "old",
            constants: ProblemConstantSet = ProblemConstantSet()):
     self.assertEqual(load_intermediate_format(py_test_name),
                      str(response.simple_format))
     self.assertEqual(load_intermediate_types(py_test_name),
                      str(response.types))
     self.assertEqual(
         load_generated_code(py_test_name, lang),
         self.lang_to_code_generator_func[lang](CodeGenArgs(
             self.get_template(lang, template_type),
             response.original_result.format, constants,
             CodeStyleConfig(lang=lang.name))))
Exemplo n.º 7
0
def prepare_procedure(atcoder_client: AtCoderClient, problem: Problem,
                      config: Config):
    workspace_root_path = config.code_style_config.workspace_dir
    template_code_path = config.code_style_config.template_file
    lang = config.code_style_config.lang

    pid = problem.get_alphabet()
    problem_dir_path = os.path.join(workspace_root_path,
                                    problem.get_contest().get_id(), pid)

    def emit_error(text):
        logger.error(with_color("Problem {}: {}".format(pid, text), Fore.RED))

    def emit_warning(text):
        logger.warning("Problem {}: {}".format(pid, text))

    def emit_info(text):
        logger.info("Problem {}: {}".format(pid, text))

    emit_info('{} is used for template'.format(template_code_path))

    original_html = atcoder_client.download_problem_content_raw_html(problem)
    constants = predict_constants(original_html)

    if constants.judge_method.judge_type != JudgeType.Interactive:
        # Fetch problem data from the statement
        try:
            content = get_problem_content(original_html)
        except InputFormatDetectionError as e:
            emit_error("Failed to download input format.")
            raise e
        except SampleDetectionError as e:
            emit_error("Failed to download samples.")
            raise e

        # Store examples to the directory path
        if len(content.get_samples()) == 0:
            emit_info("No samples.")
        else:
            os.makedirs(problem_dir_path, exist_ok=True)
            create_examples(content.get_samples(), problem_dir_path,
                            config.etc_config.in_example_format,
                            config.etc_config.out_example_format)
            emit_info("Created examples.")

    code_file_path = os.path.join(problem_dir_path,
                                  "main.{}".format(lang.extension))

    # If there is an existing code, just create backup
    if os.path.exists(code_file_path):
        backup_id = 1
        while True:
            backup_name = "{}.{}".format(code_file_path, backup_id)
            if not os.path.exists(backup_name):
                new_path = backup_name
                shutil.copy(code_file_path, backup_name)
                break
            backup_id += 1
        emit_info("Backup for existing code '{}' -> '{}'".format(
            code_file_path, new_path))

    if constants.judge_method.judge_type != JudgeType.Interactive:
        try:
            prediction_result = predict_format(content)
            emit_info(
                with_color("Format prediction succeeded", Fore.LIGHTGREEN_EX))
        except (NoPredictionResultError, MultiplePredictionResultsError) as e:
            prediction_result = FormatPredictionResult.empty_result()
            if isinstance(e, NoPredictionResultError):
                msg = "No prediction -- Failed to understand the input format"
            else:
                msg = "Too many prediction -- Failed to understand the input format"
            emit_warning(with_color(msg, Fore.LIGHTRED_EX))
    else:
        prediction_result = FormatPredictionResult.empty_result()

    code_generator = config.code_style_config.code_generator
    with open(template_code_path, "r") as f:
        template = f.read()

    create_code(
        code_generator(
            CodeGenArgs(template, prediction_result.format, constants,
                        config.code_style_config)), code_file_path)
    emit_info("Saved code to {}".format(code_file_path))

    # Save metadata
    metadata_path = os.path.join(problem_dir_path, "metadata.json")
    Metadata(
        problem,
        os.path.basename(code_file_path),
        config.etc_config.in_example_format.replace("{}", "*"),
        config.etc_config.out_example_format.replace("{}", "*"),
        lang,
        constants.judge_method,
    ).save_to(metadata_path)
    emit_info("Saved metadata to {}".format(metadata_path))

    if config.postprocess_config.exec_cmd_on_problem_dir is not None:
        emit_info(
            _message_on_execution(
                problem_dir_path,
                config.postprocess_config.exec_cmd_on_problem_dir))
        config.postprocess_config.execute_on_problem_dir(problem_dir_path)

    output_splitter()