use of org.ballerinalang.model.tree.NodeKind in project ballerina by ballerina-lang.
the class ModelGenerator method getContext.
public static JsonObject getContext() {
// Set alias for the classes
/*
alias.put("ConnectorInitExprNode", "ConnectorInitNode");
alias.put("XmlCommentLiteralNode", "XMLCommentLiteralNode");
alias.put("XmlElementLiteralNode", "XMLElementLiteralNode");
alias.put("XmlPiLiteralNode", "XMLProcessingInstructionLiteralNode");
alias.put("XmlTextLiteralNode", "XMLTextLiteralNode");
*/
alias.put("EnumeratorNode", "EnumNode");
alias.put("ImportNode", "ImportPackageNode");
alias.put("RecordLiteralKeyValueNode", "RecordKeyValueNode");
alias.put("XmlnsNode", "XMLNSDeclarationNode");
alias.put("ArrayLiteralExprNode", "ArrayLiteralNode");
alias.put("BinaryExprNode", "BinaryExpressionNode");
alias.put("TypeInitExprNode", "TypeInitNode");
alias.put("FieldBasedAccessExprNode", "FieldBasedAccessNode");
alias.put("IndexBasedAccessExprNode", "IndexBasedAccessNode");
alias.put("IntRangeExprNode", "IntRangeExpression");
alias.put("ActionInvocationNode", "");
alias.put("LambdaNode", "LambdaFunctionNode");
alias.put("RecordLiteralExprNode", "RecordLiteralNode");
alias.put("SimpleVariableRefNode", "SimpleVariableReferenceNode");
alias.put("TernaryExprNode", "TernaryExpressionNode");
alias.put("TypeCastExprNode", "TypeCastNode");
alias.put("TypeConversionExprNode", "TypeConversionNode");
alias.put("UnaryExprNode", "UnaryExpressionNode");
alias.put("XmlQnameNode", "XMLQNameNode");
alias.put("XmlAttributeNode", "XMLAttributeNode");
alias.put("XmlAttributeAccessExprNode", "IndexBasedAccessNode");
alias.put("XmlQuotedStringNode", "XMLQuotedStringNode");
alias.put("XmlElementLiteralNode", "XmlElementLiteralNode");
alias.put("XmlTextLiteralNode", "XMLTextLiteralNode");
alias.put("XmlCommentLiteralNode", "XmlCommentLiteralNode");
alias.put("XmlPiLiteralNode", "XMLProcessingInstructionLiteralNode");
// alias.put("TransformNode", ""); -- not used
alias.put("TryNode", "TryCatchFinallyNode");
alias.put("VariableDefNode", "VariableDefinitionNode");
alias.put("BuiltInRefTypeNode", "BuiltInReferenceTypeNode");
alias.put("EndpointTypeNode", "UserDefinedTypeNode");
alias.put("StreamletInitExprNode", "");
// alias.put("ActionInvocationNode", ""); not used
alias.put("RestArgsExprNode", "");
alias.put("NamedArgsExprNode", "");
alias.put("XmlElementLiteralNode", "");
alias.put("XmlCommentLiteralNode", "");
alias.put("TableQueryExpressionNode", "");
alias.put("MatchPatternClauseNode", "MatchStatementPatternNode");
alias.put("TransformNode", "");
alias.put("StreamNode", "");
alias.put("UnionTypeNodeNode", "UnionTypeNode");
alias.put("StreamingInputNode", "");
alias.put("JoinStreamingInputNode", "");
alias.put("TableQueryNode", "");
alias.put("SetAssignmentClauseNode", "");
alias.put("SetNode", "");
alias.put("StreamingQueryNode", "");
alias.put("QueryNode", "");
alias.put("StreamingQueryDeclarationNode", "");
alias.put("WithinNode", "");
alias.put("PatternClauseNode", "");
List<Class<?>> list = ModelGenerator.find("org.ballerinalang.model.tree");
NodeKind[] nodeKinds = NodeKind.class.getEnumConstants();
JsonObject nodes = new JsonObject();
for (NodeKind node : nodeKinds) {
String nodeKind = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, node.toString());
String nodeClassName = nodeKind + "Node";
try {
String actualClassName = (alias.get(nodeClassName) != null) ? alias.get(nodeClassName) : nodeClassName;
Class<?> clazz = list.stream().filter(nodeClass -> nodeClass.getSimpleName().equals(actualClassName)).findFirst().get();
JsonObject nodeObj = new JsonObject();
nodeObj.addProperty("kind", nodeKind);
nodeObj.addProperty("name", nodeClassName);
nodeObj.addProperty("fileName", CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, nodeClassName));
JsonArray attr = new JsonArray();
JsonArray bools = new JsonArray();
JsonArray imports = new JsonArray();
List<String> parents = Arrays.asList(clazz.getInterfaces()).stream().map(parent -> parent.getSimpleName()).collect(Collectors.toList());
// tag object with supper type
if (parents.contains("StatementNode")) {
nodeObj.addProperty("isStatement", true);
JsonObject imp = new JsonObject();
imp.addProperty("returnType", "StatementNode");
imp.addProperty("returnTypeFile", "statement-node");
imports.add(imp);
} else {
nodeObj.addProperty("isStatement", false);
}
if (parents.contains("ExpressionNode")) {
nodeObj.addProperty("isExpression", true);
JsonObject imp = new JsonObject();
imp.addProperty("returnType", "ExpressionNode");
imp.addProperty("returnTypeFile", "expression-node");
imports.add(imp);
} else {
nodeObj.addProperty("isExpression", false);
}
if (!parents.contains("StatementNode") && !parents.contains("ExpressionNode")) {
JsonObject imp = new JsonObject();
imp.addProperty("returnType", "Node");
imp.addProperty("returnTypeFile", "node");
imports.add(imp);
}
Method[] methods = clazz.getMethods();
for (Method m : methods) {
String methodName = m.getName();
if ("getKind".equals(methodName) || "getWS".equals(methodName) || "getPosition".equals(methodName)) {
continue;
}
if (methodName.startsWith("get")) {
JsonObject attribute = new JsonObject();
JsonObject imp = new JsonObject();
attribute.addProperty("property", toJsonName(m.getName(), 3));
attribute.addProperty("methodSuffix", m.getName().substring(3));
attribute.addProperty("list", List.class.isAssignableFrom(m.getReturnType()));
attribute.addProperty("isNode", Node.class.isAssignableFrom(m.getReturnType()));
if (Node.class.isAssignableFrom(m.getReturnType())) {
String returnClass = m.getReturnType().getSimpleName();
if (alias.containsValue(m.getReturnType().getSimpleName())) {
returnClass = getKindForAliasClass(m.getReturnType().getSimpleName());
}
imp.addProperty("returnType", returnClass);
attribute.addProperty("returnType", returnClass);
imp.addProperty("returnTypeFile", CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, returnClass));
if (!imports.contains(imp)) {
imports.add(imp);
}
}
attr.add(attribute);
}
if (methodName.startsWith("is")) {
JsonObject attribute = new JsonObject();
JsonObject imp = new JsonObject();
attribute.addProperty("property", toJsonName(m.getName(), 2));
attribute.addProperty("methodSuffix", m.getName().substring(2));
attribute.addProperty("list", List.class.isAssignableFrom(m.getReturnType()));
attribute.addProperty("isNode", Node.class.isAssignableFrom(m.getReturnType()));
if (Node.class.isAssignableFrom(m.getReturnType())) {
String returnClass = m.getReturnType().getSimpleName();
if (alias.containsValue(m.getReturnType().getSimpleName())) {
returnClass = getKindForAliasClass(m.getReturnType().getSimpleName());
}
imp.addProperty("returnType", returnClass);
attribute.addProperty("returnType", returnClass);
imp.addProperty("returnTypeFile", CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, returnClass));
if (!imports.contains(imp)) {
imports.add(imp);
}
}
bools.add(attribute);
}
}
nodeObj.add("attributes", attr);
nodeObj.add("bools", bools);
nodeObj.add("imports", imports);
nodes.add(nodeClassName, nodeObj);
} catch (NoSuchElementException e) {
out.println("alias.put(\"" + nodeClassName + "\", \"\");");
}
}
out.println(nodes);
return nodes;
}
use of org.ballerinalang.model.tree.NodeKind in project ballerina by ballerina-lang.
the class SemanticAnalyzer method checkRetryStmtValidity.
private void checkRetryStmtValidity(BLangExpression retryCountExpr) {
boolean error = true;
NodeKind retryKind = retryCountExpr.getKind();
if (retryKind == NodeKind.LITERAL) {
if (retryCountExpr.type.tag == TypeTags.INT) {
int retryCount = Integer.parseInt(((BLangLiteral) retryCountExpr).getValue().toString());
if (retryCount >= 0) {
error = false;
}
}
} else if (retryKind == NodeKind.SIMPLE_VARIABLE_REF) {
if (((BLangSimpleVarRef) retryCountExpr).symbol.flags == Flags.CONST) {
if (((BLangSimpleVarRef) retryCountExpr).symbol.type.tag == TypeTags.INT) {
error = false;
}
}
}
if (error) {
this.dlog.error(retryCountExpr.pos, DiagnosticCode.INVALID_RETRY_COUNT);
}
}
use of org.ballerinalang.model.tree.NodeKind in project ballerina by ballerina-lang.
the class CodeGenerator method generateFinallyInstructions.
private void generateFinallyInstructions(BLangStatement statement, NodeKind... expectedParentKinds) {
BLangStatement current = statement;
while (current != null && current.statementLink.parent != null) {
BLangStatement parent = current.statementLink.parent.statement;
for (NodeKind expected : expectedParentKinds) {
if (expected == parent.getKind()) {
return;
}
}
if (NodeKind.TRY == parent.getKind()) {
BLangTryCatchFinally tryCatchFinally = (BLangTryCatchFinally) parent;
if (tryCatchFinally.finallyBody != null && current != tryCatchFinally.finallyBody) {
genNode(tryCatchFinally.finallyBody, env);
}
} else if (NodeKind.LOCK == parent.getKind()) {
BLangLock lockNode = (BLangLock) parent;
if (!lockNode.lockVariables.isEmpty()) {
Operand[] operands = getOperands(lockNode);
emit((InstructionCodes.UNLOCK), operands);
}
}
current = parent;
}
}
use of org.ballerinalang.model.tree.NodeKind 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;
}
use of org.ballerinalang.model.tree.NodeKind 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;
}
Aggregations