Search in sources :

Example 6 with Flags

use of org.wso2.ballerinalang.util.Flags in project ballerina by ballerina-lang.

the class BallerinaParserService method generateJSON.

public static JsonElement generateJSON(Node node, Map<String, Node> anonStructs) throws InvocationTargetException, IllegalAccessException {
    if (node == null) {
        return JsonNull.INSTANCE;
    }
    Set<Method> methods = ClassUtils.getAllInterfaces(node.getClass()).stream().flatMap(aClass -> Arrays.stream(aClass.getMethods())).collect(Collectors.toSet());
    JsonObject nodeJson = new JsonObject();
    JsonArray wsJsonArray = new JsonArray();
    Set<Whitespace> ws = node.getWS();
    if (ws != null && !ws.isEmpty()) {
        for (Whitespace whitespace : ws) {
            JsonObject wsJson = new JsonObject();
            wsJson.addProperty("ws", whitespace.getWs());
            wsJson.addProperty("i", whitespace.getIndex());
            wsJson.addProperty("text", whitespace.getPrevious());
            wsJson.addProperty("static", whitespace.isStatic());
            wsJsonArray.add(wsJson);
        }
        nodeJson.add("ws", wsJsonArray);
    }
    Diagnostic.DiagnosticPosition position = node.getPosition();
    if (position != null) {
        JsonObject positionJson = new JsonObject();
        positionJson.addProperty("startColumn", position.getStartColumn());
        positionJson.addProperty("startLine", position.getStartLine());
        positionJson.addProperty("endColumn", position.getEndColumn());
        positionJson.addProperty("endLine", position.getEndLine());
        nodeJson.add("position", positionJson);
    }
    /* Virtual props */
    JsonArray type = getType(node);
    if (type != null) {
        nodeJson.add(SYMBOL_TYPE, type);
    }
    if (node.getKind() == NodeKind.INVOCATION) {
        assert node instanceof BLangInvocation : node.getClass();
        BLangInvocation invocation = (BLangInvocation) node;
        if (invocation.symbol != null && invocation.symbol.kind != null) {
            nodeJson.addProperty(INVOCATION_TYPE, invocation.symbol.kind.toString());
        }
    }
    for (Method m : methods) {
        String name = m.getName();
        if (name.equals("getWS") || name.equals("getPosition")) {
            continue;
        }
        String jsonName;
        if (name.startsWith("get")) {
            jsonName = toJsonName(name, 3);
        } else if (name.startsWith("is")) {
            jsonName = toJsonName(name, 2);
        } else {
            continue;
        }
        Object prop = m.invoke(node);
        /* Literal class - This class is escaped in backend to address cases like "ss\"" and 8.0 and null */
        if (node.getKind() == NodeKind.LITERAL && "value".equals(jsonName)) {
            if (prop instanceof String) {
                nodeJson.addProperty(jsonName, '"' + StringEscapeUtils.escapeJava((String) prop) + '"');
                nodeJson.addProperty(UNESCAPED_VALUE, String.valueOf(prop));
            } else {
                nodeJson.addProperty(jsonName, String.valueOf(prop));
            }
            continue;
        }
        if (node.getKind() == NodeKind.ANNOTATION && node instanceof BLangAnnotation) {
            JsonArray attachmentPoints = new JsonArray();
            ((BLangAnnotation) node).getAttachmentPoints().stream().map(BLangAnnotationAttachmentPoint::getAttachmentPoint).map(BLangAnnotationAttachmentPoint.AttachmentPoint::getValue).map(JsonPrimitive::new).forEach(attachmentPoints::add);
            nodeJson.add("attachmentPoints", attachmentPoints);
        }
        if (node.getKind() == NodeKind.USER_DEFINED_TYPE && jsonName.equals("typeName")) {
            IdentifierNode typeNode = (IdentifierNode) prop;
            Node structNode;
            if (typeNode.getValue().startsWith("$anonStruct$") && (structNode = anonStructs.remove(typeNode.getValue())) != null) {
                JsonObject anonStruct = generateJSON(structNode, anonStructs).getAsJsonObject();
                anonStruct.addProperty("anonStruct", true);
                nodeJson.add("anonStruct", anonStruct);
                continue;
            }
        }
        if (prop instanceof List && jsonName.equals("types")) {
            // Currently we don't need any Symbols for the UI. So skipping for now.
            continue;
        }
        /* Node classes */
        if (prop instanceof Node) {
            nodeJson.add(jsonName, generateJSON((Node) prop, anonStructs));
        } else if (prop instanceof List) {
            List listProp = (List) prop;
            JsonArray listPropJson = new JsonArray();
            nodeJson.add(jsonName, listPropJson);
            for (Object listPropItem : listProp) {
                if (listPropItem instanceof Node) {
                    /* Remove top level anon func and struct */
                    if (node.getKind() == NodeKind.COMPILATION_UNIT) {
                        if (listPropItem instanceof BLangStruct && ((BLangStruct) listPropItem).isAnonymous) {
                            anonStructs.put(((BLangStruct) listPropItem).getName().getValue(), ((BLangStruct) listPropItem));
                            continue;
                        }
                        if (listPropItem instanceof BLangFunction && (((BLangFunction) listPropItem)).name.value.startsWith("$lambda$")) {
                            continue;
                        }
                    }
                    listPropJson.add(generateJSON((Node) listPropItem, anonStructs));
                } else {
                    logger.debug("Can't serialize " + jsonName + ", has a an array of " + listPropItem);
                }
            }
        /* Runtime model classes */
        } else if (prop instanceof Set && jsonName.equals("flags")) {
            Set flags = (Set) prop;
            for (Flag flag : Flag.values()) {
                nodeJson.addProperty(StringUtils.lowerCase(flag.toString()), flags.contains(flag));
            }
        } else if (prop instanceof Set) {
            // TODO : limit this else if to getInputs getOutputs of transform.
            Set vars = (Set) prop;
            JsonArray listVarJson = new JsonArray();
            nodeJson.add(jsonName, listVarJson);
            for (Object obj : vars) {
                listVarJson.add(obj.toString());
            }
        } else if (prop instanceof NodeKind) {
            String kindName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, prop.toString());
            nodeJson.addProperty(jsonName, kindName);
        } else if (prop instanceof OperatorKind) {
            nodeJson.addProperty(jsonName, prop.toString());
        /* Generic classes */
        } else if (prop instanceof String) {
            nodeJson.addProperty(jsonName, (String) prop);
        } else if (prop instanceof Number) {
            nodeJson.addProperty(jsonName, (Number) prop);
        } else if (prop instanceof Boolean) {
            nodeJson.addProperty(jsonName, (Boolean) prop);
        } else if (prop instanceof Enum) {
            nodeJson.addProperty(jsonName, StringUtils.lowerCase(((Enum) prop).name()));
        } else if (prop != null) {
            nodeJson.addProperty(jsonName, prop.toString());
            String message = "Node " + node.getClass().getSimpleName() + " contains unknown type prop: " + jsonName + " of type " + prop.getClass();
            logger.error(message);
        }
    }
    return nodeJson;
}
Also used : JsonObject(com.google.gson.JsonObject) Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) StringUtils(org.apache.commons.lang3.StringUtils) ClassUtils(org.apache.commons.lang3.ClassUtils) Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic) MediaType(javax.ws.rs.core.MediaType) OperatorKind(org.ballerinalang.model.tree.OperatorKind) Flag(org.ballerinalang.model.elements.Flag) IdentifierNode(org.ballerinalang.model.tree.IdentifierNode) Consumes(javax.ws.rs.Consumes) Gson(com.google.gson.Gson) Map(java.util.Map) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit) StringEscapeUtils(org.apache.commons.lang3.StringEscapeUtils) BLangAnnotationAttachmentPoint(org.wso2.ballerinalang.compiler.tree.BLangAnnotationAttachmentPoint) Method(java.lang.reflect.Method) BLangFragmentParser(org.ballerinalang.composer.service.ballerina.parser.service.util.BLangFragmentParser) ServiceType(org.ballerinalang.composer.server.spi.ServiceType) Set(java.util.Set) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) TextDocumentServiceUtil(org.ballerinalang.langserver.TextDocumentServiceUtil) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) Whitespace(org.ballerinalang.model.Whitespace) JsonArray(com.google.gson.JsonArray) List(java.util.List) ServerConstants(org.ballerinalang.composer.server.core.ServerConstants) NodeKind(org.ballerinalang.model.tree.NodeKind) Response(javax.ws.rs.core.Response) BLangSourceFragment(org.ballerinalang.composer.service.ballerina.parser.service.model.BLangSourceFragment) Optional(java.util.Optional) ServiceInfo(org.ballerinalang.composer.server.spi.ServiceInfo) BallerinaFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile) GET(javax.ws.rs.GET) BLangAnnotation(org.wso2.ballerinalang.compiler.tree.BLangAnnotation) BFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BFile) HashMap(java.util.HashMap) JsonParser(com.google.gson.JsonParser) ParserUtils(org.ballerinalang.composer.service.ballerina.parser.service.util.ParserUtils) JsonElement(com.google.gson.JsonElement) ComposerService(org.ballerinalang.composer.server.spi.ComposerService) BType(org.wso2.ballerinalang.compiler.semantics.model.types.BType) Constants(org.ballerinalang.composer.service.ballerina.parser.Constants) JsonPrimitive(com.google.gson.JsonPrimitive) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) CaseFormat(com.google.common.base.CaseFormat) ModelPackage(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage) IOException(java.io.IOException) OPTIONS(javax.ws.rs.OPTIONS) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) Paths(java.nio.file.Paths) Node(org.ballerinalang.model.tree.Node) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) JsonNull(com.google.gson.JsonNull) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) Set(java.util.Set) IdentifierNode(org.ballerinalang.model.tree.IdentifierNode) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) Node(org.ballerinalang.model.tree.Node) JsonObject(com.google.gson.JsonObject) Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) Whitespace(org.ballerinalang.model.Whitespace) NodeKind(org.ballerinalang.model.tree.NodeKind) BLangAnnotation(org.wso2.ballerinalang.compiler.tree.BLangAnnotation) List(java.util.List) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) IdentifierNode(org.ballerinalang.model.tree.IdentifierNode) Method(java.lang.reflect.Method) BLangAnnotationAttachmentPoint(org.wso2.ballerinalang.compiler.tree.BLangAnnotationAttachmentPoint) Flag(org.ballerinalang.model.elements.Flag) JsonArray(com.google.gson.JsonArray) OperatorKind(org.ballerinalang.model.tree.OperatorKind) JsonObject(com.google.gson.JsonObject)

Example 7 with Flags

use of org.wso2.ballerinalang.util.Flags in project ballerina by ballerina-lang.

the class CommonUtil method generateJSON.

/**
 * Generate json representation for the given node.
 *
 * @param node        Node to get the json representation
 * @param anonStructs Map of anonymous structs
 * @return {@link JsonElement}          Json Representation of the node
 */
public static JsonElement generateJSON(Node node, Map<String, Node> anonStructs) {
    if (node == null) {
        return JsonNull.INSTANCE;
    }
    Set<Method> methods = ClassUtils.getAllInterfaces(node.getClass()).stream().flatMap(aClass -> Arrays.stream(aClass.getMethods())).collect(Collectors.toSet());
    JsonObject nodeJson = new JsonObject();
    JsonArray wsJsonArray = new JsonArray();
    Set<Whitespace> ws = node.getWS();
    if (ws != null && !ws.isEmpty()) {
        for (Whitespace whitespace : ws) {
            JsonObject wsJson = new JsonObject();
            wsJson.addProperty("ws", whitespace.getWs());
            wsJson.addProperty("i", whitespace.getIndex());
            wsJson.addProperty("text", whitespace.getPrevious());
            wsJson.addProperty("static", whitespace.isStatic());
            wsJsonArray.add(wsJson);
        }
        nodeJson.add("ws", wsJsonArray);
    }
    org.ballerinalang.util.diagnostic.Diagnostic.DiagnosticPosition position = node.getPosition();
    if (position != null) {
        JsonObject positionJson = new JsonObject();
        positionJson.addProperty("startColumn", position.getStartColumn());
        positionJson.addProperty("startLine", position.getStartLine());
        positionJson.addProperty("endColumn", position.getEndColumn());
        positionJson.addProperty("endLine", position.getEndLine());
        nodeJson.add("position", positionJson);
    }
    JsonArray type = getType(node);
    if (type != null) {
        nodeJson.add(SYMBOL_TYPE, type);
    }
    if (node.getKind() == NodeKind.INVOCATION) {
        assert node instanceof BLangInvocation : node.getClass();
        BLangInvocation invocation = (BLangInvocation) node;
        if (invocation.symbol != null && invocation.symbol.kind != null) {
            nodeJson.addProperty(INVOCATION_TYPE, invocation.symbol.kind.toString());
        }
    }
    for (Method m : methods) {
        String name = m.getName();
        if (name.equals("getWS") || name.equals("getPosition")) {
            continue;
        }
        String jsonName;
        if (name.startsWith("get")) {
            jsonName = toJsonName(name, 3);
        } else if (name.startsWith("is")) {
            jsonName = toJsonName(name, 2);
        } else {
            continue;
        }
        Object prop = null;
        try {
            prop = m.invoke(node);
        } catch (IllegalAccessException | InvocationTargetException e) {
            logger.error("Error while serializing source to JSON: [" + e.getMessage() + "]");
        }
        /* Literal class - This class is escaped in backend to address cases like "ss\"" and 8.0 and null */
        if (node.getKind() == NodeKind.LITERAL && "value".equals(jsonName)) {
            if (prop instanceof String) {
                nodeJson.addProperty(jsonName, '"' + StringEscapeUtils.escapeJava((String) prop) + '"');
                nodeJson.addProperty(UNESCAPED_VALUE, String.valueOf(prop));
            } else {
                nodeJson.addProperty(jsonName, String.valueOf(prop));
            }
            continue;
        }
        if (node.getKind() == NodeKind.USER_DEFINED_TYPE && jsonName.equals("typeName")) {
            IdentifierNode typeNode = (IdentifierNode) prop;
            Node structNode;
            if (typeNode.getValue().startsWith("$anonStruct$") && (structNode = anonStructs.remove(typeNode.getValue())) != null) {
                JsonObject anonStruct = generateJSON(structNode, anonStructs).getAsJsonObject();
                anonStruct.addProperty("anonStruct", true);
                nodeJson.add("anonStruct", anonStruct);
                continue;
            }
        }
        if (prop instanceof List && jsonName.equals("types")) {
            // Currently we don't need any Symbols for the UI. So skipping for now.
            continue;
        }
        /* Node classes */
        if (prop instanceof Node) {
            nodeJson.add(jsonName, generateJSON((Node) prop, anonStructs));
        } else if (prop instanceof List) {
            List listProp = (List) prop;
            JsonArray listPropJson = new JsonArray();
            nodeJson.add(jsonName, listPropJson);
            for (Object listPropItem : listProp) {
                if (listPropItem instanceof Node) {
                    /* Remove top level anon func and struct */
                    if (node.getKind() == NodeKind.COMPILATION_UNIT) {
                        if (listPropItem instanceof BLangStruct && ((BLangStruct) listPropItem).isAnonymous) {
                            anonStructs.put(((BLangStruct) listPropItem).getName().getValue(), ((BLangStruct) listPropItem));
                            continue;
                        }
                        if (listPropItem instanceof BLangFunction && (((BLangFunction) listPropItem)).name.value.startsWith("$lambda$")) {
                            continue;
                        }
                    }
                    listPropJson.add(generateJSON((Node) listPropItem, anonStructs));
                } else {
                    logger.debug("Can't serialize " + jsonName + ", has a an array of " + listPropItem);
                }
            }
        /* Runtime model classes */
        } else if (prop instanceof Set && jsonName.equals("flags")) {
            Set flags = (Set) prop;
            for (Flag flag : Flag.values()) {
                nodeJson.addProperty(StringUtils.lowerCase(flag.toString()), flags.contains(flag));
            }
        } else if (prop instanceof Set) {
            // TODO : limit this else if to getInputs getOutputs of transform.
            Set vars = (Set) prop;
            JsonArray listVarJson = new JsonArray();
            nodeJson.add(jsonName, listVarJson);
            for (Object obj : vars) {
                listVarJson.add(obj.toString());
            }
        } else if (prop instanceof NodeKind) {
            String kindName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, prop.toString());
            nodeJson.addProperty(jsonName, kindName);
        } else if (prop instanceof OperatorKind) {
            nodeJson.addProperty(jsonName, prop.toString());
        /* Generic classes */
        } else if (prop instanceof String) {
            nodeJson.addProperty(jsonName, (String) prop);
        } else if (prop instanceof Number) {
            nodeJson.addProperty(jsonName, (Number) prop);
        } else if (prop instanceof Boolean) {
            nodeJson.addProperty(jsonName, (Boolean) prop);
        } else if (prop instanceof Enum) {
            nodeJson.addProperty(jsonName, StringUtils.lowerCase(((Enum) prop).name()));
        } else if (prop != null) {
            nodeJson.addProperty(jsonName, prop.toString());
            String message = "Node " + node.getClass().getSimpleName() + " contains unknown type prop: " + jsonName + " of type " + prop.getClass();
            logger.error(message);
        }
    }
    return nodeJson;
}
Also used : JsonObject(com.google.gson.JsonObject) Arrays(java.util.Arrays) TokenStream(org.antlr.v4.runtime.TokenStream) URISyntaxException(java.net.URISyntaxException) Token(org.antlr.v4.runtime.Token) LoggerFactory(org.slf4j.LoggerFactory) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) StringUtils(org.apache.commons.lang3.StringUtils) PROJECT_DIR(org.ballerinalang.compiler.CompilerOptionName.PROJECT_DIR) ClassUtils(org.apache.commons.lang3.ClassUtils) LSDocument(org.ballerinalang.langserver.common.LSDocument) OperatorKind(org.ballerinalang.model.tree.OperatorKind) Flag(org.ballerinalang.model.elements.Flag) IdentifierNode(org.ballerinalang.model.tree.IdentifierNode) Map(java.util.Map) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit) StringEscapeUtils(org.apache.commons.lang3.StringEscapeUtils) PRESERVE_WHITESPACE(org.ballerinalang.compiler.CompilerOptionName.PRESERVE_WHITESPACE) Method(java.lang.reflect.Method) Path(java.nio.file.Path) DocumentServiceKeys(org.ballerinalang.langserver.DocumentServiceKeys) CompilerPhase(org.ballerinalang.compiler.CompilerPhase) NullSourceDirectory(org.ballerinalang.langserver.workspace.repository.NullSourceDirectory) Set(java.util.Set) COMPILER_PHASE(org.ballerinalang.compiler.CompilerOptionName.COMPILER_PHASE) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) Whitespace(org.ballerinalang.model.Whitespace) JsonArray(com.google.gson.JsonArray) List(java.util.List) NodeKind(org.ballerinalang.model.tree.NodeKind) WorkspaceDocumentManager(org.ballerinalang.langserver.workspace.WorkspaceDocumentManager) CompilerOptions(org.wso2.ballerinalang.compiler.util.CompilerOptions) ArrayList(java.util.ArrayList) JsonElement(com.google.gson.JsonElement) SourceDirectory(org.wso2.ballerinalang.compiler.SourceDirectory) Position(org.eclipse.lsp4j.Position) BType(org.wso2.ballerinalang.compiler.semantics.model.types.BType) DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) TextDocumentServiceContext(org.ballerinalang.langserver.TextDocumentServiceContext) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) CaseFormat(com.google.common.base.CaseFormat) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) Paths(java.nio.file.Paths) Node(org.ballerinalang.model.tree.Node) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) JsonNull(com.google.gson.JsonNull) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) TextDocumentFormatUtil(org.ballerinalang.langserver.format.TextDocumentFormatUtil) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) Set(java.util.Set) IdentifierNode(org.ballerinalang.model.tree.IdentifierNode) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) Node(org.ballerinalang.model.tree.Node) JsonObject(com.google.gson.JsonObject) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) Whitespace(org.ballerinalang.model.Whitespace) NodeKind(org.ballerinalang.model.tree.NodeKind) List(java.util.List) ArrayList(java.util.ArrayList) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) IdentifierNode(org.ballerinalang.model.tree.IdentifierNode) Method(java.lang.reflect.Method) Flag(org.ballerinalang.model.elements.Flag) InvocationTargetException(java.lang.reflect.InvocationTargetException) JsonArray(com.google.gson.JsonArray) OperatorKind(org.ballerinalang.model.tree.OperatorKind) JsonObject(com.google.gson.JsonObject)

Aggregations

BType (org.wso2.ballerinalang.compiler.semantics.model.types.BType)3 CaseFormat (com.google.common.base.CaseFormat)2 JsonArray (com.google.gson.JsonArray)2 JsonElement (com.google.gson.JsonElement)2 JsonNull (com.google.gson.JsonNull)2 JsonObject (com.google.gson.JsonObject)2 IOException (java.io.IOException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Method (java.lang.reflect.Method)2 Path (java.nio.file.Path)2 Paths (java.nio.file.Paths)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Map (java.util.Map)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2 ClassUtils (org.apache.commons.lang3.ClassUtils)2 StringEscapeUtils (org.apache.commons.lang3.StringEscapeUtils)2 StringUtils (org.apache.commons.lang3.StringUtils)2 Whitespace (org.ballerinalang.model.Whitespace)2