id stringlengths 36 36 | text stringlengths 1 1.25M |
|---|---|
376d6a89-1c89-40cd-a040-97bd5f60c89f | public static void withMBeanServerConnection(JMXConnector jmxConnector, Function1V<MBeanServerConnection> handler) {
MBeanServerConnection mBeanServerConnection = connectToMBeanServerUnchecked(jmxConnector);
handler.apply(mBeanServerConnection);
} |
02cf646e-3e39-4153-a537-cb9f86a92c0f | private static MBeanServerConnection connectToMBeanServerUnchecked(JMXConnector jmxConnector) {
try {
LOGGER.info("Connecting to MBean server with connection [{}]...", jmxConnector.getConnectionId());
MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
LOGGER.info("Connected to MBean server with connection [{}]", jmxConnector.getConnectionId());
return mBeanServerConnection;
} catch (IOException e) {
throw new RuntimeException(e);
}
} |
fcf8e98a-5585-4f4c-8902-368200395afb | public ZkVmListener(VirtualMachineDescriptor vmDescriptor, long pollPauseMillis) {
this.vmDescriptor = vmDescriptor;
this.pollPauseMillis = pollPauseMillis;
} |
1ef6bc66-eed7-4909-9a51-b5f3671cc5c9 | @Override
public void run() {
try {
doListen();
} catch (Exception e) {
LOGGER.error("VM listener error", e);
}
} |
bc3d6379-4615-44e2-a0db-d435a15a2207 | private void doListen() {
LOGGER.info("VM listener is running for VM with PID=[{}]...", vmDescriptor.id());
withZkVm(vmDescriptor, vm -> withJmxConnector(vm, con -> withMBeanServerConnection(con, mbsc -> {
MetricsCollection.withMetrics(mc -> {
synchronized (shutdownLock) {
while (!shutdown) {
pollVM(mc, mbsc);
try {
shutdownLock.wait(pollPauseMillis);
} catch (InterruptedException e) {
}
}
}
});
})));
LOGGER.info("VM listener for VM with PID=[{}] was stopped", vmDescriptor.id());
} |
2840bf97-e1b3-4338-9a58-82d2d1f7c457 | public void shutdown() {
synchronized (shutdownLock) {
shutdown = true;
shutdownLock.notifyAll();
}
} |
6ba4deb4-6512-4640-9fe1-8fc51f9808c4 | private void pollVM(MetricsCollection mc, MBeanServerConnection con) {
JvmMetricsCollector.collectMetrics(getMetricsPrefix(con), con, mc);
ZkMetricsCollector.collectMetrics(getMetricsPrefix(con), con, mc);
} |
21a56718-05d1-403d-8a1e-8c558c163927 | private String getMetricsPrefix(MBeanServerConnection con) {
if (prefix != null) {
return prefix;
}
String hostname = getLocalHostName();
Optional<String> standaloneZkPort = tryResolveStandaloneZKPort(con);
if (standaloneZkPort.isPresent()) {
prefix = "one_min." + hostname + ".zookeeper." + standaloneZkPort.get();
} else {
prefix = "one_min." + hostname + ".zookeeper." + vmDescriptor.id();
}
return prefix;
} |
ec06d928-51d5-4fff-ba3b-ab154c2334d5 | private Optional<String> tryResolveStandaloneZKPort(MBeanServerConnection con) {
Set<ObjectName> zkServerBeanNames = queryNames(con, "org.apache.ZooKeeperService:name0=StandaloneServer_port*",
Query.isInstanceOf(Query.value("org.apache.zookeeper.server.ZooKeeperServerBean")));
if (zkServerBeanNames.isEmpty()) {
return Optional.empty();
}
ObjectName name = zkServerBeanNames.iterator().next();
Map<String, Object> attributes = getBeanAttributes(con, name, "ClientPort");
if(!attributes.containsKey("ClientPort") || attributes.get("ClientPort") == null
|| ((String) attributes.get("ClientPort")).trim().isEmpty())
{
return Optional.empty();
}
return Optional.of(((String) attributes.get("ClientPort")).replaceAll("\\s", "").replace(".", "_").replace(":", "_"));
} |
c6215d69-77b8-4d10-ac3c-7f5a0ab01d94 | private String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
} |
e72096ca-4507-46c5-a753-f7f1e64c6228 | private JmxConnectionProvider() {
} |
7255616d-88b9-45d1-a040-22559734679a | public static void withJmxConnector(VirtualMachine virtualMachine, Function1V<JMXConnector> handler) {
String connectionAddress = prepareConnectionAddress(virtualMachine);
JMXServiceURL jmxServiceURL = prepareJMXServiceURLUnchecked(connectionAddress);
URLClassLoader classLoader = buildTargetLocalVmClassloader(virtualMachine);
try {
JMXConnector jmxConnector = connectToJMXUnchecked(jmxServiceURL, classLoader);
try {
JmxConnectionNotificationListener jmxConnectionNotificationListener = new JmxConnectionNotificationListener();
jmxConnector.addConnectionNotificationListener(jmxConnectionNotificationListener, null, null);
try {
handler.apply(jmxConnector);
} finally {
safeRemoveConnectionNotificationListener(jmxConnector, jmxConnectionNotificationListener);
}
} finally {
safeCloseJMXConnection(jmxConnector);
}
} finally {
safeCloseURLClassloader(classLoader);
}
} |
90041b0f-f8c4-4fcb-aece-d09956549655 | private static String prepareConnectionAddress(VirtualMachine virtualMachine) {
String connectorAddress = getAgentPropertiesUnchecked(virtualMachine).getProperty(CONNECTOR_ADDRESS);
if (connectorAddress != null) {
return connectorAddress;
}
String javaHome = getSystemPropertiesUnchecked(virtualMachine).getProperty("java.home");
String agentPath = javaHome + File.separator + "lib" + File.separator + "management-agent.jar";
loadAgentUnchecked(virtualMachine, agentPath);
return getAgentPropertiesUnchecked(virtualMachine).getProperty(CONNECTOR_ADDRESS);
} |
70ce78a0-dda6-442c-a26a-0b73c40921e3 | private static Properties getAgentPropertiesUnchecked(VirtualMachine virtualMachine) {
try {
return virtualMachine.getAgentProperties();
} catch (IOException e) {
throw new RuntimeException(e);
}
} |
58f2ae3f-a20a-47cf-b877-0bb55c5c1742 | private static Properties getSystemPropertiesUnchecked(VirtualMachine virtualMachine) {
try {
return virtualMachine.getSystemProperties();
} catch (IOException e) {
throw new RuntimeException(e);
}
} |
faeffc44-038e-4b65-92a3-19255f0d7a39 | private static void loadAgentUnchecked(VirtualMachine virtualMachine, String agentPath) {
try {
LOGGER.info("Loading management agent from [{}] for JVM with PID=[{}]...", agentPath, virtualMachine.id());
virtualMachine.loadAgent(agentPath);
LOGGER.info("Loaded management agent from [{}] for JVM with PID=[{}]", agentPath, virtualMachine.id());
} catch (AgentLoadException | AgentInitializationException | IOException e) {
throw new RuntimeException(e);
}
} |
5bd6fbfe-e56c-48f4-ac94-ae43e9b1cf9d | private static JMXServiceURL prepareJMXServiceURLUnchecked(String connectionAddress) {
try {
return new JMXServiceURL(connectionAddress);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
} |
6fe8c059-8bb6-4959-89ce-a7b0baa70185 | private static JMXConnector connectToJMXUnchecked(JMXServiceURL jmxServiceURL, ClassLoader classLoader) {
try {
LOGGER.info("Establishing JMX connection to [{}]...", jmxServiceURL.toString());
Map<String, Object> environment = new HashMap<>();
environment.put(JMXConnectorFactory.DEFAULT_CLASS_LOADER, classLoader);
JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL, environment);
String connectionId = safeGetJmxConnectionId(jmxConnector).orElse("<Undefined>");
LOGGER.info("Established JMX connection to [{}] with id [{}]", jmxServiceURL.toString(), connectionId);
return jmxConnector;
} catch (IOException e) {
throw new RuntimeException(e);
}
} |
9c1cb287-beb5-4ce6-9e8d-2ba165a6aaaa | private static void safeCloseJMXConnection(JMXConnector jmxConnector) {
try {
String connectionId = safeGetJmxConnectionId(jmxConnector).orElse("<Undefined>");
LOGGER.info("Closing JMX connection [{}]...", connectionId);
jmxConnector.close();
LOGGER.info("Closed JMX connection [{}]", connectionId);
} catch (Exception e) {
LOGGER.error("JMX connection close error", e);
}
} |
158d808c-42bd-4651-af38-bf006b3e814a | private static Optional<String> safeGetJmxConnectionId(JMXConnector jmxConnector) {
try {
return Optional.ofNullable(jmxConnector.getConnectionId());
} catch (IOException e) {
return Optional.empty();
}
} |
491beaf6-82d7-45f4-abf4-7e0b6465ddfc | private static void safeRemoveConnectionNotificationListener(JMXConnector jmxConnector,
JmxConnectionNotificationListener jmxConnectionNotificationListener)
{
try {
jmxConnector.removeConnectionNotificationListener(jmxConnectionNotificationListener, null, null);
} catch (Exception e) {
LOGGER.error("Error removing connection notification listener", e);
}
} |
0e148e06-b24b-4c3b-bd47-0a832fd6a0a1 | @Override
public void handleNotification(Notification notification, Object handback) {
LOGGER.info("JMX connection notification received: {}", notification.toString());
} |
a74dbe35-44e8-42f6-8cdc-e53624c81fe8 | private static URLClassLoader buildTargetLocalVmClassloader(VirtualMachine virtualMachine) {
LOGGER.info("Creating class loader for JVM with PID=[{}]...", virtualMachine.id());
ClassLoader defaultClassLoader = Thread.currentThread().getContextClassLoader();
List<String> classpath = getVmClasspath(virtualMachine);
List<URL> classloaderURLs = classpath.stream().flatMap(e -> resolveClasspathEntry(e).stream())
.distinct().collect(Collectors.toList());
URL[] classloaderURLsArray = new URL[classloaderURLs.size()];
classloaderURLs.toArray(classloaderURLsArray);
URLClassLoader result = new URLClassLoader(classloaderURLsArray, defaultClassLoader);
LOGGER.info("Class loader for JVM with PID=[{}] created, using URLs [{}]", virtualMachine.id(),
Arrays.stream(result.getURLs()).map(URL::toExternalForm).collect(Collectors.joining(", ")));
return result;
} |
b1d94426-44c0-40cd-8591-ede3617e7b2c | private static List<String> getVmClasspath(VirtualMachine virtualMachine) {
Properties targetVmSystemProperties = getSystemPropertiesUnchecked(virtualMachine);
String classpathSeparator = targetVmSystemProperties.getProperty("path.separator");
String classpath = targetVmSystemProperties.getProperty("java.class.path");
String[] splittedClasspath = classpath.split(Pattern.quote(classpathSeparator));
return Arrays.stream(splittedClasspath).filter(e -> !e.isEmpty()).collect(Collectors.toList());
} |
1363a4f1-cb92-4f39-9a33-8ab2e319df80 | private static List<URL> resolveClasspathEntry(String entry) {
if (entry.toLowerCase().endsWith("*.jar") || entry.endsWith("*")) {
return resolveWildcardClasspathEntry(entry);
}
File entryFile = new File(entry);
if (!entryFile.exists()) {
return new ArrayList<>();
}
List<URL> result = new ArrayList<>();
result.add(toURL(entryFile));
return result;
} |
e7e91fca-d32c-4032-86d7-1299833cd685 | private static List<URL> resolveWildcardClasspathEntry(String entry) {
String dirPath;
if (entry.toLowerCase().endsWith("*.jar")) {
dirPath = entry.substring(0, entry.length() - 5);
} else {
dirPath = entry.substring(0, entry.length() - 1);
}
File dir = new File(dirPath);
if (!dir.exists() || !dir.isDirectory()) {
return new ArrayList<>();
}
return Arrays.stream(dir.list((f, n) -> f.isFile() && n.toLowerCase().endsWith(".jar")))
.map(n -> toURL(new File(dir, n))).collect(Collectors.toList());
} |
b23eb59c-a3c3-4fdd-b0fa-a38618a3d544 | private static URL toURL(File file) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
} |
d618130f-7185-488b-91c2-25f5bba65f85 | private static void safeCloseURLClassloader(URLClassLoader urlClassLoader) {
try {
LOGGER.info("Closing URL class loader...");
urlClassLoader.close();
LOGGER.info("Closed URL class loader");
} catch (IOException e) {
LOGGER.error("Error closing class loader", e);
}
} |
7d98de5e-768e-4f4a-aa02-7d4ac24cddb7 | public static List<VirtualMachineDescriptor> getZkVmDescriptors() {
return VirtualMachine.list().stream()
.filter(d -> d.displayName().startsWith(ZK_MAIN))
.collect(Collectors.toList());
} |
0e60434f-89e0-4b4f-ba05-77c4f6a21a84 | public static void withZkVm(VirtualMachineDescriptor descriptor, Function1V<VirtualMachine> handler) {
VirtualMachine vm = uncheckedAttach(descriptor);
try {
handler.apply(vm);
} finally {
safeDetach(vm);
}
} |
0f30f0ca-3770-4344-9d53-e6b8f0faf45d | private static VirtualMachine uncheckedAttach(VirtualMachineDescriptor descriptor) {
try {
LOGGER.info("Attaching to {} JVM with PID = [{}]...", descriptor.displayName(), descriptor.id());
VirtualMachine vm = VirtualMachine.attach(descriptor);
LOGGER.info("Attached to {} JVM with PID = [{}]", descriptor.displayName(), descriptor.id());
return vm;
} catch (AttachNotSupportedException | IOException e) {
throw new RuntimeException(e);
}
} |
f01ff47b-efe8-4102-be58-4133858702aa | private static void safeDetach(VirtualMachine virtualMachine) {
try {
LOGGER.info("Detaching from JVM with PID = [{}]...", virtualMachine.id());
virtualMachine.detach();
LOGGER.info("Detached from JVM with PID = [{}]", virtualMachine.id());
} catch (Exception e) {
LOGGER.error("JVM detach error", e);
}
} |
257a1637-3615-45f3-92a0-192c9ac35452 | public static Map<String, Object> getBeanAttributes(MBeanServerConnection con, ObjectName beanName,
String... requestedAtributes)
{
Set<String> attributes = findReadableAttributes(con, beanName);
String[] attributesToQuery = collectAttributesToQuery(attributes, requestedAtributes);
try {
AttributeList receivedAttributes = con.getAttributes(beanName, attributesToQuery);
Map<String, Object> result = new HashMap<>();
receivedAttributes.asList().forEach(a -> result.put(a.getName(), a.getValue()));
return result;
} catch (InstanceNotFoundException | ReflectionException | IOException e) {
throw new RuntimeException(e);
}
} |
9a801dfb-1e6b-411e-a068-735a5a14d23e | public static Set<ObjectName> queryNames(MBeanServerConnection con, String name, QueryExp query) {
try {
return con.queryNames(buildObjectName(name), query);
} catch (IOException e) {
throw new RuntimeException(e);
}
} |
6b148c8e-76cb-47d6-9584-90da5628e580 | private static Set<String> findReadableAttributes(MBeanServerConnection con, ObjectName beanName) {
try {
MBeanInfo info = con.getMBeanInfo(beanName);
return Arrays.asList(info.getAttributes()).stream()
.filter(MBeanAttributeInfo::isReadable).map(MBeanFeatureInfo::getName)
.collect(Collectors.toSet());
} catch (InstanceNotFoundException | IntrospectionException | ReflectionException | IOException e) {
throw new RuntimeException(e);
}
} |
f04983ee-c609-4e70-a6a1-6d65dab6d570 | private static String[] collectAttributesToQuery(Set<String> existingAttributes, String... requestedAtributes) {
Set<String> attributesToQuery = new HashSet<>();
for (String attribute : requestedAtributes) {
if (existingAttributes.contains(attribute)) {
attributesToQuery.add(attribute);
}
}
String[] result = new String[attributesToQuery.size()];
return attributesToQuery.toArray(result);
} |
db6313ab-b7b5-424e-9f66-7ce0dbfc3a68 | private static ObjectName buildObjectName(String name) {
try {
return new ObjectName(name);
} catch (MalformedObjectNameException e) {
throw new RuntimeException(e);
}
} |
8068edd8-5643-455a-9be6-146d566c926e | public ZkVmWatcher(long vmPollPauseMillis, long vmListPollPauseMillis) {
this.vmPollPauseMillis = vmPollPauseMillis;
this.vmListPollPauseMillis = vmListPollPauseMillis;
} |
a4353840-9d07-4b3c-a1ca-fda4f18da8f3 | @Override
public void run() {
try {
doWatch();
} catch (Exception e) {
LOGGER.error("VM watcher error", e);
}
} |
0396910b-42ec-4a8d-84bb-aab7afed9ee5 | private void doWatch() {
LOGGER.info("VM watcher is running...");
synchronized (shutdownLock) {
while (!shutdown) {
Set<VirtualMachineDescriptor> machines = new HashSet<>(ZkVmProvider.getZkVmDescriptors());
machines.forEach(m -> {
if (!watchedVMs.contains(m)) {
watchVm(m);
}
});
watchedVMs.forEach(m -> {
if (!machines.contains(m)) {
unwatchVM(m);
}
});
watchedVMs.forEach(m -> {
if (!watchedVmListenerThreads.get(m).isAlive()) {
unwatchVM(m);
}
});
try {
shutdownLock.wait(vmListPollPauseMillis);
} catch (InterruptedException e) {
}
}
watchedVMs.forEach(this::unwatchVM);
}
LOGGER.info("VM watcher was stopped");
} |
ea83a248-5b7c-4eb6-afdf-f424343635ab | private void watchVm(VirtualMachineDescriptor m) {
ZkVmListener listener = new ZkVmListener(m, vmPollPauseMillis);
Thread listenerThread = new Thread(listener);
listenerThread.setDaemon(true);
listenerThread.start();
watchedVMs.add(m);
watchedVmListeners.put(m, listener);
watchedVmListenerThreads.put(m, listenerThread);
LOGGER.info("Watching VM with PID=[{}]", m.id());
} |
63ee0223-fc59-4a26-9ffe-2d8639bdb74c | private void unwatchVM(VirtualMachineDescriptor m) {
watchedVmListeners.get(m).shutdown();
try {
watchedVmListenerThreads.get(m).join(100);
} catch (InterruptedException e) {
}
watchedVmListeners.remove(m);
watchedVmListenerThreads.remove(m);
watchedVMs.remove(m);
LOGGER.info("No longer watching VM with PID=[{}]", m.id());
} |
d4ffb550-13f1-4553-8d92-17a17aa65ab0 | public void shutdown() {
synchronized (shutdownLock) {
shutdown = true;
shutdownLock.notifyAll();
}
} |
4531b212-9c27-474a-80c4-e3fea95f802a | void apply(); |
651ae8cb-180e-41de-8ec3-61cbc7aa6f77 | void apply(T arg); |
807c235d-46f1-4547-ac19-db09dec277c7 | public static boolean isInt(Node t) {
String name = t.type.name;
return (name.equals("int"));
} |
d468f473-2257-4d9c-93a1-40006c7c2879 | public static boolean isStrInt(Node t) {
String name = t.type.name;
return ((name.equals("int") || name.equals("string")));
} |
9432c316-26ba-4a49-9cca-caaef76a980f | public static boolean isStr(Node t) {
String name = t.type.name;
return (name.equals("string"));
} |
248e5673-31f6-4462-815e-7df067f7fd38 | public static boolean isChar(Node t) {
String name = t.type.name;
return (name.equals("char"));
} |
2d86d5ce-6036-448b-9acb-1d95592fbc0d | public Parser(boolean doSemanticChecks) {
this.doSemanticChecks = doSemanticChecks;
} |
629e9404-4427-4449-b873-250b5047af9d | public Parser() {
this(true);
} |
7294b9bf-8805-48ce-ae06-120848c792ab | public void parse(String sourceFilename) throws ParserException {
parseTreeBuffer = new StringBuilder();
recursionDepth = 1; // to match test cases, should really be 0
errors = new ArrayList<String>();
scanner = new Scanner(sourceFilename);
scanner.next();
symbolTable = new SymbolTable();
program();
} |
35e33d58-8ae4-4714-916c-eefe5e42859f | private void enterRule(NonTerminal nt) throws ParserException {
if (! have(nt)) printError(nt);
StringBuilder lineData = new StringBuilder();
for (int i = 0; i < recursionDepth; i++) lineData.append(" ");
lineData.append(nt.name);
parseTreeBuffer.append(lineData).append("\n");
recursionDepth++;
} |
08a87ea2-c00c-4f57-b5d6-b39a0f462b92 | private void exitRule(NonTerminal nt) {
recursionDepth--;
} |
727f9f0e-0531-4369-abe1-375b78222fb8 | public String getParseTree() {
return parseTreeBuffer.toString();
} |
adf620be-eece-4aa6-b673-19add203cda3 | private void addTestCaseErrorMessage() {
// For comparing output: please use this format as it will be used to compare output results.
if (doSemanticChecks) {
StringBuilder errorMessage = new StringBuilder();
if (scanner.getTokenKind() == TokenKind.ERROR) {
errorMessage.append("Syntax Error (Scanner): SCAN_ERROR on symbol " + scanner.getLexeme());
} else {
errorMessage.append("Syntax Error (Parser): on symbol " + scanner.getLexeme());
}
errorMessage.append("\n");
errorMessage.append("Error Found on Line Number: ").append(scanner.getLineNum()).append("\n");
errorMessage.append(symbolTable);
errors.add(errorMessage.toString());
} else {
errors.add("Error: " + scanner.getTokenKind() + " " + scanner.getLexeme());
}
} |
40c40246-7354-4f62-baaf-d81da234596a | private void printError(TokenKind expectedToken) throws ParserException {
addTestCaseErrorMessage();
String errorMessage = "Error: found " + scanner.getTokenKind() + " (" + scanner.getLexeme() + ")"
+ " but expected: " + expectedToken;
throw new ParserException(scanner.getLineNum(), scanner.getCharPos(), errorMessage);
} |
e831d01c-df8a-4e28-951e-c57a615e0aed | private void printError(NonTerminal nt) throws ParserException {
addTestCaseErrorMessage();
String errorMessage = "Error: found " + scanner.getTokenKind() + " (" + scanner.getLexeme() + ")"
+ " but expected: " + nt + " with " + nt.firstSet;
throw new ParserException(scanner.getLineNum(), scanner.getCharPos(), errorMessage);
} |
122e0bdc-de67-40ed-b6db-718d3b7f8982 | private void printError(ErrorType errorType, Token nameToken) throws ParserException {
String errorMessage = "SEMANTIC ERROR: " + errorType + " on symbol " + nameToken.getLexeme();
StringBuilder outputError = new StringBuilder();
outputError.append(errorMessage).append("\n");
outputError.append("Error Found on Line Number: " + nameToken.getLineNum()).append("\n");
outputError.append(symbolTable);
errors.add(outputError.toString());
throw new ParserException(nameToken.getLineNum(), nameToken.getCharPos(), errorMessage);
} |
fb667db6-a314-49c3-84c2-3edeb868e6ac | private void printError(ErrorType errorType, Token nameToken, String message) throws ParserException {
String errorMessage = "SEMANTIC ERROR: " + errorType + " on symbol " + nameToken.getLexeme();
StringBuilder outputError = new StringBuilder();
outputError.append(errorMessage).append("\n");
outputError.append("Error Found on Line Number: " +
nameToken.getLineNum()).append(", Char Position: " + nameToken.getCharPos()).append("\n");
if (message != null) outputError.append(message).append("\n");
outputError.append(symbolTable);
errors.add(outputError.toString());
throw new ParserException(scanner.getLineNum(), scanner.getCharPos(), errorMessage);
} |
117526f5-5cb5-49a6-a8a1-f2fc5ab3547b | public void prntMismatchInvRef(Token t, Type baseType, Node type) throws ParserException {
printError(ErrorType.MISMATCH_ERROR, t, ERR_MISMATCH_INVALID_REF + "base = " +
baseType + ", index = " + type.type.name);
} |
bfd1244d-ac8f-4fbe-954b-141483c19035 | public void prntMismatchInvOp(Token operator, Node t1, Node t2) throws ParserException {
printError(ErrorType.MISMATCH_ERROR, operator, ERR_MISMATCH_INVALID_OP + operator.getLexeme()
+ ", " + t1.type.toString()+", " + t2.type.toString());
} |
2ddd6ee2-d0d7-4f4a-a8f0-fbd8d25dca55 | public void prntMismatchInvArg(Token functToken, Token t, Symbol s) throws ParserException {
printError(ErrorType.MISMATCH_ERROR, functToken,
ERR_MISMATCH_INVALID_ARG + t.getLexeme() + ", "+ s.getType().toString());
} |
37bed5d1-7136-4822-bf74-2be5fab9b34f | public void prntMismatchInvArg(Token functToken, Token ident, Type t) throws ParserException {
printError(ErrorType.MISMATCH_ERROR, functToken,
ERR_MISMATCH_INVALID_ARG + ident.getLexeme() + ", "+ t.toString());
} |
90b8598b-83c6-432c-a5d1-b1b3091d588a | public void prntMismatchInvCall(Token functTok, Symbol decSym, List<Node> types) throws ParserException {
printError(ErrorType.MISMATCH_ERROR, functTok, ERR_MISMATCH_INVALID_CALL +
functTok.getLexeme() + decParams(decSym.params) + " with " + callParams(types));
} |
5a2ff696-9cac-4bac-b664-f756d95bf0fa | public void prntArtyInvCall(Token functTok, Symbol decSym, List<Node> types) throws ParserException {
printError(ErrorType.ARITY_ERROR, functTok, ERR_MISMATCH_INVALID_CALL +
functTok.getLexeme() + decParams(decSym.params) + " with " + callParams(types));
} |
57faef8a-2f58-491f-a82c-0768928248a2 | public void prntMismatchInvAssign(Token assignTok, Node type1, Node type2) throws ParserException {
printError(ErrorType.MISMATCH_ERROR, assignTok,
ERR_MISMATCH_INVALID_ASSIGN + type1.type + " <- " + type2.type);
} |
aedac2e2-86d2-4f66-9036-6f7e03be14a3 | public void prntMismatchInvRetVoid(Token ret, Node t) throws ParserException {
printError(ErrorType.MISMATCH_ERROR, ret, ERR_MISMATCH_INVALID_RET
+ "expected = " + "void" + ", received = " + t.type.toString());
} |
a70f0499-cc93-40be-800a-c59813cb48d4 | public void prntMismatchInvRet(Token ret, Node t, Symbol function) throws ParserException {
printError(ErrorType.MISMATCH_ERROR, ret, ERR_MISMATCH_INVALID_RET
+ "expected = " + function.type.toString() + ", received = " + t.type.toString());
} |
7b42b03e-e58d-4e85-b9e1-f61a205cb2c5 | public List<String> getErrors() { return errors; } |
2d31f43f-417e-4623-94a5-9c8550908b70 | public SymbolTable getSymbolTable() {
return symbolTable;
} |
f2eadbc0-71b1-493d-ba11-c862011c8a32 | private boolean have(TokenKind tokenKind) {
return scanner.getTokenKind() == tokenKind;
} |
09c9c11a-846a-4816-b952-9d472bf700e8 | private boolean have(NonTerminal nt) {
return nt.firstSet.contains(scanner.getTokenKind());
} |
398b3917-2227-4803-a211-f6e33f5fabc3 | private boolean accept(TokenKind tokenKind) {
if (have(tokenKind)) {
scanner.next();
return true;
}
return false;
} |
8ecfb9ac-a8aa-4a75-a65a-cfa62de2788a | private boolean accept(NonTerminal nt) {
if (have(nt)) {
scanner.next();
return true;
}
return false;
} |
32e90f90-9691-4537-8ec7-010f92b676d8 | private boolean expect(TokenKind tokenKind) throws ParserException {
if (accept(tokenKind)) return true;
printError(tokenKind);
return false;
} |
1cb43094-6377-4a09-9f52-a5be83298469 | private boolean expect(NonTerminal nt) throws ParserException {
if (accept(nt)) return true;
printError(nt);
return false;
} |
c14fd661-b224-4fe7-b892-c752542ba709 | private Token expectRetrieve(TokenKind tokenKind) throws ParserException {
Token res = scanner.getToken();
expect(tokenKind);
return res;
} |
9a6edec8-f0ba-40cd-a744-e4171f526107 | private Token expectRetrieve(NonTerminal nt) throws ParserException {
Token res = scanner.getToken();
expect(nt);
return res;
} |
d5cacaa1-e787-42d4-8635-ee5682c38620 | public void addSymbol(Symbol sym, Token ident) throws ParserException {
if (symbolTable.inCurrentScope(sym))
printError(ErrorType.REDEFINED_ERROR, ident);
symbolTable.addSymbol(sym);
} |
41756984-ac83-48c0-abfd-16808072a25e | private Node selector() throws ParserException {
enterRule(NonTerminal.SELECTOR);
Token t = expectRetrieve(TokenKind.IDENT);
Symbol s = symbolTable.inParentScopes(t.getLexeme(), "selector");
if (s == null) printError(ErrorType.UNDEFINED_ERROR, t);
Type retType = s.getType();
int depth;
if (s.type.isArray) depth = s.type.depth;
else depth = 0;
while (accept(TokenKind.L_BRACKET)) {
Node type = expression();
if (!TypeChecker.isInt(type)) prntMismatchInvRef(t, s.getType().baseType, type);
expect(TokenKind.R_BRACKET);
if (retType == null) prntMismatchInvRef(t, s.getType(), type);
retType = retType.baseType;
depth--;
}
exitRule(NonTerminal.SELECTOR);
return new Node(t, retType);
} |
64ab4ef6-4e26-4751-b8bf-b4ca104c82a0 | private List<Node> parameters(Token functToken) throws ParserException {
enterRule(NonTerminal.PARAMETERS);
List<Node> types = new ArrayList<Node>();
do {
Token t = expectRetrieve(TokenKind.IDENT);
Symbol s = symbolTable.inParentScopes(t.getLexeme(), "selector");
if (s == null)
this.printError(ErrorType.UNDEFINED_ERROR, t);
types.add(new Node(t, s.getType()));
if (s.type.isArray) prntMismatchInvArg(functToken, t, s);
} while (accept(TokenKind.COMMA));
exitRule(NonTerminal.PARAMETERS);
return types;
} |
ed91f10c-86ab-4a66-9a23-f915c5649ca2 | private void condition() throws ParserException {
enterRule(NonTerminal.CONDITION);
expect(TokenKind.L_PAREN);
Node t1 = expression();
Token operator = expectRetrieve(NonTerminal.RELOP);
Node t2 = expression();
if (t1.type.isArray || t2.type.isArray || !t1.type.equals(t2.type))
prntMismatchInvOp(operator, t1, t2);
expect(TokenKind.R_PAREN);
exitRule(NonTerminal.CONDITION);
} |
9b337a84-56d2-4d48-ae90-9be0c9f7f67a | private String decParams(List<Type> params) {
if (params == null) return "()";
String paramStr = "(";
for (Type t : params) paramStr += t.toString() + ", ";
return paramStr.substring(0, paramStr.length() - 2) + ")";
} |
1a5e953d-5e3a-4fbc-9599-db24c877db45 | private String callParams(List<Node> params) {
if (params == null) return "()";
String paramStr = "(";
for (Node t : params) paramStr += t.type.toString() + ", ";
return paramStr.substring(0, paramStr.length() - 2) + ")";
} |
52cefb49-9e9e-44d3-9ac7-b54c5abdba8b | private Node procedureCall() throws ParserException {
enterRule(NonTerminal.PROCEDURE_CALL);
expect(TokenKind.COLON);
expect(TokenKind.COLON);
Token functTok = expectRetrieve(TokenKind.IDENT);
Symbol decSym = symbolTable.inParentScopes(functTok.getLexeme(), "procedure");
if (decSym == null) printError(ErrorType.UNDEFINED_ERROR, functTok);
expect(TokenKind.L_PAREN);
if (have(NonTerminal.PARAMETERS)) {
List<Node> types = parameters(functTok);
if (decSym.params == null && types.size() > 0)
prntMismatchInvCall(functTok, decSym, types);
if (decSym.params != null) {
if (types.size() != decSym.params.size())
prntArtyInvCall(functTok, decSym, types);
for (int i = 0; i < decSym.params.size(); i++) {
if (!decSym.params.get(i).equals(types.get(i).type))
prntMismatchInvCall(functTok, decSym, types);
}
}
}
expect(TokenKind.R_PAREN);
exitRule(NonTerminal.PROCEDURE_CALL);
return new Node(functTok, decSym.getType());
} |
1271feac-97f8-44b8-85c7-9120d161a6a7 | private void assignment() throws ParserException {
enterRule(NonTerminal.ASSIGNMENT);
Node type1 = selector();
Node type2 = null;
Token assignTok = expectRetrieve(TokenKind.ASSIGN);
if (have(NonTerminal.EXPRESSION)) {
type2 = expression();
if (type1.type.isArray || type2.type.isArray) {
prntMismatchInvAssign(assignTok, type1, type2);
}
}
else expect(TokenKind.STRING_LITERAL);
expect(TokenKind.SEMICOLON);
exitRule(NonTerminal.ASSIGNMENT);
} |
4639f8ca-dae0-42f1-b684-dc688172f939 | private void input() throws ParserException {
enterRule(NonTerminal.INPUT);
Token t = expectRetrieve(TokenKind.INPUT);
expect(TokenKind.L_PAREN);
parameters(t);
expect(TokenKind.R_PAREN);
expect(TokenKind.SEMICOLON);
exitRule(NonTerminal.INPUT);
} |
9d1aefcb-a5c0-440e-8fe0-4655f885775c | private void output() throws ParserException {
enterRule(NonTerminal.OUTPUT);
Token t = expectRetrieve(TokenKind.PRINT);
expect(TokenKind.L_PAREN);
parameters(t);
expect(TokenKind.R_PAREN);
expect(TokenKind.SEMICOLON);
exitRule(NonTerminal.OUTPUT);
} |
cdb2d0f7-883d-460c-807f-c14a77ad81d4 | private void ifStatement() throws ParserException {
enterRule(NonTerminal.IF_STATEMENT);
expect(TokenKind.IF);
condition();
expect(TokenKind.L_BRACE);
statementSequence(null);
expect(TokenKind.R_BRACE);
if (accept(TokenKind.ELSE)) {
expect(TokenKind.L_BRACE);
statementSequence(null);
expect(TokenKind.R_BRACE);
}
exitRule(NonTerminal.IF_STATEMENT);
} |
01a286e0-5136-4f40-a027-b7993a862584 | private void whileStatement() throws ParserException {
enterRule(NonTerminal.WHILE_STATEMENT);
expect(TokenKind.WHILE);
condition();
expect(TokenKind.L_BRACE);
statementSequence(null);
expect(TokenKind.R_BRACE);
exitRule(NonTerminal.WHILE_STATEMENT);
} |
e02e07fa-6fd8-4f94-ac95-8e1b5431d383 | private void returnStatement(Symbol function) throws ParserException {
enterRule(NonTerminal.RETURN_STATEMENT);
Token ret = expectRetrieve(TokenKind.RETURN);
Node t = expression();
if (function == null) prntMismatchInvRetVoid(ret, t);
if (function.type.name.equals("void") || !function.type.toString().equals(t.type.toString()))
prntMismatchInvRet(ret, t, function);
expect(TokenKind.SEMICOLON);
exitRule(NonTerminal.RETURN_STATEMENT);
} |
d8f777b4-3065-41ad-b058-ba6ee83c6d8d | private void procedureStatement() throws ParserException {
enterRule(NonTerminal.PROCEDURE_STATEMENT);
procedureCall();
expect(TokenKind.SEMICOLON);
exitRule(NonTerminal.PROCEDURE_STATEMENT);
} |
04a4e5fb-fc11-46e2-b997-64ba43cc1876 | private void statement(Symbol function) throws ParserException {
enterRule(NonTerminal.STATEMENT);
if (have(NonTerminal.ASSIGNMENT)) assignment();
else if (have(NonTerminal.INPUT)) input();
else if (have(NonTerminal.OUTPUT)) output();
else if (have(NonTerminal.IF_STATEMENT)) ifStatement();
else if (have(NonTerminal.WHILE_STATEMENT)) whileStatement();
else if (have(NonTerminal.RETURN_STATEMENT)) returnStatement(function);
else if (have(NonTerminal.PROCEDURE_STATEMENT)) procedureStatement();
else expect(NonTerminal.STATEMENT);
exitRule(NonTerminal.STATEMENT);
} |
2baa41f7-587e-4173-9d9f-0ec82554d02d | private void statementSequence(Symbol function) throws ParserException {
enterRule(NonTerminal.STATEMENT_SEQUENCE);
do {
statement(function);
} while (have(NonTerminal.STATEMENT));
exitRule(NonTerminal.STATEMENT_SEQUENCE);
} |
6111b9f9-efaf-40dc-9322-2c3b37c8c3df | private Node factor() throws ParserException {
enterRule(NonTerminal.FACTOR);
Node t = null;
if (have(NonTerminal.SELECTOR))
t = selector();
else if (have(TokenKind.NUMBER)) {
Token tok = expectRetrieve(TokenKind.NUMBER);
t = new Node(tok, Type.newPrimitiveType("int"));
}
else if (have(NonTerminal.PROCEDURE_CALL))
t = procedureCall();
else if (accept(TokenKind.L_PAREN)) {
t = expression();
expect(TokenKind.R_PAREN);
} else expect(NonTerminal.FACTOR);
exitRule(NonTerminal.FACTOR);
return t;
} |
19cd14b3-fa88-4c4e-81a1-dd376f1333f1 | private Node term() throws ParserException {
enterRule(NonTerminal.TERM);
Node t1 = factor();
Node t2 = null;
while (have(NonTerminal.OP1)) {
if (t2 != null) t1 = t2;
Token op = expectRetrieve(NonTerminal.OP1);
t2 = factor();
if(!TypeChecker.isInt(t1)) prntMismatchInvOp(op, t1, t2);
// The two must have the same type :)
if (!t1.type.equals(t2.type)) prntMismatchInvOp(op, t1, t2);
}
exitRule(NonTerminal.TERM);
return t1;
} |
92e14a76-1647-4b61-a307-3681873392f1 | private Node expression() throws ParserException {
enterRule(NonTerminal.EXPRESSION);
Node t1 = term();
Node t2 = null;
boolean strung = false;
while (have(TokenKind.ADD) || have(TokenKind.SUB)) {
if (t2 != null) t1 = t2;
if (have(TokenKind.ADD)) {
Token op = expectRetrieve(TokenKind.ADD);
t2 = term();
// Strings plug anything besides arrays become strings!!
if ((TypeChecker.isStr(t1) || TypeChecker.isStr(t2)))
strung = true;
if ((TypeChecker.isStr(t1) && !t2.type.isArray) ||
(TypeChecker.isStr(t2) && !t1.type.isArray)); // Do nothing
else if (!t1.type.equals(t2.type) && TypeChecker.isInt(t1) &&
TypeChecker.isInt(t2)) prntMismatchInvOp(op, t1, t2);
}
else if (have(TokenKind.SUB)) {
Token op = expectRetrieve(TokenKind.SUB);
t2 = term();
if(!TypeChecker.isInt(t1)) prntMismatchInvOp(op, t1, t2);
if (!t1.type.equals(t2.type)) prntMismatchInvOp(op, t1, t2);
}
}
exitRule(NonTerminal.EXPRESSION);
if (strung)
t1.type = Type.newPrimitiveType("string");
return t1;
} |
bd6ea7ec-102f-4339-9ca9-42c944512cd9 | private Type retType() throws ParserException {
enterRule(NonTerminal.RET_TYPE);
Token t = expectRetrieve(NonTerminal.RET_TYPE);
exitRule(NonTerminal.RET_TYPE);
return Type.newPrimitiveType(t.getLexeme());
} |
798dcebc-c8f4-4468-a0ce-1425d4dabf36 | private Type type() throws ParserException {
enterRule(NonTerminal.TYPE);
String name = scanner.getLexeme();
if (accept(TokenKind.INT)) {}
else if (accept(TokenKind.CHAR)) {}
else if (accept(TokenKind.STRING)) {}
else if (accept(TokenKind.ARRAY)) {
int dim = Integer.parseInt(scanner.getLexeme());
expect(TokenKind.NUMBER);
expect(TokenKind.OF);
Type t = type();
exitRule(NonTerminal.TYPE);
return Type.newArrayType(t, dim);
}
exitRule(NonTerminal.TYPE);
return Type.newPrimitiveType(name);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.