void CodeGenerator::ProcessSetstateTerm(int flags) { infunc(CodeGenerator::ProcessSetstateTerm); INC_TOKEN; // Check for the name if (CUR_TOKEN.type != TOKEN_NAME) throw CompileError("(Line %d) Expecting the name of a state", CUR_TOKEN.line); // Grab the state name IsolateTokenString(CUR_TOKEN); if (g_Object) { State *state_ptr; // Try and get the state if ((state_ptr = cur_class->GetState(token_string)) == NULL) throw CompileError("(Line %d) Undefined state", CUR_TOKEN.line); // Write the opcode to set the state g_Object->WriteOp(OPCODE_SETSTATE, state_ptr->GetIndex()); } // State name INC_TOKEN; outfunc; }
// Parse the loop block and ignore its result int Compiler::ParseOptimizeBlock(int arguments) { if (!ThisTokenIsBinary('[')) { CompileError(CErrExpectLiteralBlock); return 0; } int nTextStart = ThisTokenRange().m_start; _ASSERTE(IsInOptimizedBlock()); // Parse the arguments - note we parse them anyway, regardless of whether they are wanted, // and subsequently complain if there are too many NextToken(); int argument = 0; while (m_ok && ThisTokenIsSpecial(':') ) { if (NextToken()==NameConst) { if (argument < arguments) RenameTemporary(argument, ThisTokenText(), ThisTokenRange()); else AddTemporary(ThisTokenText(), ThisTokenRange(), true); argument++; NextToken(); } else CompileError(CErrExpectVariable); } int argBar = -1; if (m_ok && argument > 0) { if (ThisTokenIsBinary(TEMPSDELIMITER)) { argBar = ThisTokenRange().m_stop; NextToken(); } else m_ok = false; } int nBlockTemps = 0; if (m_ok) { // Temporarily commented out for interim release ParseTemporaries(); ParseBlockStatements(); if (m_ok && ThisToken() != CloseSquare) CompileError(TEXTRANGE(nTextStart, LastTokenRange().m_stop), CErrBlockNotClosed); } if (m_ok && argument != arguments) CompileError(TEXTRANGE(nTextStart, argBar < 0 ? ThisTokenRange().m_stop : argBar), CErrIncorrectBlockArgCount); return nBlockTemps; }
void CodeGenerator::ProcessClassTerm(int flags) { Class *class_ptr; infunc(CodeGenerator::ProcessClassTerm); if (flags & FLAGS_IN_CLASS) throw CompileError("(Line %d) Already within a class", CUR_TOKEN.line); if (NEXT_TOKEN.type != TOKEN_NAME) throw CompileError("(Line %d) Expecting class name", CUR_TOKEN.line); // Move onto the name and grab it INC_TOKEN; IsolateTokenString(CUR_TOKEN); // Sneak passed it INC_TOKEN; if (g_Object == NULL) { // Allocate the memory if ((class_ptr = new Class) == NULL) throw CError("Couldn't allocate Class structure"); class_ptr->SetName(token_string); } else { // Class already defined, get it from the environment class_ptr = g_Env->GetClass(token_string); } ProcessClassModifiers(class_ptr); // Set the current class g_Env->SetActiveClass(class_ptr); cur_class = class_ptr; ProcessBlock(flags | FLAGS_IN_CLASS); // Go passed the close block INC_TOKEN; if (g_Object == NULL) { // Add the defined class to the environment class_ptr->SetDefined(); g_Env->AddClassPtr(class_ptr); } else { // Write the class information to file g_Object->WriteClassInfo(cur_class); } outfunc; }
void CodeGenerator::ProcessReturnTerm(int flags) { infunc(CodeGenerator::ProcessKeywordTerm); ParseTree *tree; if (!(flags & FLAGS_IN_FUNCTION)) throw CompileError("(Line %d) Cannot specify return keyword outside of a function", CUR_TOKEN.line); INC_TOKEN; // Does this function return any values? if (cur_class->cur_function->GetReturnType().id == VARIABLE_TYPEID_VOID) { // Can only end here if (CUR_TOKEN.type != TOKEN_END_OF_LINE) throw CompileError("(Line %d) Cannot specify return value for void function", CUR_TOKEN.line); return; } // Allocate the parse tree if ((tree = new ParseTree) == NULL) throw CError("Couldn't allocate parse tree"); // Build the parse tree tree->Build(tokeniser, TOKEN_END_OF_LINE, TOKEN_NULL); // Reduce it tree->Optimise(); if (g_Object) { tree->CompleteTypes(flags | FLAGS_IMPLICIT_ASSIGNMENT); tree->GenerateCode(flags | FLAGS_IMPLICIT_ASSIGNMENT); } // Don't need the tree delete tree; // Mark the return cur_class->cur_function->had_return = 1; if (g_Object) { // Pop the return value to a safe place if (cur_class->cur_function->GetReturnType().id != VARIABLE_TYPEID_VOID) g_Object->WriteOp(OPCODE_POP_RETURN); // Write the return code cur_class->cur_function->WriteReturn(g_Object); } outfunc; }
void CodeGenerator::ProcessClassModifiers(Class *class_ptr) { infunc(CodeGenerator::ProcessClassModifiers); int loop = 1; // Loop for a while while (loop) { switch (CUR_TOKEN.type) { // Does this class inherit? case (TOKEN_EXTENDS): INC_TOKEN; // Need a name for the super-class if (CUR_TOKEN.type != TOKEN_NAME) throw CompileError("(Line %d) Expecting name of super-class", CUR_TOKEN.line); // Grab the name IsolateTokenString(CUR_TOKEN); INC_TOKEN; // Set the super-class! if (g_Object == NULL) class_ptr->SetSuperClass(token_string); break; // Is this an abstract class? (Can't be instantiated) case (TOKEN_ABSTRACT): INC_TOKEN; // Set the abstract flag if (g_Object == NULL) class_ptr->SetFlag(CLASS_FLAGS_ABSTRACT); break; // Break out of the keyword search case (TOKEN_BLOCK_OPEN): loop = 0; break; // Anything else is an error default: throw CompileError("(Line %d) Illegal token after class definition", CUR_TOKEN.line); break; } } outfunc; }
E_F0* code(const basicAC_F0 & args) const { Expression p = args[1]; if(!p->EvaluableWithOutStack()) CompileError("A^p, The p must be a constant == -1, sorry"); long pv = GetAny<long>((*p)(NullStack)); if(pv != -1) { char buf[100]; sprintf(buf, "A^%ld, The pow must be == -1, sorry", pv); CompileError(buf); } return new E_F_F0<Inv, Op*>(Build<Inv, Op*>, t[0]->CastTo(args[0])); }
BuiltExpression NFABuilderImpl::getGraph() { DEBUG_PRINTF("built graph has %zu vertices and %zu edges\n", num_vertices(*graph), num_edges(*graph)); if (num_edges(*graph) > grey.limitGraphEdges) { throw CompileError("Pattern too large."); } if (num_vertices(*graph) > grey.limitGraphVertices) { throw CompileError("Pattern too large."); } return { expr, move(graph) }; }
//----------------------------------------------------------------------------- // From the I/O list, determine which pins are inputs and which pins are // outputs, and pack that in 8-bit format as we will need to write to the // TRIS or DDR registers. ADC pins are neither inputs nor outputs. //----------------------------------------------------------------------------- void BuildDirectionRegisters(BYTE *isInput, BYTE *isOutput) { memset(isOutput, 0x00, MAX_IO_PORTS); memset(isInput, 0x00, MAX_IO_PORTS); BOOL usedUart = UartFunctionUsed(); BOOL usedPwm = PwmFunctionUsed(); int i; for(i = 0; i < Prog.io.count; i++) { int pin = Prog.io.assignment[i].pin; if(Prog.io.assignment[i].type == IO_TYPE_DIG_OUTPUT || Prog.io.assignment[i].type == IO_TYPE_DIG_INPUT) { int j; for(j = 0; j < Prog.mcu->pinCount; j++) { McuIoPinInfo *iop = &Prog.mcu->pinInfo[j]; if(iop->pin == pin) { if(Prog.io.assignment[i].type == IO_TYPE_DIG_INPUT) { isInput[iop->port - 'A'] |= (1 << iop->bit); } else { isOutput[iop->port - 'A'] |= (1 << iop->bit); } break; } } if(j >= Prog.mcu->pinCount) { Error("Must assign pins for all I/O.\r\n\r\n" "'%s' is not assigned.", Prog.io.assignment[i].name); CompileError(); } if(usedUart && (pin == Prog.mcu->uartNeeds.rxPin || pin == Prog.mcu->uartNeeds.txPin)) { Error("UART in use; pins %d and %d reserved for that.", Prog.mcu->uartNeeds.rxPin, Prog.mcu->uartNeeds.txPin); CompileError(); } if(usedPwm && pin == Prog.mcu->pwmNeedsPin) { Error("PWM in use; pin %d reserved for that.", Prog.mcu->pwmNeedsPin); CompileError(); } } } }
Token & ReadToken(TokenType type) { if (pos >= tokens.Count()) { errors.Add(CompileError(TokenTypeToString(type) + String(L" expected but end of file encountered."), 0, CodePosition(0, 0, fileName))); throw 0; } else if (tokens[pos].Type != type) { errors.Add(CompileError(TokenTypeToString(type) + String(L" expected"), 20001, tokens[pos].Position)); throw 20001; } return tokens[pos++]; }
Token & ReadToken(const wchar_t * string) { if (pos >= tokens.Count()) { errors.Add(CompileError(String(L"\"") + string + String(L"\" expected but end of file encountered."), 0, CodePosition(0, 0, fileName))); throw 0; } else if (tokens[pos].Content != string) { errors.Add(CompileError(String(L"\"") + string + String(L"\" expected"), 0, tokens[pos].Position)); throw 20001; } return tokens[pos++]; }
void Lexer::ScanLiteral() { // Literal; remove # tp--; NextChar(); if (isIdentifierFirst(m_cc)) { ScanSymbol(); m_tokenType = SymbolConst; } else if (isAnsiBinaryChar(m_cc)) { ScanBinary(); m_tokenType = SymbolConst; } else if (m_cc == STRINGDELIM) { // Quoted Symbol ScanString(CharPosition()); m_tokenType = SymbolConst; } else if (m_cc == '(') { m_tokenType = ArrayBegin; } else if (m_cc == '[') { m_tokenType = ByteArrayBegin; } else if (m_cc == LITERAL) { // Second hash, so should be a constant expression ##(xxx) NextChar(); if (m_cc != '(') CompileError(TEXTRANGE(CharPosition(), CharPosition()), LErrExpectExtendedLiteral); m_tokenType = ExprConstBegin; } else { m_thisTokenRange.m_stop = CharPosition(); CompileError(LErrExpectConst); } }
void Environment::AddClassPtr(Class *class_ptr) { infunc(Environment::AddClassPtr); Class *tclass; // Check to see if the class is already in the environment if ((tclass = (Class *)class_hash.GetEntry(class_ptr->GetName())) == NULL) { // Add to the classes in the environment class_hash.Add(class_ptr->GetName(), class_ptr); } else { // Throw an error if the class has already been defined if (tclass->IsDefined()) throw CompileError("(File %s) Second definition of class %s found", cur_filename, tclass->GetName()); // Remove the old shell and replace it with the defined class class_hash.Remove(tclass); class_hash.Add(class_ptr->GetName(), class_ptr); } // Add to the list of base classes if it's a base class if (!class_ptr->DoesInherit()) base_classes.Add(class_ptr); outfunc; }
void ReportManager::registerExtReport(ReportID id, const external_report_info &ext) { if (contains(externalIdMap, id)) { const external_report_info &eri = externalIdMap.at(id); if (eri.highlander != ext.highlander) { /* we have a problem */ ostringstream out; out << "Expression (index " << ext.first_pattern_index << ") with match ID " << id << " "; if (!ext.highlander) { out << "did not specify "; } else { out << "specified "; } out << "HS_FLAG_SINGLEMATCH whereas previous expression (index " << eri.first_pattern_index << ") with the same match ID did"; if (ext.highlander) { out << " not"; } out << "."; throw CompileError(ext.first_pattern_index, out.str()); } } else { externalIdMap.emplace(id, ext); } // Any non-highlander pattern will render us not globally exhaustible. if (!ext.highlander) { global_exhaust = false; } }
//----------------------------------------------------------------------------- // Return the address (octet) and bit of the bit in memory that represents the // given input or output pin. Raises an internal error if the specified name // is not present in the I/O list or a user error if a pin has not been // assigned to that I/O name. Will allocate if it no memory allocated for it // yet, else will return the previously allocated bit. //----------------------------------------------------------------------------- static void MemForPin(char *name, DWORD *addr, int *bit, BOOL asInput) { int i; for(i = 0; i < Prog.io.count; i++) { if(strcmp(Prog.io.assignment[i].name, name)==0) break; } if(i >= Prog.io.count) oops(); if(asInput && Prog.io.assignment[i].type == IO_TYPE_DIG_OUTPUT) oops(); if(!asInput && Prog.io.assignment[i].type == IO_TYPE_DIG_INPUT) oops(); int pin = Prog.io.assignment[i].pin; for(i = 0; i < Prog.mcu->pinCount; i++) { if(Prog.mcu->pinInfo[i].pin == pin) break; } if(i >= Prog.mcu->pinCount) { Error("Must assign pins for all I/O.\r\n\r\n" "'%s' is not assigned.", name); CompileError(); } McuIoPinInfo *iop = &Prog.mcu->pinInfo[i]; if(asInput) { *addr = Prog.mcu->inputRegs[iop->port - 'A']; } else { *addr = Prog.mcu->outputRegs[iop->port - 'A']; } *bit = iop->bit; }
ExprPtr NamedRef::resolve(ModuleBuilder& modBuilder) { auto resolvedExpr = modBuilder.resolveIdent(name); if(!resolvedExpr) throw CompileError(CEUnresolvedIdentifier, 0); return resolvedExpr->doResolve(modBuilder); }
TypePtr TypeDataAlias::doResolve(ModuleBuilder& /*modBuilder*/) { if(resolveStarted) throw CompileError(CECyclicRef, -1); resolveStarted = true; aliasFor = aliasFor->doResolve(*modBuilder); resolveStarted = false; return aliasFor; }
string Parser::expectIdent(bool se) { if(token != TIdent) throw CompileError(CEUnexpectedToken, currentLine); string ret(tokenStr); next(se); return ret; }
void StringLiteral::ResolveType(int flags) { infunc(StringLiteral::ResolveType); // Check for errors only (type was resolved in the constructor) if (flags & FLAGS_ASSIGN_DEST) throw CompileError("(Line %d) String literals are not l-values", token.line); outfunc; }
void PatternBindingExpr::doResolve( ModuleBuilder& modBuilder, TypePtr const& valueType) { if(!var->declType) var->declType = valueType; var->declType = var->declType->doResolve(modBuilder); if(! var->declType->isAssignableFrom(*valueType)) throw CompileError(CETypeError, -1); }
//----------------------------------------------------------------------------- // Return the address of a previously unused octet of RAM on the target, or // signal an error if there is no more available. //----------------------------------------------------------------------------- DWORD AllocOctetRam(void) { if(MemOffset >= Prog.mcu->ram[0].len) { Error("Out of memory; simplify program or choose " "microcontroller with more memory."); CompileError(); } MemOffset++; return Prog.mcu->ram[0].start + MemOffset - 1; }
llvm::Value* MatchSingleNonRejectExpr::build(FuncBuilder& builder) { auto valueVal = value->build(builder); bool nonReject = pattern->build(builder, valueVal, 0, 0); if(!nonReject) throw CompileError(CEGeneralError, this); return 0; }
//----------------------------------------------------------------------------- // Do any post-compilation sanity checks necessary. //----------------------------------------------------------------------------- void MemCheckForErrorsPostCompile(void) { int i; for(i = 0; i < InternalRelayCount; i++) { if(!InternalRelays[i].assignedTo) { Error( "Internal relay '%s' never assigned; add its coil somewhere.", InternalRelays[i].name); CompileError(); } } }
unique_ptr<HWLMProto> hwlmBuildProto(vector<hwlmLiteral> &lits, bool make_small, const CompileContext &cc) { assert(!lits.empty()); dumpLits(lits); // Check that we haven't exceeded the maximum number of literals. if (lits.size() > cc.grey.limitLiteralCount) { throw ResourceLimitError(); } // Safety and resource limit checks. u64a total_chars = 0; for (const auto &lit : lits) { assert(!lit.s.empty()); if (lit.s.length() > cc.grey.limitLiteralLength) { throw ResourceLimitError(); } total_chars += lit.s.length(); if (total_chars > cc.grey.limitLiteralMatcherChars) { throw ResourceLimitError(); } // We do not allow the all-ones ID, as we reserve that for internal use // within literal matchers. if (lit.id == 0xffffffffu) { assert(!"reserved id 0xffffffff used"); throw CompileError("Internal error."); } } unique_ptr<HWLMProto> proto; DEBUG_PRINTF("building table with %zu strings\n", lits.size()); assert(everyoneHasGroups(lits)); if (isNoodleable(lits, cc)) { DEBUG_PRINTF("build noodle table\n"); proto = ue2::make_unique<HWLMProto>(HWLM_ENGINE_NOOD, lits); } else { DEBUG_PRINTF("building a new deal\n"); proto = fdrBuildProto(HWLM_ENGINE_FDR, lits, make_small, cc.target_info, cc.grey); if (!proto) { return nullptr; } } return proto; }
void NFABuilderImpl::addVertex(Position pos) { // Enforce resource limit. if (pos > grey.limitGraphVertices) { throw CompileError("Pattern too large."); } NFAVertex v = add_vertex(*graph); if (id2vertex.size() <= pos) { id2vertex.resize(pos + 1); } id2vertex[pos] = v; (*graph)[v].index = pos; }
MatrixUpWind0(const basicAC_F0 & args) { args.SetNameParam(); emat =args[0]; expTh= to<pmesh>(args[1]); expc = CastTo<double>(args[2]); const E_Array * a= dynamic_cast<const E_Array*>((Expression) args[3]); if (a->size() != 2) CompileError("syntax: MatrixUpWind0(Th,rhi,[u1,u2])"); int err =0; expu1= CastTo<double>((*a)[0]); expu2= CastTo<double>((*a)[1]); }
bool LookAheadToken(const wchar_t * string) { if (pos >= tokens.Count()) { errors.Add(CompileError(String(L"\'") + string + String(L"\' expected but end of file encountered."), 0, CodePosition(0, 0, fileName))); return false; } else { if (tokens[pos].Content == string) return true; else return false; } }
void PatternNamedCtorExpr::doResolve( ModuleBuilder& modBuilder, TypePtr const& valueType) { // TODO: ctor->type may be generic, e.g. Box(a). // We need to match this against valueType, which may be e.g. Box(Int) // translating ctor->members[i].type to 'Int', not 'a'. auto ctorI = modBuilder.module->constructorDefs.find(name); if(ctorI == modBuilder.module->constructorDefs.end()) throw CompileError(CEUnresolvedIdentifier, -1); ctor = ctorI->second; if(! ctor->type->isAssignableFrom(*valueType)) throw CompileError(CETypeError, -1); if(subPatterns.size() != (size_t)ctor->ctorParams) throw CompileError(CEGeneralError, -1); for(auto i = 0u; i < subPatterns.size(); ++i) { subPatterns[i]->doResolve(modBuilder, ctor->members[i].type); } }
void CodeGenerator::ProcessBeginTerm(int flags) { infunc(CodeGenerator::ProcessBeginTerm); INC_TOKEN; if ((flags & FLAGS_IN_STATE) && CUR_TOKEN.type == TOKEN_COLON) { if (g_Object) { if (cur_class->cur_state->GetCodeStart() != -1) throw CompileError("(Line %d) Multiple 'begin' declaration", CUR_TOKEN.line); // Set the execution position here cur_class->cur_state->SetCodeStart(g_Object->GetPosition()); } } else { throw CompileError("(Line %d) Expecting colon to complete 'begin' declaration", CUR_TOKEN.line); } outfunc; }
bool CCastleGame::ProcessGameUntilBreak() { char szCurrentString[MAX_CHARS_PER_LINE]; FUNCTIONTYPE eFunction=FUNCTIONFAIL; int nNumLoops=0; while(true) { //Read the next statement STATEMENTRESULT stResult=ReadStatement(szCurrentString, MAX_CHARS_PER_LINE); if(stResult == ST_FUNCTION) { eFunction=GetFunction(szCurrentString); ProcessFunction(eFunction, szCurrentString); if(eFunction==END||eFunction==CHOICE)break; } else if(stResult==ST_LABEL) { //we don't need to do anything on a label } else { CompileError(("Error: An error occured while translating the script!")); } //if this loop loops too many times we quit because there is probably //a problem with the script (for example an infinite GOTO loop) nNumLoops++; if(nNumLoops>1000) { CompileError(("Error: Possible Infinite Loop!")); return false; } } return true; }
ConcreteNodePtr CompilationContext::instantiate( const string& name, Type argTypes ) { if (ConcreteNodePtr cn = _scope->lookup(name, argTypes)) { //std::cerr << "Found " << name << "\n"; return cn; } //std::cerr << "Didn't find " << name << "\n"; // We didn't find it. std::ostringstream os; os << name << " accepting " << argTypes.getName() << " not defined."; throw CompileError(os.str()); }