aboutsummaryrefslogtreecommitdiff
blob: 7af4f917388cd3fa0290148a6ae9d5b59d013ffd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
   Please use git log for copyright holder and year information

   This file is part of libbash.

   libbash is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 2 of the License, or
   (at your option) any later version.

   libbash is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with libbash.  If not, see <http://www.gnu.org/licenses/>.
*/
///
/// \file source_builtin.h
/// \brief class that implements the source builtin
///

#include "builtins/source_builtin.h"

#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
#include <thread>

#include "builtins/builtin_exceptions.h"
#include "cppbash_builtin.h"
#include "core/interpreter.h"
#include "core/bash_ast.h"
#include "exceptions.h"

namespace {
  std::mutex parse_mutex;

  std::shared_ptr<bash_ast>& parse(const std::string& path)
  {
    static std::unordered_map<std::string, std::shared_ptr<bash_ast>> ast_cache;

    std::lock_guard<std::mutex> parse_lock(parse_mutex);

    auto stored_ast = ast_cache.find(path);
    if(stored_ast == ast_cache.end())
    {
      // ensure the path is cached
      auto iter = ast_cache.insert(make_pair(path, std::shared_ptr<bash_ast>()));
      // this may throw exception
      iter.first->second.reset(new bash_ast(path));
      stored_ast = iter.first;
    }
    else if(!(stored_ast->second))
    {
      throw libbash::parse_exception(path + " cannot be fully parsed");
    }

    return stored_ast->second;
  }
}

int source_builtin::exec(const std::vector<std::string>& bash_args)
{
  if(bash_args.size() == 0)
    throw libbash::illegal_argument_exception("source: argument required");

  const std::string& original_path = _walker.resolve<std::string>("0");
  _walker.define("0", bash_args.front(), true);
  try
  {
    parse(bash_args.front())->interpret_with(_walker);
  }
  catch(return_exception& e) {}

  _walker.define("0", original_path, true);

  return _walker.get_status();
}