summaryrefslogtreecommitdiff
path: root/shell/lib/igt-toy.cc
blob: dcbb228fb97a75473d0c3b0b846168293399182f (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#include <iostream>
#include <fstream>
#include <sstream>

#include "igt-shell.h"
#include "v8-helpers.h"

using namespace v8;

static const char* ToCString(const String::Utf8Value& value) {
  return *value ? *value : "<invalid string>";
}

static void ReportException(Isolate* iso, TryCatch* try_catch)
{
  HandleScope handle_scope(iso);
  String::Utf8Value exception(iso, try_catch->Exception());
  const char* exception_string = ToCString(exception);

  Local<Message> message = try_catch->Message();
  if (message.IsEmpty()) {
    fprintf(stderr, "%s\n", exception_string);
  } else {
    String::Utf8Value filename(iso,
                               message->GetScriptOrigin().ResourceName());
    Local<Context> ctx(iso->GetCurrentContext());
    fprintf(stderr, "%s:%i: %s\n",
            ToCString(filename),
            message->GetLineNumber(ctx).FromJust(),
            exception_string);

    String::Utf8Value sourceline(iso,
                                 message->GetSourceLine(ctx).ToLocalChecked());
    fprintf(stderr, "%s\n", ToCString(sourceline));

    int start = message->GetStartColumn(ctx).FromJust();
    for (int i = 0; i < start; i++)
      fprintf(stderr, " ");
    int end = message->GetEndColumn(ctx).FromJust();
    for (int i = start; i < end; i++)
      fprintf(stderr, "^");
    fprintf(stderr, "\n");

    Local<Value> stack_trace_string;
    if (try_catch->StackTrace(ctx).ToLocal(&stack_trace_string) &&
        stack_trace_string->IsString() &&
        Local<String>::Cast(stack_trace_string)->Length() > 0) {
      String::Utf8Value stack_trace(iso, stack_trace_string);
      fprintf(stderr, "%s\n", ToCString(stack_trace));
    }
  }
}

static bool ExecuteString(Isolate* iso, Local<String> source,
			  Local<Value> name, bool print_result,
			  bool report_exceptions)
{
  HandleScope handle_scope(iso);
  TryCatch try_catch(iso);

  ScriptOrigin origin(name);
  Local<Context> ctx(iso->GetCurrentContext());
  Local<Script> script;
  if (!Script::Compile(ctx, source, &origin).ToLocal(&script)) {
    if (report_exceptions)
      ReportException(iso, &try_catch);
    return false;
  }

  Local<Value> result;
  if (!script->Run(ctx).ToLocal(&result)) {
    if (report_exceptions)
      ReportException(iso, &try_catch);
    return false;
  }

  if (print_result && !result->IsUndefined()) {
    String::Utf8Value str(iso, result);
    printf("%s\n", ToCString(str));
  }

  return true;
}

static void Print(const FunctionCallbackInfo<Value>& args)
{
  auto iso = args.GetIsolate();
  HandleScope handle_scope(iso);

  for (int i = 0; i < args.Length(); i++) {
    String::Utf8Value str(iso, args[i]);
    printf("%s%s", i ? " " : "", ToCString(str));
  }
  printf("\n");
  fflush(stdout);
}

static MaybeLocal<String> ReadStream(Isolate* iso, std::istream &in)
{
  std::stringstream out;
  out << in.rdbuf();
  std::string str = out.str();
  return String::NewFromUtf8(iso, str.c_str(), NewStringType::kNormal,
                             str.length());
}

static MaybeLocal<String> ReadFile(Isolate* iso, const char* filename)
{
  std::ifstream stream(filename);
  if (!stream)
    iso->ThrowException(AsString(iso, "Error opening file").ToLocalChecked());

  return ReadStream(iso, stream);
}

static void Read(const FunctionCallbackInfo<Value>& args)
{
  auto iso = args.GetIsolate();

  if (args.Length() != 1) {
    iso->ThrowException(AsString(iso, "Bad parameters").ToLocalChecked());
    return;
  }

  String::Utf8Value filename(iso, args[0]);
  if (*filename == NULL) {
    iso->ThrowException(AsString(iso, "Bad parameters").ToLocalChecked());
    return;
  }

  Local<String> source;
  if (!ReadFile(iso, *filename).ToLocal(&source)) {
    iso->ThrowException(AsString(iso, "Error reading file").ToLocalChecked());
    return;
  }

  args.GetReturnValue().Set(source);
}

static void Load(const FunctionCallbackInfo<Value>& args)
{
  auto iso = args.GetIsolate();

  for (int i = 0; i < args.Length(); i++) {
    HandleScope handle_scope(iso);
    String::Utf8Value filename(iso, args[i]);
    if (*filename == NULL) {
      iso->ThrowException(AsString(iso, "Bad parameters").ToLocalChecked());
      return;
    }

    Local<String> source;
    if (!ReadFile(iso, *filename).ToLocal(&source)) {
      iso->ThrowException(AsString(iso, "Error loading file").ToLocalChecked());
      return;
    }

    if (!ExecuteString(iso, source, args[i], false, false)) {
      iso->ThrowException(AsString(iso, "Error executing file").ToLocalChecked());
      return;
    }
  }
}

static void Quit(const FunctionCallbackInfo<Value>& args)
{
  int exit_code =
      args[0]->Int32Value(args.GetIsolate()->GetCurrentContext()).FromMaybe(0);
  fflush(stdout);
  fflush(stderr);
  exit(exit_code);
}

static void igt_toy_ctor(Isolate *iso, Local<ObjectTemplate> igt)
{
  HandleScope handle_scope(iso);

  auto tmpl = ObjectTemplate::New(iso);

  static const v8_helper_fn funcs[] = {
    { "print", Print },
    { "read", Read },
    { "load", Load },
    { "quit", Quit },
    { },
  };
  v8_helper_funcs(iso, tmpl, funcs);

  igt->Set(iso, "toy", tmpl);
}

static struct igt_builtin igt_toy = {
  .name = "toy",
  .ctor = igt_toy_ctor
};

__attribute__((constructor))
void __igt_register_toy__(void)
{
  igt_register_builtin(&igt_toy);
}