/* Copyright 2014-2015 Samsung Electronics Co., Ltd.
 *
 * 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.
 */

#include "mem-allocator.h"
#include "opcodes.h"
#include "parser.h"
#include "serializer.h"

#include "test-common.h"

#define NAME_TO_ID(op) (__op__idx_##op)

#define __OPCODE_SIZE(name, arg1, arg2, arg3) \
  (uint8_t) (sizeof (__op_##name) + 1),

static uint8_t opcode_sizes[] =
{
  OP_LIST (OPCODE_SIZE)
  0
};

static bool
opcodes_equal (const opcode_t *opcodes1, opcode_t *opcodes2, uint16_t size)
{
  uint16_t i;
  for (i = 0; i < size; i++)
  {
    uint8_t opcode_num1 = opcodes1[i].op_idx, opcode_num2 = opcodes2[i].op_idx;
    uint8_t j;

    if (opcode_num1 != opcode_num2)
    {
      return false;
    }

    if (opcode_num1 == NAME_TO_ID (nop) || opcode_num1 == NAME_TO_ID (ret))
    {
      return true;
    }

    for (j = 1; j < opcode_sizes[opcode_num1]; j++)
    {
      if (((uint8_t*)&opcodes1[i])[j] != ((uint8_t*)&opcodes2[i])[j])
      {
        return false;
      }
    }
  }

  return true;
}

/**
 * Unit test's main function.
 */
int
main (int __attr_unused___ argc,
      char __attr_unused___ **argv)
{
  TEST_INIT ();

  const opcode_t *opcodes_p;
  bool is_syntax_correct;

  mem_init ();

  // #1
  char program1[] = "a=1;var a;";

  serializer_init ();
  parser_set_show_opcodes (true);
  is_syntax_correct = parser_parse_script (program1, strlen (program1), &opcodes_p);

  JERRY_ASSERT (is_syntax_correct && opcodes_p != NULL);

  opcode_t opcodes[] =
  {
    getop_meta (OPCODE_META_TYPE_SCOPE_CODE_FLAGS, // [ ]
                OPCODE_SCOPE_CODE_FLAGS_NOT_REF_ARGUMENTS_IDENTIFIER
                | OPCODE_SCOPE_CODE_FLAGS_NOT_REF_EVAL_IDENTIFIER,
                INVALID_VALUE),
    getop_reg_var_decl (128, 129),  // var tmp128 .. tmp129;
    getop_var_decl (0),             // var a;
    getop_assignment (129, 1, 1),   // tmp129 = 1: SMALLINT;
    getop_assignment (0, 6, 129),   // a = tmp129 : TYPEOF (tmp129);
    getop_exitval (0)               // exit 0;
  };

  JERRY_ASSERT (opcodes_equal (opcodes_p, opcodes, 5));

  serializer_free ();

  // #2
  char program2[] = "var var;";

  serializer_init ();
  parser_set_show_opcodes (true);
  is_syntax_correct = parser_parse_script (program2, strlen (program2), &opcodes_p);

  JERRY_ASSERT (!is_syntax_correct && opcodes_p == NULL);

  serializer_free ();

  mem_finalize (false);

  return 0;
} /* main */
