public void visitFunctionDeclaration(FunctionDeclarationContext function) { symbolTable.newScope(); Function f = buildFunction(function); returnType = f.getReturnValueType(); f.getArguments().stream().forEach(symbolTable::defineVariable); Type[] argTypes = f.getArguments() .stream() .flatMap(variable -> Stream.of(variable.getValueType().toAsmType())) .toArray(Type[]::new); String descriptor = Type.getMethodDescriptor(f.getReturnValueType().toAsmType(), argTypes); if ("main".equals(f.getName())) { if (!f.getArguments().isEmpty()) { throw new GenerationException("Main function must have zero arguments"); } descriptor = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String[].class)); } method = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, f.getName(), descriptor, null, null); BlockContext block = function.functionBody().block(); visitBlock(block); checkReturn(block); method.visitMaxs(0, 0); method.visitEnd(); symbolTable.dropScope(); }
@Test(expected = TypeException.class) public void testTypeCheckingVisitorWordCountMissingEmitIndex() throws IOException, ParseException { final String source = "out: table sum[key: string][month: int][day: int] of int;\nstatic keywords: array of string = { \"hitchhiker\", \"benedict\", \"vytorin\", \"itanium\", \"aardvark\" };\nquerywords: array of string = words_from_query();\nmonth: int = month_of_query();\nday: int = day_of_query();\nwhen (i: each int; j: some int; querywords[i] == keywords[j])\n emit out <- 1;\n"; final SymbolTable st = new SymbolTable(); // fake functions for this unit test st.setFunction( "day_of_query", new SizzleFunction(new SizzleInt(), new SizzleType[] {}, "Nonexistant.day_of_query()")); st.setFunction( "month_of_query", new SizzleFunction(new SizzleInt(), new SizzleType[] {}, "Nonexistant.month_of_query()")); st.setFunction( "words_from_query", new SizzleFunction( new SizzleArray(new SizzleString()), new SizzleType[] {}, "Nonexistant.words_from_query()")); SizzleParser.ReInit(new StringReader(source)); TestTypeCheckingVisitor.typeChecker.visit(SizzleParser.Start(), st); }
/* */ public void translate(ClassGenerator classGen, MethodGenerator methodGen) /* */ { /* 88 */ ConstantPoolGen cpg = classGen.getConstantPool(); /* 89 */ InstructionList il = methodGen.getInstructionList(); /* 90 */ SymbolTable symbolTable = getParser().getSymbolTable(); /* */ /* 93 */ for (int i = 0; i < this._sets.size(); i++) /* */ { /* 95 */ QName name = (QName) this._sets.elementAt(i); /* */ /* 97 */ AttributeSet attrs = symbolTable.lookupAttributeSet(name); /* */ /* 99 */ if (attrs != null) { /* 100 */ String methodName = attrs.getMethodName(); /* 101 */ il.append(classGen.loadTranslet()); /* 102 */ il.append(methodGen.loadDOM()); /* 103 */ il.append(methodGen.loadIterator()); /* 104 */ il.append(methodGen.loadHandler()); /* 105 */ il.append(methodGen.loadCurrentNode()); /* 106 */ int method = cpg.addMethodref( classGen.getClassName(), methodName, "(Lcom/sun/org/apache/xalan/internal/xsltc/DOM;Lcom/sun/org/apache/xml/internal/dtm/DTMAxisIterator;Lcom/sun/org/apache/xml/internal/serializer/SerializationHandler;I)V"); /* */ /* 108 */ il.append(new INVOKESPECIAL(method)); /* */ } /* */ else /* */ { /* 112 */ Parser parser = getParser(); /* 113 */ String atrs = name.toString(); /* 114 */ reportError(this, parser, "ATTRIBSET_UNDEF_ERR", atrs); /* */ } /* */ } /* */ }
@Test public void testTypeCheckingVisitorQueryLog() throws IOException, ParseException { final String source = "proto \"querylog.proto\"\n\nqueries_per_degree: table sum[lat: int][lon: int] of int;\n\nlog_record: QueryLogProto = input;\nloc: Location = locationinfo(log_record.ip);\nemit queries_per_degree[int(loc.lat)][int(loc.lon)] <- 1;\n"; final SymbolTable st = new SymbolTable(new SizzleBytes()); SizzleParser.ReInit(new StringReader(source)); TestTypeCheckingVisitor.typeChecker.visit(SizzleParser.Start(), st); Assert.assertEquals( "queries_per_degree is not an unweighted table of ints indexed by ints", new SizzleTable( new SizzleInt(), Arrays.asList(new SizzleScalar[] {new SizzleInt(), new SizzleInt()}), null), st.get("queries_per_degree")); final List<SizzleType> lmembers = new ArrayList<SizzleType>(Arrays.asList(new SizzleFloat(), new SizzleFloat())); Assert.assertEquals("loc is not a Location", new SizzleTuple(lmembers), st.get("loc")); final List<SizzleType> qlpmembers = new ArrayList<SizzleType>(Arrays.asList(new SizzleString(), new SizzleInt())); Assert.assertEquals( "log_record is not a QueryLogProto", new SizzleTuple(qlpmembers), st.get("log_record")); }
/** * Loads a theory into the given symbol table. * * @param theoryName the theory to load * @param symTable the symbol table into which to put the theory * @return null if OK, otherwise an error as a IResponse */ public /* @Nullable */ IResponse loadTheory(String theoryName, SymbolTable symTable) { ITheory th = null; try { th = findTheory(theoryName, smtConfig.logicPath); } catch (SMTLIBException e) { return e.errorResponse; } // The second element should be the name of the logic, if specified if (theoryName != null && !theoryName.equals(th.theoryName().value())) { return smtConfig.responseFactory.error( "Definition of logic " + theoryName + " is mal-formed (internal name does not match file name): " + th.theoryName().value(), th.theoryName().pos()); } if (smtConfig.verbose != 0) { smtConfig.log.logDiag("#Installing theory " + theoryName); } /* @Nullable */ IResponse response = loadTheory(th, symTable); if (response == null) { if (theoryName.equals("ArraysEx")) symTable.arrayTheorySet = true; if (theoryName.equals("Fixed_Size_BitVectors")) symTable.bitVectorTheorySet = true; if (theoryName.equals("Reals_Ints")) symTable.realsIntsTheorySet = true; } return response; }
@Test public void testTypeCheckingRobustQueryLogFixed() throws IOException, ParseException { final String source = "proto \"querylog.proto\"\n static MINUTE: float = 0.0; static RESOLUTION: int = 5; # minutes; must be divisor of 60\n log_record: QueryLogProto = input;\n queries_per_degree: table sum[t: time][lat: int][lon: int] of int;\n loc: Location = locationinfo(log_record.ip);\n if (def(loc)) {\n t: time = log_record.time_usec;\n m: int = minuteof(t); # within the hour\n m = m - m % RESOLUTION;\n t = trunctohour(t) + time(m * int(MINUTE));\n emit queries_per_degree[t][int(loc.lat)][int(loc.lon)] <- 1;\n }"; final SymbolTable st = new SymbolTable(new SizzleBytes()); SizzleParser.ReInit(new StringReader(source)); TestTypeCheckingVisitor.typeChecker.visit(SizzleParser.Start(), st); Assert.assertEquals( "queries_per_degree is not an unweighted table of ints indexed by various", new SizzleTable( new SizzleInt(), Arrays.asList(new SizzleTime(), new SizzleInt(), new SizzleInt()), null), st.get("queries_per_degree")); // assertEquals("t is not an time", new SizzleTime(), st.get("t")); // assertEquals("m is not an int", new SizzleInt(), st.get("m")); Assert.assertEquals("RESOLUTION is not an int", new SizzleInt(), st.get("RESOLUTION")); final List<SizzleType> lmembers = new ArrayList<SizzleType>(Arrays.asList(new SizzleFloat(), new SizzleFloat())); Assert.assertEquals("loc is not a Location", new SizzleTuple(lmembers), st.get("loc")); final List<SizzleType> qlpmembers = new ArrayList<SizzleType>(Arrays.asList(new SizzleString(), new SizzleInt())); Assert.assertEquals( "log_record is not a QueryLogProto", new SizzleTuple(qlpmembers), st.get("log_record")); }
@Test public void testTypeCheckingVisitorTypeDeclaration() throws IOException, ParseException { final String source = "type my_bool = bool;\ntype Coordinates = { x: float, y: float };\ntype CityMap = map [city_name: string] of Coordinates;\n"; final SymbolTable st = new SymbolTable(); SizzleParser.ReInit(new StringReader(source)); TestTypeCheckingVisitor.typeChecker.visit(SizzleParser.Start(), st); Assert.assertEquals( "my_bool is not an alias for bool", new SizzleName(new SizzleBool()), st.getType("my_bool")); final ArrayList<SizzleType> members = new ArrayList<SizzleType>(Arrays.asList(new SizzleFloat(), new SizzleFloat())); Assert.assertEquals( "Coordinates is not is not an alias for a tuple of x: float, y: float", new SizzleName(new SizzleTuple(members)), st.getType("Coordinates")); Assert.assertEquals( "CityMap is not an alias for a mapping from string to tuple of x: float, y: float", new SizzleName(new SizzleMap(new SizzleString(), new SizzleName(new SizzleTuple(members)))), st.getType("CityMap")); }
public void handleStatement(ASTStatement node) { // System.out.println(node.getCode()); // Drawing connector.startSnap(node.getLineNumber()); // FIXME we'll see how this works // Nested scope for by macro SimpleNode s = (SimpleNode) node.jjtGetChild(0); if (s instanceof ASTStatementList) { System.out.println("This'll never happen"); SymbolTable st = new SymbolTable(Global.getCurrentSymbolTable()); st.setName("nested"); Global.setCurrentSymbolTable(st); s.jjtAccept(this, null); Global.setCurrentSymbolTable(st.getPrevious()); } else { node.jjtGetChild(0).jjtAccept(this, null); if (((SimpleNode) node.jjtGetChild(0)).getId() == JJTCALL) { ((ASTCall) (node.jjtGetChild(0))).setLineNumber(node.getLineNumber()); } update(node.getLineNumber(), UPDATE_REASON_STATEMENT); } // System.out.println("endStatement"); connector.endSnap(); }
public void handleFunction(ASTFunction node) { // Get the function's symbol table, set it's previous to the // calling function's, and then set it to current. connector.startSnap(node.getLineNumber()); if (node.getName().equals("main")) { connector.addQuestion(startQuestion); connector.showScope("main"); } else { } connector.endSnap(); if (!node.getUsed()) { return; } SymbolTable currentSymbolTable = node.getSymbolTable(); for (String p : node.getParameters()) { ByNameVariable v = new ByNameVariable(); v.setParam(); currentSymbolTable.put(p, v); } Global.setCurrentSymbolTable(currentSymbolTable); node.jjtGetChild(0).jjtAccept(this, null); leaveScope(); }
/** Performs semantic analysis on the function's signature and return type, but not the body. */ public void analyzeSignature(Log log, SymbolTable table, Subroutine owner, boolean inLoop) { SymbolTable tableForParameters; body.createTable(table); tableForParameters = body.getTable(); for (Variable parameter : parameters) { tableForParameters.insert(parameter, log); parameter.analyze(log, tableForParameters, owner, inLoop); } }
@Test public void multipleTables() { SymbolTable t1 = new SymbolTable(); SymbolTable t2 = new SymbolTable(); Symbol s1 = t1.create("foo"); Symbol s2 = t2.create("foo"); assertEquals(s1.getName(), s2.getName()); assertNotSame(s1, s2); }
/** Convenience routine taking Strings; lookup is done in SymbolTable. */ public Method findMethod(String name, String sig) { SymbolTable syms = VM.getVM().getSymbolTable(); Symbol nameSym = syms.probe(name); Symbol sigSym = syms.probe(sig); if (nameSym == null || sigSym == null) { return null; } return findMethod(nameSym, sigSym); }
private void visitBlock(BlockContext block) { symbolTable.newScope(); for (BlockStatementContext blockStatement : block.blockStatement()) { visitBlockStatement(blockStatement); } symbolTable.dropScope(); }
/** Resolve referenced names */ void resolveTypes(SymbolTable symbolTable) { symbolTable.pushScope(this); // push the current scope elements.resolveTypes(symbolTable); // resolve elements in this scope if (unresolvedStuff != null) { // resolve refs to other syms unresolvedStuff.resolveRefs(symbolTable); unresolvedStuff = null; } symbolTable.popScope(); // pop back out of the scope super.resolveTypes(symbolTable); // let superclass resolve if needed }
private void commit(byte command, long txn, long txPin) throws JournalException { boolean force = command == Tx.TX_FORCE; Partition<T> partition = lastNonEmptyNonLag(); Partition<T> lag = getIrregularPartition(); tx.command = command; tx.txn = txn; tx.txPin = txPin; tx.prevTxAddress = txLog.getCurrentTxAddress(); tx.journalMaxRowID = partition == null ? -1 : Rows.toRowID(partition.getPartitionIndex(), partition.size()); tx.lastPartitionTimestamp = partition == null || partition.getInterval() == null ? 0 : partition.getInterval().getLo(); tx.lagSize = lag == null ? 0 : lag.open().size(); tx.lagName = lag == null ? null : lag.getName(); tx.symbolTableSizes = new int[getSymbolTableCount()]; tx.symbolTableIndexPointers = new long[tx.symbolTableSizes.length]; for (int i = 0; i < tx.symbolTableSizes.length; i++) { SymbolTable tab = getSymbolTable(i); tab.commit(); if (force) { tab.force(); } tx.symbolTableSizes[i] = tab.size(); tx.symbolTableIndexPointers[i] = tab.getIndexTxAddress(); } tx.indexPointers = new long[getMetadata().getColumnCount()]; for (int i = Math.max(txPartitionIndex, 0), sz = nonLagPartitionCount(); i < sz; i++) { Partition<T> p = getPartition(i, true); p.commit(); if (force) { p.force(); } } if (partition != null) { partition.getIndexPointers(tx.indexPointers); } tx.lagIndexPointers = new long[tx.indexPointers.length]; if (lag != null) { lag.commit(); if (force) { lag.force(); } lag.getIndexPointers(tx.lagIndexPointers); } txLog.write(tx, txn != -1); if (force) { txLog.force(); } }
@Test public void testSymbol() { SymbolTable t = new SymbolTable(); Symbol s1 = t.create("foo"); // Check that two objects are equal (using Object.equals()) assertEquals(s1.getName(), "foo"); Symbol s2 = t.create("foo"); // Check that two objects are the same (same reference) assertSame(s1, s2); Symbol s3 = t.create("foobar"); assertNotSame(s1, s3); }
private boolean funDefined() { for (Symbol f : symbols.values()) { if (f.isFunction() && !f.defined) return false; } boolean ret = true; for (SymbolTable baby : this.children) { ret = ret && baby.funDefined(); } return ret; }
private String reportDeclareSymbolError(String name, int lineNum, int charPos) { String message = "DeclareSymbolError(" + lineNum + "," + charPos + ")[" + name + " already exists.]"; errorBuffer.append(message + "\n"); errorBuffer.append(symbolTable.toString() + "\n"); return message; }
private String reportResolveSymbolError(String name, int lineNum, int charPos) { String message = "ResolveSymbolError(" + lineNum + "," + charPos + ")[Could not find " + name + ".]"; errorBuffer.append(message + "\n"); errorBuffer.append(symbolTable.toString() + "\n"); return message; }
@Override public Integer eval(Evaluator evaluator, RuntimeEnvironment localEnv) throws EvaluatorException { Integer value; RuntimeEnvironment globalEnv = evaluator.getGlobalEnv(); SymbolTable symbolTable = evaluator.getSymbolTable(); if (localEnv.isBound(nameIndex)) { value = localEnv.fetch(nameIndex); } else if (globalEnv.isBound(nameIndex)) { value = globalEnv.fetch(nameIndex); } else { throw new EvaluatorException("Undefined variable: " + symbolTable.getName(nameIndex)); } return value; }
/* * Generate assignment IR nodes and add them to IR list * @param scope : the current scope * @param ctx: the current parse subtree context * @return last node in the list */ public IRNode attach_Assignment(SymbolTable scope, MicroParser.Assign_exprContext ctx) { Id dest_token = scope.search(ctx.id().getText()); if (dest_token == null) { System.err.println("Symbol not found: " + ctx.id().getText()); System.exit(1); } IRNode nodeA = null; IRDest v = attach_Expressions(scope, ctx.expr()); Register i_dest = null; if (v == null) { System.err.print("Expression returned null\n"); // TODO: and exit? return null; } i_dest = v._reg; Instruction op = ISA.STOREI; if (dest_token.type.equals("FLOAT")) { op = ISA.STOREF; } IRNode nodeB = null; if (i_dest != null) { nodeB = new IRNode(op, i_dest, dest_token); } else { nodeB = new IRNode(op, v._id, dest_token); } _List.add(nodeB); return null; }
/* * Grammar : ( READ BROPEN id_list BRCLOSE SEMI ); */ public void attach_Read(SymbolTable scope, MicroParser.Read_stmtContext rstmt) { String[] ids = rstmt.id_list().getText().split(","); // TODO: ugly for (int i = 0; i < ids.length; i++) { String token_name = ids[i]; IRNode n = new IRNode(ISA.READI, scope.search(token_name)); _List.add(n); } }
private Type retrieve(String id, CommonTree occ) { // Retrieve id's type from the type table. Type type = typeTable.get(id); if (type == null) { reportError(id + " is undeclared", occ); return Type.ERROR; } else return type; }
/* * @see com.ibm.wala.ssa.SSAPiNodePolicy#getPi(com.ibm.wala.ssa.SSAConditionalBranchInstruction, com.ibm.wala.ssa.SSAInstruction, * com.ibm.wala.ssa.SSAInstruction, com.ibm.wala.ssa.SymbolTable) */ @Override public Pair<Integer, SSAInstruction> getPi( SSAConditionalBranchInstruction cond, SSAInstruction def1, SSAInstruction def2, SymbolTable symbolTable) { if (def1 instanceof SSAInstanceofInstruction) { if (symbolTable.isBooleanOrZeroOneConstant(cond.getUse(1))) { return Pair.make(def1.getUse(0), def1); } } if (def2 instanceof SSAInstanceofInstruction) { if (symbolTable.isBooleanOrZeroOneConstant(cond.getUse(0))) { return Pair.make(def2.getUse(0), def2); } } return null; }
/* * Function : parseInstruction * Description : Parses the IType instructions without displacements. */ public static ITypeImmediate parseInstruction(String instruction, int address) { ITypeImmediate instruct = new ITypeImmediate(); // set the icode instruct.icode = IMap.get(Instruction.getIcodeName(instruction)); // grab the string from the registers.java class that we will use to match registers Pattern registerPattern = Pattern.compile(Registers.registerString()); Matcher registerMatcher = registerPattern.matcher(instruction); // match the first register if there is one if (registerMatcher.find()) { instruct.rd = Registers.registerValue(registerMatcher.group(0)); // I clear off the bits we've already read instruction = instruction.substring(registerMatcher.end(0)); } // match the second register if we can if (registerMatcher.find()) { instruct.r1 = Registers.registerValue(registerMatcher.group(0)); } // This regex attempts to match a label name. The [^\\s\\d] means not a space or digit character // This ensures that the label is infact a valid label and does not start with a number. Pattern symbolPattern = Pattern.compile("\\b([^\\d\\s][^\\s]*)\\b$"); Matcher symbolMatcher = symbolPattern.matcher(instruction); Pattern literalPattern = Pattern.compile("\\b(0x)?\\d+\\b"); Matcher literalMatcher = literalPattern.matcher(instruction); if (symbolMatcher.find()) { SymbolTable symbolTable = SymbolTable.getInstance(); instruct.immediateValue = symbolTable.getSymbol(symbolMatcher.group(0).replace(" ", "")); if (instruct.icode == BEQZ || instruct.icode == BNEZ) { instruct.r1 = instruct.rd; instruct.rd = 0; instruct.immediateValue = instruct.immediateValue - (address + 4); } } else if (literalMatcher.find()) { instruct.immediateValue = Tools.processNumber(literalMatcher.group(0).replace(" ", "")); } else { instruct.r1 = instruct.rd; instruct.rd = 0; } return instruct; }
@Test public void testTypeCheckingVisitorP4Stat() throws IOException, ParseException { final String source = "proto \"p4stat.proto\"\nsubmitsthroughweek: table sum[minute: int] of count: int;\nlog: P4ChangelistStats = input;\nt: time = log.time; # microseconds\nminute: int = minuteof(t)+60*(hourof(t)+24*(dayofweek(t)-1));\nemit submitsthroughweek[minute] <- 1;\n"; final SymbolTable st = new SymbolTable(new SizzleBytes()); SizzleParser.ReInit(new StringReader(source)); TestTypeCheckingVisitor.typeChecker.visit(SizzleParser.Start(), st); Assert.assertEquals( "submitsthroughweek is not an unweighted table of ints indexed by int", new SizzleTable(new SizzleInt(), Arrays.asList(new SizzleScalar[] {new SizzleInt()}), null), st.get("submitsthroughweek")); final List<SizzleType> members = new ArrayList<SizzleType>(Arrays.asList(new SizzleInt())); Assert.assertEquals("log is not a P4ChangelistStats", new SizzleTuple(members), st.get("log")); Assert.assertEquals("t is not a time", new SizzleTime(), st.get("t")); Assert.assertEquals("minute is not an int", new SizzleInt(), st.get("minute")); }
private Symbol tryResolveSymbol(Token ident) { assert (ident.is(Token.Kind.IDENTIFIER)); String name = ident.lexeme(); try { return symbolTable.lookup(name); } catch (SymbolNotFoundError e) { String message = reportResolveSymbolError(name, ident.lineNumber(), ident.charPosition()); return new ErrorSymbol(message); } }
/** * Creates a function definition and declaration in one fell swoop, all in global scope. This * isn't javascript, you know. * * @param name Function name * @param returnType Function return type * @param paramTypes Function parameter types or empty list for void * @return Indication of success */ public boolean defineFunction(String name, Type returnType, List<Type> paramTypes) { SymbolTable root = this; // getRoot(); Symbol s = root.getSymbol(name); if (s != null) { if (s.isFunction() && !s.defined && paramTypes.equals(s.signature.y) && returnType.equals(s.signature.x)) { s.defined = true; return true; } else { return false; } } s = new Symbol(name, null, new Pair<Type, List<Type>>(returnType, paramTypes)); s.defined = true; root.putSymbol(s); return true; }
private void detectSymbolsAndBaseAddresses() throws IOException { Hashtable<String, Integer> moduleSymbols = new Hashtable<String, Integer>(); int nd = parseNumber(); for (int i = 1; i <= nd; i++) { String symbol = parseWord(); if (SymbolTable.defines(symbol)) { String error = "Error: This variable is multiply defined; first value used."; SymbolTable.getInstance().getErrors().put(symbol, error); } else { moduleSymbols.put(symbol, parseNumber() + this.baseAddress); SymbolTable.getInstance().put(symbol, moduleSymbols.get(symbol)); } } skipUseList(); int moduleSize = parseNumber(); skipProgram(moduleSize); MemoryMap.createProgramModule(this.baseAddress, moduleSymbols); this.baseAddress += moduleSize; skipWhiteSpace(); }
/** * Call this function if you want to parse expressions which involve complex numbers. This method * specifies "i" as the imaginary unit (0,1). Two functions re() and im() are also added for * extracting the real or imaginary components of a complex number respectively. * * <p> * * @since 2.3.0 alpha The functions cmod and arg are added to get the modulus and argument. * @since 2.3.0 beta 1 The functions complex and polar to convert x,y and r,theta to Complex. * @since Feb 05 added complex conjugate conj. */ public void addComplex() { // add constants to Symbol Table symTab.addConstant("i", new Complex(0, 1)); funTab.put("re", new Real()); funTab.put("im", new Imaginary()); funTab.put("arg", new Arg()); funTab.put("cmod", new Abs()); funTab.put("complex", new ComplexPFMC()); funTab.put("polar", new Polar()); funTab.put("conj", new Conjugate()); }