use of com.oracle.truffle.tools.utils.json.JSONObject in project graal by oracle.
the class InspectorRuntime method evaluate.
@Override
public Params evaluate(String expression, String objectGroup, boolean includeCommandLineAPI, boolean silent, int contextId, boolean returnByValue, boolean generatePreview, boolean awaitPromise) throws CommandProcessException {
if (expression == null) {
throw new CommandProcessException("An expression required.");
}
JSONObject json = new JSONObject();
DebuggerSuspendedInfo suspendedInfo = context.getSuspendedInfo();
if (suspendedInfo != null) {
try {
context.executeInSuspendThread(new SuspendThreadExecutable<Void>() {
@Override
public Void executeCommand() throws CommandProcessException {
suspendedInfo.lastEvaluatedValue.set(null);
LanguageInfo languageInfo = context.getSuspendedInfo().getSuspendedEvent().getTopStackFrame().getLanguage();
if (languageInfo == null || !languageInfo.isInteractive()) {
fillExceptionDetails(json, InspectorDebugger.getEvalNonInteractiveMessage());
return null;
}
JSONObject result;
DebugValue value = null;
if (suspendedInfo.getCallFrames().length > 0) {
value = InspectorDebugger.getVarValue(expression, suspendedInfo.getCallFrames()[0]);
}
if (value == null) {
value = suspendedInfo.getSuspendedEvent().getTopStackFrame().eval(expression);
suspendedInfo.refreshFrames();
}
if (returnByValue) {
result = RemoteObject.createJSONResultValue(value, context.areToStringSideEffectsAllowed(), context.getErr());
} else {
RemoteObject ro = new RemoteObject(value, generatePreview, context);
context.getRemoteObjectsHandler().register(ro, objectGroup);
result = ro.toJSON();
if (!ro.isReplicable()) {
suspendedInfo.lastEvaluatedValue.set(Pair.create(value, ro.getRawValue()));
}
}
json.put("result", result);
return null;
}
@Override
public Void processException(DebugException ex) {
fillExceptionDetails(json, ex);
return null;
}
});
} catch (NoSuspendedThreadException ex) {
fillExceptionDetails(json, ex.getLocalizedMessage());
}
} else {
fillExceptionDetails(json, "<Not suspended>");
}
return new Params(json);
}
use of com.oracle.truffle.tools.utils.json.JSONObject in project graal by oracle.
the class InspectorRuntime method callFunctionOn.
@Override
public Params callFunctionOn(String objectId, String functionDeclaration, JSONArray arguments, boolean silent, boolean returnByValue, boolean generatePreview, boolean awaitPromise, int executionContextId, String objectGroup) throws CommandProcessException {
if (objectId == null) {
throw new CommandProcessException("An objectId required.");
}
RemoteObject object = context.getRemoteObjectsHandler().getRemote(objectId);
JSONObject json = new JSONObject();
if (object != null) {
DebugValue value = object.getDebugValue();
DebugScope scope = object.getScope();
RemoteObject.IndexRange indexRange = object.getIndexRange();
DebuggerSuspendedInfo suspendedInfo = context.getSuspendedInfo();
if (suspendedInfo != null) {
try {
String functionTrimmed = functionDeclaration.trim();
String functionNoWS = eliminateWhiteSpaces(functionDeclaration);
context.executeInSuspendThread(new SuspendThreadExecutable<Void>() {
@Override
public Void executeCommand() throws CommandProcessException {
JSONObject result;
if (functionNoWS.startsWith(FUNCTION_COMPLETION)) {
result = createCodecompletion(value, scope, context, true);
} else if (functionNoWS.equals(FUNCTION_SET_PROPERTY)) {
// Set of an array element, or object property
if (arguments == null || arguments.length() < 2) {
throw new CommandProcessException("Insufficient number of arguments: " + (arguments != null ? arguments.length() : 0) + ", expecting: 2");
}
Object property = ((JSONObject) arguments.get(0)).get("value");
CallArgument newValue = CallArgument.get((JSONObject) arguments.get(1));
setPropertyValue(value, scope, property, object.getTypeMark(), newValue, suspendedInfo.lastEvaluatedValue.getAndSet(null));
result = new JSONObject();
} else if (functionNoWS.equals(FUNCTION_GET_ARRAY_NUM_PROPS)) {
if (!value.isArray()) {
throw new CommandProcessException("Expecting an Array the function is called on.");
}
JSONArray arr = new JSONArray();
if (indexRange != null && !indexRange.isNamed()) {
List<DebugValue> array = value.getArray();
if (indexRange.start() < 0 || indexRange.end() > array.size()) {
throw new CommandProcessException("Array range out of bounds.");
}
arr.put(indexRange.end() - indexRange.start());
} else {
arr.put(value.getArray().size());
}
Collection<DebugValue> props = value.getProperties();
if (props == null) {
arr.put(0);
} else if (indexRange != null && indexRange.isNamed()) {
ArrayList<DebugValue> list = new ArrayList<>(props);
if (indexRange.start() < 0 || indexRange.end() > list.size()) {
throw new CommandProcessException("Named range out of bounds.");
}
arr.put(indexRange.end() - indexRange.start());
} else if (LanguageChecks.isJS(value.getOriginalLanguage())) {
// +1 for __proto__
arr.put(props.size() + 1);
} else {
arr.put(props.size());
}
result = new JSONObject();
result.put("value", arr);
} else if (functionNoWS.equals(FUNCTION_GET_BUFFER_NUM_PROPS)) {
if (!value.isArray()) {
throw new CommandProcessException("Expecting a Buffer the function is called on.");
}
JSONArray arr = new JSONArray();
if (indexRange != null && !indexRange.isNamed()) {
List<DebugValue> array = value.getArray();
if (indexRange.start() < 0 || indexRange.end() > array.size()) {
throw new CommandProcessException("Array range out of bounds.");
}
arr.put(indexRange.end() - indexRange.start());
} else {
arr.put(value.getArray().size());
}
if (LanguageChecks.isJS(value.getOriginalLanguage())) {
// +1 for __proto__
arr.put(1);
} else {
arr.put(0);
}
result = new JSONObject();
result.put("value", arr);
} else if (functionNoWS.equals(FUNCTION_GET_COLLECTION_NUM_PROPS)) {
Collection<DebugValue> props = value.getProperties();
if (props == null) {
throw new CommandProcessException("Expecting an Object the function is called on.");
}
JSONArray arr = new JSONArray();
arr.put(0);
if (indexRange != null && indexRange.isNamed()) {
ArrayList<DebugValue> list = new ArrayList<>(props);
if (indexRange.start() < 0 || indexRange.end() > list.size()) {
throw new CommandProcessException("Named range out of bounds.");
}
arr.put(indexRange.end() - indexRange.start());
} else if (LanguageChecks.isJS(value.getOriginalLanguage())) {
// +1 for __proto__
arr.put(props.size() + 1);
} else {
arr.put(props.size());
}
result = new JSONObject();
result.put("value", arr);
} else if (FUNCTION_GETTER_PATTERN1.matcher(functionTrimmed).matches()) {
if (arguments == null || arguments.length() < 1) {
throw new CommandProcessException("Expecting an argument to invokeGetter function.");
}
String propertyNames = ((JSONObject) arguments.get(0)).getString("value");
JSONArray properties = new JSONArray(propertyNames);
DebugValue v = value;
for (int i = 0; i < properties.length() && (i == 0 || v != null); i++) {
String propertyName = properties.getString(i);
if (v != null) {
v = v.getProperty(propertyName);
} else {
v = scope.getDeclaredValue(propertyName);
}
}
result = asResult(v);
} else if (FUNCTION_GETTER_PATTERN2.matcher(functionTrimmed).matches()) {
if (arguments == null || arguments.length() < 1) {
throw new CommandProcessException("Expecting an argument to invokeGetter function.");
}
String propertyName = ((JSONObject) arguments.get(0)).getString("value");
DebugValue p;
if (value != null) {
p = value.getProperty(propertyName);
} else {
p = scope.getDeclaredValue(propertyName);
}
result = asResult(p);
} else if (FUNCTION_GET_INDEXED_VARS_PATTERN.matcher(functionTrimmed).matches()) {
if (!value.isArray()) {
throw new CommandProcessException("Expecting an Array the function is called on.");
}
if (arguments == null || arguments.length() < 2) {
throw new CommandProcessException("Insufficient number of arguments: " + (arguments != null ? arguments.length() : 0) + ", expecting: 2");
}
int start = ((JSONObject) arguments.get(0)).getInt("value");
int count = ((JSONObject) arguments.get(1)).getInt("value");
RemoteObject ro = new RemoteObject(value, true, generatePreview, context, new RemoteObject.IndexRange(start, start + count, false));
context.getRemoteObjectsHandler().register(ro, objectGroup);
result = ro.toJSON();
} else if (FUNCTION_GET_NAMED_VARS_PATTERN.matcher(functionTrimmed).matches()) {
Collection<DebugValue> props = value.getProperties();
if (props == null) {
throw new CommandProcessException("Expecting an Object the function is called on.");
}
if (arguments == null || arguments.length() < 2) {
throw new CommandProcessException("Insufficient number of arguments: " + (arguments != null ? arguments.length() : 0) + ", expecting: 2");
}
int start = ((JSONObject) arguments.get(0)).getInt("value");
int count = ((JSONObject) arguments.get(1)).getInt("value");
RemoteObject ro = new RemoteObject(value, true, generatePreview, context, new RemoteObject.IndexRange(start, start + count, true));
context.getRemoteObjectsHandler().register(ro, objectGroup);
result = ro.toJSON();
} else {
// Process CustomPreview body:
if (arguments != null && arguments.length() > 0) {
Object arg0 = arguments.get(0);
if (arg0 instanceof JSONObject) {
JSONObject argObj = (JSONObject) arg0;
Object id = argObj.opt("objectId");
if (id instanceof String) {
DebugValue body = context.getRemoteObjectsHandler().getCustomPreviewBody((String) id);
if (body != null) {
// The config is not provided as an argument.
// Get the cached config:
DebugValue config = context.getRemoteObjectsHandler().getCustomPreviewConfig(objectId);
DebugValue bodyML = (config != null) ? body.execute(object.getDebugValue(), config) : body.execute(object.getDebugValue());
Object bodyjson = CustomPreview.value2JSON(bodyML, context);
result = new JSONObject();
result.put("type", "object");
result.put("value", bodyjson);
json.put("result", result);
return null;
}
}
}
}
StringBuilder code = new StringBuilder();
code.append("(").append(functionTrimmed).append(").apply(").append(value != null ? value.getName() : "null");
if (arguments != null) {
code.append(",[");
for (int i = 0; i < arguments.length(); i++) {
JSONObject arg = arguments.getJSONObject(i);
if (i > 0) {
code.append(",");
}
Object id = arg.opt("objectId");
if (id instanceof String) {
RemoteObject remoteArg = context.getRemoteObjectsHandler().getRemote((String) id);
if (remoteArg == null) {
throw new CommandProcessException("Cannot resolve argument by its objectId: " + id);
}
code.append(remoteArg.getDebugValue().getName());
} else {
code.append(JSONObject.valueToString(arg.get("value")));
}
}
code.append("]");
}
code.append(")");
DebugValue eval = suspendedInfo.getSuspendedEvent().getTopStackFrame().eval(code.toString());
suspendedInfo.refreshFrames();
result = asResult(eval);
}
json.put("result", result);
return null;
}
@Override
public Void processException(DebugException ex) {
fillExceptionDetails(json, ex);
return null;
}
private JSONObject asResult(DebugValue v) {
JSONObject result;
if (v == null) {
LanguageInfo language = suspendedInfo.getSuspendedEvent().getTopStackFrame().getLanguage();
result = RemoteObject.createNullObject(context.getEnv(), language).toJSON();
} else {
if (!returnByValue) {
RemoteObject ro = new RemoteObject(v, true, generatePreview, context);
context.getRemoteObjectsHandler().register(ro, objectGroup);
result = ro.toJSON();
} else {
result = RemoteObject.createJSONResultValue(v, context.areToStringSideEffectsAllowed(), context.getErr());
}
}
return result;
}
});
} catch (NoSuspendedThreadException ex) {
json.put("result", new JSONObject());
}
}
}
return new Params(json);
}
use of com.oracle.truffle.tools.utils.json.JSONObject in project graal by oracle.
the class InspectorDebugger method searchInContent.
@Override
public Params searchInContent(String scriptId, String query, boolean caseSensitive, boolean isRegex) throws CommandProcessException {
if (scriptId.isEmpty() || query.isEmpty()) {
throw new CommandProcessException("Must specify both scriptId and query.");
}
Source source = getScript(scriptId).getSource();
JSONArray matchLines;
try {
matchLines = LineSearch.matchLines(source, query, caseSensitive, isRegex);
} catch (PatternSyntaxException ex) {
throw new CommandProcessException(ex.getDescription());
}
JSONObject match = new JSONObject();
match.put("properties", matchLines);
return new Params(match);
}
use of com.oracle.truffle.tools.utils.json.JSONObject in project graal by oracle.
the class InspectorDebugger method getPossibleBreakpoints.
@Override
public Params getPossibleBreakpoints(Location start, Location end, boolean restrictToFunction) throws CommandProcessException {
if (start == null) {
throw new CommandProcessException("Start location required.");
}
int scriptId = start.getScriptId();
if (end != null && scriptId != end.getScriptId()) {
throw new CommandProcessException("Different location scripts: " + scriptId + ", " + end.getScriptId());
}
Script script = scriptsHandler.getScript(scriptId);
if (script == null) {
throw new CommandProcessException("Unknown scriptId: " + scriptId);
}
JSONObject json = new JSONObject();
JSONArray arr = new JSONArray();
Source source = script.getSourceLoaded();
if (source.hasCharacters() && source.getLength() > 0) {
int lc = source.getLineCount();
int l1 = start.getLine();
int c1 = start.getColumn();
if (c1 <= 0) {
c1 = 1;
}
if (l1 > lc) {
l1 = lc;
c1 = source.getLineLength(l1);
}
int l2;
int c2;
if (end != null) {
l2 = end.getLine();
c2 = end.getColumn();
// The end should be exclusive, but not all clients adhere to that.
if (l1 != l2 || c1 != c2) {
// Only when start != end consider end as exclusive:
if (l2 > lc) {
l2 = lc;
c2 = source.getLineLength(l2);
} else {
if (c2 <= 1) {
l2 = l2 - 1;
if (l2 <= 0) {
l2 = 1;
}
c2 = source.getLineLength(l2);
} else {
c2 = c2 - 1;
}
}
if (l1 > l2) {
l1 = l2;
}
}
} else {
l2 = l1;
c2 = source.getLineLength(l2);
}
if (c2 == 0) {
// 1-based column on zero-length line
c2 = 1;
}
if (l1 == l2 && c2 < c1) {
c1 = c2;
}
SourceSection range = source.createSection(l1, c1, l2, c2);
Iterable<SourceSection> locations = SuspendableLocationFinder.findSuspendableLocations(range, restrictToFunction, debuggerSession, context.getEnv());
for (SourceSection ss : locations) {
arr.put(new Location(scriptId, ss.getStartLine(), ss.getStartColumn()).toJSON());
}
}
json.put("locations", arr);
return new Params(json);
}
use of com.oracle.truffle.tools.utils.json.JSONObject in project graal by oracle.
the class InspectorProfiler method getTypeProfile.
private Params getTypeProfile(Collection<TypeHandler.SectionTypeProfile> profiles) {
JSONObject json = new JSONObject();
Map<Source, Collection<TypeHandler.SectionTypeProfile>> sourceToProfiles = new LinkedHashMap<>();
profiles.forEach(profile -> {
Collection<TypeHandler.SectionTypeProfile> pfs = sourceToProfiles.computeIfAbsent(profile.getSourceSection().getSource(), t -> new LinkedList<>());
pfs.add(profile);
});
JSONArray result = new JSONArray();
sourceToProfiles.entrySet().forEach(entry -> {
List<TypeProfileEntry> entries = new ArrayList<>();
entry.getValue().forEach(sectionProfile -> {
List<TypeObject> types = new ArrayList<>();
sectionProfile.getTypes().forEach(type -> {
types.add(new TypeObject(type));
});
if (!types.isEmpty()) {
entries.add(new TypeProfileEntry(sectionProfile.getSourceSection().getCharEndIndex(), types.toArray(new TypeObject[types.size()])));
}
});
Script script = slh.assureLoaded(entry.getKey());
result.put(new ScriptTypeProfile(script.getId(), script.getUrl(), entries.toArray(new TypeProfileEntry[entries.size()])).toJSON());
});
json.put("result", result);
return new Params(json);
}
Aggregations