diff --git a/openmodelica/bootstrapping/TestDiffAlgorithmModelica.mo b/openmodelica/bootstrapping/TestDiffAlgorithmModelica.mo index 92988f1a4ee..6269273f597 100644 --- a/openmodelica/bootstrapping/TestDiffAlgorithmModelica.mo +++ b/openmodelica/bootstrapping/TestDiffAlgorithmModelica.mo @@ -1,5 +1,5 @@ function diffModelica - import LexerModelicaDiff.{Token,TokenId,tokenContent,scan,scanString}; + import LexerModelicaDiff.{Token,TokenId,tokenContent,scan,scanString,filterModelicaDiff,modelicaDiffTokenEq}; import DiffAlgorithm.{Diff,diff,printActual,printDiffTerminalColor}; input String before; input String after; @@ -16,159 +16,10 @@ algorithm diffs := diff(tbefore, tafter, modelicaDiffTokenEq); diffs := filterModelicaDiff(diffs); // Scan a second time, with comments filtered into place - after2 := printActual(diffs, LexerModelicaDiff.tokenContent); + after2 := printActual(diffs, tokenContent); tafter2 := scanString(after2); diffs := diff(tbefore, tafter2, modelicaDiffTokenEq); diffs := filterModelicaDiff(diffs); - print(printDiffTerminalColor(diffs, LexerModelicaDiff.tokenContent)); + print(printDiffTerminalColor(diffs, tokenContent)); print("\n\n"); end diffModelica; - -function modelicaDiffTokenEq - import LexerModelicaDiff.{Token,TokenId,tokenContent}; - input Token ta,tb; - output Boolean b; -protected - LexerModelicaDiff.TokenId ida,idb; -algorithm - LexerModelicaDiff.TOKEN(id=ida) := ta; - LexerModelicaDiff.TOKEN(id=idb) := tb; - if ida <> idb then - b := false; - return; - end if; - b := match ida - case TokenId.IDENT then tokenContent(ta)==tokenContent(tb); - case TokenId.UNSIGNED_INTEGER then tokenContent(ta)==tokenContent(tb); - case TokenId.UNSIGNED_REAL - then stringReal(tokenContent(ta))==stringReal(tokenContent(tb)); - case TokenId.BLOCK_COMMENT - then valueEq(blockCommentCanonical(ta),blockCommentCanonical(tb)); - case TokenId.LINE_COMMENT then tokenContent(ta)==tokenContent(tb); - case TokenId.STRING then tokenContent(ta)==tokenContent(tb); - case TokenId.WHITESPACE then true; // tokenContent(ta)==tokenContent(tb); - else true; - end match; -end modelicaDiffTokenEq; - -function filterModelicaDiff - import LexerModelicaDiff.{Token,TokenId,tokenContent,TOKEN}; - import DiffAlgorithm.Diff; - input list>> diffs; - output list>> odiffs; -protected - list addedLineComments, removedLineComments; - list> addedBlockComments, removedBlockComments; - list> simpleDiff; -algorithm - // No changes are easy - _ := match diffs - case {(Diff.Equal,_)} - algorithm - odiffs := diffs; - return; - then (); - else (); - end match; - - odiffs := listReverse(match e - local - list ts; - case (Diff.Delete,ts as {TOKEN(id=TokenId.WHITESPACE)}) then (Diff.Equal,ts); - else e; - end match - - for e guard( - match e - // Single addition of whitespace, not followed by another addition - // is suspected garbage added by OMC. - case (Diff.Add,{TOKEN(id=TokenId.WHITESPACE)}) then false; - case (_,{}) then false; - else true; - end match - ) in diffs); - - // Convert from multiple additions per item to one per item - // Costs more memory, but is easier to transform - simpleDiff := listAppend( - match e - local - list ts; - case (Diff.Add,ts) then list((Diff.Add,t) for t in ts); - case (Diff.Equal,ts) then list((Diff.Equal,t) for t in ts); - case (Diff.Delete,ts) then list((Diff.Delete,t) for t in ts); - end match - for e in odiffs); - - addedLineComments := list(tokenContent(tuple22(e)) for e guard Diff.Add==tuple21(e) and isLineComment(tuple22(e)) in simpleDiff); - removedLineComments := list(tokenContent(tuple22(e)) for e guard Diff.Delete==tuple21(e) and isLineComment(tuple22(e)) in simpleDiff); - - addedBlockComments := list(blockCommentCanonical(tuple22(e)) for e guard Diff.Add==tuple21(e) and isBlockComment(tuple22(e)) in simpleDiff); - removedBlockComments := list(blockCommentCanonical(tuple22(e)) for e guard Diff.Delete==tuple21(e) and isBlockComment(tuple22(e)) in simpleDiff); - - simpleDiff := list( - match e - local - Token t; - case (Diff.Delete,t as TOKEN(id=TokenId.LINE_COMMENT)) then (if listMember(tokenContent(t), addedLineComments) then (Diff.Equal,t) else e); - case (Diff.Delete,t as TOKEN(id=TokenId.BLOCK_COMMENT)) then (if listMember(blockCommentCanonical(t), addedBlockComments) then (Diff.Equal,t) else e); - else e; - end match - for e guard( - match e - local - Token t; - case (Diff.Add,t as TOKEN(id=TokenId.LINE_COMMENT)) then not listMember(tokenContent(t), removedLineComments); - case (Diff.Add,t as TOKEN(id=TokenId.BLOCK_COMMENT)) then not listMember(blockCommentCanonical(t), removedBlockComments); - else true; - end match - ) in simpleDiff); - - odiffs := list( - match e - local - Diff d; - Token t; - case (d,t) then (d,{t}); - end match - for e in simpleDiff); -end filterModelicaDiff; - -function isBlockComment - import LexerModelicaDiff.{Token,TokenId,TOKEN}; - input Token t; - output Boolean b; -algorithm - b := match t case TOKEN(id=TokenId.BLOCK_COMMENT) then true; else false; end match; -end isBlockComment; - -function isLineComment - import LexerModelicaDiff.{Token,TokenId,TOKEN}; - input Token t; - output Boolean b; -algorithm - b := match t case TOKEN(id=TokenId.LINE_COMMENT) then true; else false; end match; -end isLineComment; - -function tuple21 - input tuple t; - output A a; -algorithm - (a,_) := t; -end tuple21; - -function tuple22 - input tuple t; - output B b; -algorithm - (_,b) := t; -end tuple22; - -function blockCommentCanonical - import LexerModelicaDiff.{Token,tokenContent}; - input Token t; - output list lines; -algorithm - // Canonical representation trims whitespace from each line - lines := list(System.trim(s) for s in System.strtok(tokenContent(t),"\n")); -end blockCommentCanonical; diff --git a/openmodelica/omcc/.gitignore b/openmodelica/omcc/.gitignore deleted file mode 100644 index 72a2a5368e1..00000000000 --- a/openmodelica/omcc/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -OpenModelicaHome.mo -System_*.* -Settings_*.* -Print_*.* -Flags_*.* -Error_*.* -ErrorExt_*.* -OMCC_main* -LexerTest_main* -*Modelica.mo -OMCC diff --git a/openmodelica/omcc/GenerateParser.mos b/openmodelica/omcc/GenerateParser.mos deleted file mode 100644 index 41753de142a..00000000000 --- a/openmodelica/omcc/GenerateParser.mos +++ /dev/null @@ -1,33 +0,0 @@ -setCommandLineOptions({"+g=MetaModelica","+d=rml"}); -loadFile("Types.mo"); -loadFile("Absyn.mo"); - -compilerSources := "../../../OMCompiler/Compiler/"; - -loadFile(compilerSources + "Util/Error.mo"); -loadFile(compilerSources + "Util/ErrorExt.mo"); -loadFile(compilerSources + "FrontEnd/Dump.mo"); -loadFile(compilerSources + "Util/Print.mo"); -loadFile(compilerSources + "Util/Flags.mo"); -loadFile(compilerSources + "Global/Global.mo"); -loadFile(compilerSources + "Util/Config.mo"); -loadFile(compilerSources + "Util/Debug.mo"); -loadFile(compilerSources + "Util/List.mo"); -loadFile(compilerSources + "Util/Settings.mo"); -loadFile(compilerSources + "Util/Corba.mo"); -loadFile(compilerSources + "Util/Util.mo"); -loadFile(compilerSources + "Util/StringUtil.mo"); -loadFile(compilerSources + "Util/System.mo"); -loadFile("TokenModelica.mo"); -loadFile("LexTableModelica.mo"); -loadFile("LexerCodeModelica.mo"); -loadFile("LexerModelica.mo"); -loadFile("ParseCodeModelica.mo"); -loadFile("ParserModelica.mo"); -loadFile("ParseTableModelica.mo"); -loadFile("Main.mo"); -getErrorString(); - -setCFlags(getCFlags() + " -O2 -g -DGENERATE_MAIN_EXECUTABLE "); getErrorString(); -generateCode(Main.main); getErrorString(); -generateEntryPoint("modelicaParserMain.c",Main.main); diff --git a/openmodelica/omcc/LexerCode.tmo b/openmodelica/omcc/LexerCode.tmo deleted file mode 100644 index 789be4df598..00000000000 --- a/openmodelica/omcc/LexerCode.tmo +++ /dev/null @@ -1,426 +0,0 @@ -encapsulated package %LexerCode% "Automatically generated lexer based on flex, generated %time%" - /* - Template for Lexer Code - replace keywords: - %LexerCode - %time - %Token - %Lexer - %LexTable - %constant - %nameSpan - %functions - %caseAction - */ - -import System; - -import arrayGet = MetaModelica.Dangerous.arrayGetNoBoundsChecking; // Bounds checked with debug=true -import stringGet = MetaModelica.Dangerous.stringGetNoBoundsChecking; -import MetaModelica.Dangerous.listReverseInPlace; - -constant Boolean debug = false; - -replaceable package LexTable - constant Integer yy_limit; - constant Integer yy_finish; - constant Integer yy_acclist[:]; - constant Integer yy_accept[:]; - constant Integer yy_ec[:]; - constant Integer yy_meta[:]; - constant Integer yy_base[:]; - constant Integer yy_def[:]; - constant Integer yy_nxt[:]; - constant Integer yy_chk[:]; -end LexTable; - -function scan "Scan starts the lexical analysis, load the tables and consume the program to output the tokens" - input String fileName "input source code file"; - output list tokens "return list of tokens"; -protected - String contents; -algorithm - contents := System.readFile(fileName); - tokens := lex(fileName,contents); -end scan; - -function scanString "Scan starts the lexical analysis, load the tables and consume the program to output the tokens" - input String fileSource "input source code file"; - output list tokens "return list of tokens"; -algorithm - tokens := lex("",fileSource); -end scanString; - -%prologue% -function action - input Integer act; - input Integer startSt; - input Integer mm_currSt,mm_pos,mm_sPos,mm_ePos,mm_linenr,lineNrStart; - input Integer buffer; - input Boolean debug; - input String fileNm; - input String fileContents; - output Token token; - output Integer mm_startSt; - output Integer bufferRet; -protected - SourceInfo info; - String sToken; -algorithm - mm_startSt := startSt; - // nameSpan := %nameSpan%; - bufferRet := 0; - (token) := match (act) - local - Token tok; -%caseAction% - else - equation - print("\nLexer unknown rule, action="+String(act)+"\n"); - tok = TOKEN("",TokenId._NO_TOKEN,fileContents,mm_pos-buffer,buffer,lineNrStart,mm_ePos+1,mm_linenr,mm_sPos+1); - print(printToken(tok)); - then fail(); - end match; -end action; - -%Tokens% - -uniontype Token - record TOKEN - String name; - TokenId id; - String fileContents; - Integer byteOffset,length; - Integer lineNumberStart; - Integer columnNumberStart; - Integer lineNumberEnd; - Integer columnNumberEnd; - end TOKEN; -end Token; - -constant Token noToken = TOKEN("",TokenId._NO_TOKEN,"",0,0,0,0,0,0); - -function printToken - input Token token; - output String strTk; -protected - String tokName,contents; - Integer lns,cns,lne,cne,byteOffset,length; -algorithm - TOKEN(name=tokName,lineNumberStart=lns,columnNumberStart=cns,lineNumberEnd=lne,columnNumberEnd=cne,fileContents=contents,byteOffset=byteOffset,length=length) := token; - contents := if length>0 then substring(contents,byteOffset,byteOffset+length-1) else ""; - strTk := "[TOKEN:" + tokName + " '" + contents + "' (" + intString(lns) + ":" + intString(cns) + "-"+ intString(lne) + ":" + intString(cne) +")]"; -end printToken; - -function tokenContent - input Token token; - output String contents; -protected - Integer byteOffset,length; -algorithm - TOKEN(fileContents=contents,byteOffset=byteOffset,length=length) := token; - contents := if length>0 then substring(contents,byteOffset,byteOffset+length-1) else ""; -end tokenContent; - -protected - -function lex "Scan starts the lexical analysis, load the tables and consume the program to output the tokens" - input String fileName "input source code file"; - input String contents; - output list tokens "return list of tokens"; -protected - Integer startSt,numStates,i,r,cTok,cTok2,currSt,pos,sPos,ePos,linenr,contentLen,numBacktrack,buffer,lineNrStart; - list cProg,cProg2; - list chars; - array states; - String s1,s2; -algorithm - // load arrays - - // Initialize the Env Variables - startSt := 1; - currSt := 1; - pos := 1; - sPos := 0; - ePos := 0; - linenr := 1; - lineNrStart := 1; - buffer := 0; - - states := arrayCreate(128,1); - numStates := 1; - - if (debug==true) then - print("\nLexer analyzer LexerCode..." + fileName + "\n"); - //printAny("\nLexer analyzer LexerCode..." + fileName + "\n"); - end if; - - tokens := {}; - if (debug) then - print("\n TOTAL Chars:"); - print(intString(stringLength(contents))); - end if; - contentLen := stringLength(contents); - i := 1; - while i <= contentLen loop - cTok := stringGet(contents,i); - (tokens,numBacktrack,startSt,currSt,pos,sPos,ePos,linenr,lineNrStart,buffer,states,numStates) := consume(cTok,tokens,contents,startSt,currSt,pos,sPos,ePos,linenr,lineNrStart,buffer,states,numStates,fileName); - i := i - numBacktrack + 1; - end while; - tokens := listReverseInPlace(tokens); -end lex; - -function consume - input Integer cp; - input list tokens; - input String fileContents; - input Integer startSt; - input Integer currSt,pos,sPos,ePos,linenr,inLineNrStart; - input Integer inBuffer; - input array inStates; - input Integer inNumStates; - input String fileName; - output list resToken; - output Integer bkBuffer = 0; - output Integer mm_startSt; - output Integer mm_currSt,mm_pos,mm_sPos,mm_ePos,mm_linenr,lineNrStart; - output Integer buffer; - output array states; - output Integer numStates; -protected - Token tok; - Integer act,buffer2; - Integer c,baseCond; -algorithm - mm_startSt := startSt; - mm_currSt := currSt; - mm_pos := pos; - mm_sPos := sPos; - mm_ePos := ePos; - mm_linenr := linenr; - lineNrStart := inLineNrStart; - buffer := inBuffer; - states := inStates; - numStates := inNumStates; - - baseCond := LexTable.yy_base[mm_currSt]; - if (debug==true) then - print("\nPROGRAM:{" + intString(cp) + "} "); - print("\nBUFFER:{" + intString(buffer) + "} "); - print("base:" + intString(baseCond) + " st:" + intString(mm_currSt)+" "); - end if; - - buffer := buffer+1; - mm_pos := mm_pos+1; - - if (cp==10) then - mm_linenr := mm_linenr+1; - mm_sPos := 0; - else - mm_sPos := mm_sPos+1; - end if; - if (debug==true) then - print("\n[Reading:'" + intStringChar(cp) +"' at p:" + intString(mm_pos-1) + " line:"+ intString(mm_linenr) + " rPos:" + intString(mm_sPos) +"]"); - end if; - c := LexTable.yy_ec[cp]; - - if (debug==true) then - print(" evalState Before[c" + intString(c) + ",s"+ intString(mm_currSt)+"]"); - end if; - (mm_currSt,c) := evalState(mm_currSt,c); - if (debug==true) then - print(" After[c" + intString(c) + ",s"+ intString(mm_currSt)+"]"); - end if; - if (mm_currSt>0) then - mm_currSt := LexTable.yy_base[mm_currSt]; - // print("BASE:"+ intString(mm_currSt)+"]"); - mm_currSt := LexTable.yy_nxt[mm_currSt + c]; - // print("NEXT:"+ intString(mm_currSt)+"]"); - else - mm_currSt := LexTable.yy_nxt[c]; - end if; - numStates := numStates+1; // TODO: BAD BAD BAD. At least arrayUpdate should be a safe operation... We need to grow the number of states on demand though. - arrayUpdate(states,numStates,mm_currSt); - - baseCond := LexTable.yy_base[mm_currSt]; - if (baseCond==LexTable.yy_finish) then - if (debug==true) then - print("\n[RESTORE=" + intString(LexTable.yy_accept[mm_currSt]) + "]"); - end if; - - (act, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates) := findRule(fileContents, mm_currSt, mm_pos, mm_sPos, mm_ePos, mm_linenr, buffer, bkBuffer, states, numStates); - - if (debug==true) then - print("\nFound rule: " + String(act)); - end if; - - (tok,mm_startSt,buffer2) := action(act,mm_startSt,mm_currSt,mm_pos,mm_sPos,mm_ePos,mm_linenr,lineNrStart,buffer,debug,fileName,fileContents); - - if (debug==true) then - print("\nDid action"); - end if; - - mm_currSt := mm_startSt; - arrayUpdate(states,1,mm_startSt); - numStates := 1; - - /* Either a token was output (get new positions for next token). Or a whitespace was emitted. */ - if buffer <> buffer2 then - mm_ePos := mm_sPos; - lineNrStart := linenr; - end if; - buffer := buffer2; - - resToken := match tok - case TOKEN(id=TokenId._NO_TOKEN) then tokens; - else tok::tokens; - end match; - if(debug) then - print("\n CountTokens:" + intString(listLength(resToken))); - end if; - else - bkBuffer := 0; // consume the character - resToken := tokens; - end if; - -end consume; - - -function findRule - input String fileContents; - input Integer currSt; - input Integer pos; - input Integer sPos; - input Integer mm_ePos; - input Integer linenr; - input Integer inBuffer; - input Integer inBkBuffer; - input array inStates; - input Integer inNumStates; - output Integer action; - output Integer mm_currSt; - output Integer mm_pos; - output Integer mm_sPos; - output Integer mm_linenr; - output Integer buffer; - output Integer bkBuffer; - output array states; - output Integer numStates; -protected - array mm_accept,mm_ec,mm_meta,mm_base,mm_def,mm_nxt,mm_chk,mm_acclist; - Integer lp,lp1,stCmp; - Boolean st; -algorithm - mm_currSt := currSt; - mm_pos := pos; - mm_sPos := sPos; - mm_linenr := linenr; - buffer := inBuffer; - bkBuffer := inBkBuffer; - states := inStates; - numStates := inNumStates; - - stCmp := arrayGet(states,numStates); - lp := LexTable.yy_accept[stCmp]; - lp1 := LexTable.yy_accept[stCmp+1]; - - st := intGt(lp,0) and intLt(lp,lp1); - (action, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates) := match(numStates,st) - local - Integer act,cp; - list restBuff; - case (_,true) - algorithm - if debug then - checkArrayModelica(LexTable.yy_accept,stCmp,sourceInfo()); - checkArrayModelica(LexTable.yy_acclist,lp,sourceInfo()); - end if; - lp := LexTable.yy_accept[stCmp]; - act := LexTable.yy_acclist[lp]; - then (act, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates); - case (_,false) - algorithm - cp := stringGet(fileContents,mm_pos-1); - buffer := buffer-1; - bkBuffer := bkBuffer+1; - mm_pos := mm_pos - 1; - mm_sPos := mm_sPos -1; - if (cp==10) then - mm_sPos := mm_ePos; - mm_linenr := mm_linenr-1; - end if; - if debug then - checkArray(states,numStates,sourceInfo()); - end if; - mm_currSt := arrayGet(states,numStates); - numStates := numStates - 1; - (act, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates) := findRule(fileContents, mm_currSt, mm_pos, mm_sPos, mm_ePos, mm_linenr, buffer, bkBuffer, states, numStates); - then (act, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates); - - end match; -end findRule; - -function evalState - input Integer cState; - input Integer c; - output Integer new_state; - output Integer new_c; -protected - Integer cState1=cState; - Integer c1=c; - Integer val,val2,chk; -algorithm - chk := LexTable.yy_base[cState1]; - chk := chk + c1; - val := LexTable.yy_chk[chk]; - val2 := LexTable.yy_base[cState1] + c1; - if cState1<>val then - cState1 := LexTable.yy_def[cState1]; - if cState1 >= LexTable.yy_limit then - c1 := LexTable.yy_meta[c1]; - end if; - if (cState1>0) then - (cState1,c1) := evalState(cState1,c1); - end if; - end if; - new_state := cState1; - new_c := c1; -end evalState; - -function checkArray - input array arr; - input Integer index; - input SourceInfo info; -protected - String filename; - Integer lineStart; -algorithm - if index<1 or index>arrayLength(arr) then - SOURCEINFO(fileName=filename, lineNumberStart=lineStart) := info; - print("\n[" + filename + ":" + String(lineStart) + "]: checkArray failed: arrayLength="+String(arrayLength(arr))+" index=" + String(index) + "\n"); - fail(); - end if; -end checkArray; - -function checkArrayModelica - input Integer arr[:]; - input Integer index; - input SourceInfo info; -protected - String filename; - Integer lineStart; -algorithm - if index<1 or index>size(arr,1) then - SOURCEINFO(fileName=filename, lineNumberStart=lineStart) := info; - print("\n[" + filename + ":" + String(lineStart) + "]: checkArray failed: arrayLength="+String(size(arr,1))+" index=" + String(index) + "\n"); - fail(); - end if; -end checkArrayModelica; - -package LexTable -%LexTable% -end LexTable; - -%epilogue% - -end %LexerCode%; diff --git a/openmodelica/omcc/LexerGenerator.mo b/openmodelica/omcc/LexerGenerator.mo deleted file mode 100644 index a32e3cb4e13..00000000000 --- a/openmodelica/omcc/LexerGenerator.mo +++ /dev/null @@ -1,450 +0,0 @@ -package LexerGenerator - -import System; -constant Boolean debug = true; - -import OMCC.copyright; - -function genLexer - input String flexFile; - input String grammarFile; - input String outFileName; - input String tokens; - output String result; -protected - String flexCode,re,ar1,rest,lexTable; - Boolean res2,res3,res4; - list resultRegex,resTable,chars; -algorithm - //open flex file and validate - - if (outFileName<>"" and stringLength(outFileName)<15) then - if (debug==true) then - print("Generating Lexer from " + flexFile + "\n"); - end if; - - flexCode := System.readFile(flexFile); - - print("Read FLEX grammar file " + flexFile + "\n"); - - lexTable := buildLexTable(flexCode); - - if (debug==true) then - print("Build Lex Table ...\n"); - end if; - - buildLexerCode(flexCode,grammarFile,outFileName,lexTable=lexTable,tokens=tokens); - - if (debug==true) then - print("Build LexerCode ...\n"); - end if; - - result := "Lexer Built"; - else - result := "Invalid language grammar name"; - end if; -end genLexer; - -function readPrologEpilog - input String lexerCode; - input String grammarFileName; - output String lexerCodeIncluded; -protected - String grammarFile,epilog,prolog,re,ar1,astRootType; - Integer numMatches,pos1,pos2; - list resultRegex; -algorithm - if (debug==true) then - print("\nRead epilogue and prologue"); - end if; - grammarFile := System.readFile(grammarFileName); - - //find prologue - - pos1 := System.stringFind(grammarFile,"%{"); - pos2 := System.stringFind(grammarFile,"%}"); - - ar1 := System.substring(grammarFile,pos1+3,pos2-1); - lexerCodeIncluded := System.stringReplace(lexerCode,"%prologue%",ar1); - - // - /* ar1 := System.stringFindString(grammarFile,"AstTree"); - pos1 := System.stringFind(ar1,"="); - pos2 := System.stringFind(ar1,";"); - astRootType := System.substring(ar1,pos1+2,pos2); - astRootType := System.trim(astRootType," "); - parserCodeIncluded := System.stringReplace(parserCodeIncluded,"%astTree%",astRootType); */ - - //find epilogue - re := "%%"; - ar1 := System.stringFindString(grammarFile,re); - ar1 := System.substring(ar1,3,stringLength(ar1)); - ar1 := System.stringFindString(ar1,re); - ar1 := System.substring(ar1,3,stringLength(ar1)); - lexerCodeIncluded := System.stringReplace(lexerCodeIncluded,"%epilogue%",ar1); - -end readPrologEpilog; - -function buildLexerCode - input String flexCode; - input String grammarFile; - input String outFileName; - input String lexTable; - input String tokens; -protected - list resTable; - String lexCode,result,rest,stTime,cp,caseAction,re,tokenName; - Integer i,numMatches,numRules,pos,pos2,posBegin,posReturn,posKeepBuffer,posBreak,valBegin; -algorithm - lexCode := System.readFile("LexerCode.tmo"); - stTime := copyright; - result := System.stringReplace(lexCode, "%LexerCode%", "Lexer"+outFileName); - result := System.stringReplace(result, "%time%", stTime); - result := System.stringReplace(result, "%Tokens%", tokens); - result := System.stringReplace(result, "%LexTable%", lexTable); - result := System.stringReplace(result, "%nameSpan%", "255"); - - result := readPrologEpilog(result,grammarFile); - caseAction := ""; - resTable := {}; - numRules := findValue(flexCode,"YY_NUM_RULES"); - // print("\n new area"); - re := "/* beginning of action switch */"; - rest := System.stringFindString(flexCode,re); - - if (debug==true) then - print("beginning of action switch\n"); - end if; - for i in 1:numRules loop - cp := " case ("; - resTable := cp::resTable; - cp := intString(i); - resTable := cp::resTable; - cp := ") // "; - resTable := cp::resTable; - - re := "case " + intString(i) + ":"; - (numMatches,_::rest::_) := System.regex(flexCode,"case " + intString(i) + ":[^#]*(#[^#]*)YY_BREAK[^#]*",2,extended=true); - if (numMatches < 2) then - print("Failed to find lexer case " + intString(i) + "\n"); - fail(); - end if; - (numMatches,_::tokenName::_) := System.regex(rest,"return *([^;]*);",2,extended=true); -print(intString(i) + " is token " + tokenName + "\n"); - re := "#line"; - pos := System.stringFind(rest,re); - pos2 := System.stringFind(rest,".l"); - cp := substring2(rest,pos+1,pos2+3); - resTable := cp::resTable; - //posReturn,posKeepBuffer,posBreak - posReturn := System.stringFind(rest,"Return "); - posBegin := System.stringFind(rest,"BEGIN"); - posKeepBuffer := System.stringFind(rest,"keepBuffer"); - //print("\n pos:" + intString(pos) + ":" + "pos2:" + intString(pos2) + ":" + "posB:" + intString(posBegin) ); - resTable := "\n equation" :: resTable; - if (posBegin>=0) then // starts BEGIN switch start state - // find token - pos := System.stringFind(rest,"("); - pos2 := System.stringFind(rest,")"); - cp := substring2(rest,pos+2,pos2); - - valBegin := findValue(flexCode,cp); - valBegin := 1+2*valBegin; - if (debug==true) then - print("\n BEGIN at" + intString(valBegin)); - end if; - cp := "\n mm_startSt = " + intString(valBegin) +";"; - resTable := cp::resTable; - end if; - - if (posKeepBuffer>=0) then // starts keepbuffer switch start state - // print keep buffer - if (debug==true) then - print("\n keepbuffer"); - end if; - cp := "\n bufferRet = buffer;"; - resTable := cp::resTable; - end if; - - if tokenName <> "" then - cp := "\n tok = TOKEN(\""; - resTable := tokenName::cp::resTable; - cp := ",fileContents,mm_pos-buffer,buffer,lineNrStart,mm_ePos+1,mm_linenr,mm_sPos+1);\n then tok;\n"; - resTable := cp::tokenName::"\",TokenId."::resTable; - else - //print("NONE"); - cp := "\n then noToken;\n"; - resTable := cp::resTable; - end if; - - end for; - - resTable := listReverse(resTable); - caseAction := stringCharListString(resTable); - - result := System.stringReplace(result,"%caseAction%",caseAction); - System.writeFile("Lexer" + outFileName + ".mo",result); -end buildLexerCode; - -function findValue - input String flexCode; - input String variable; - output Integer value; - -protected - Integer pos; - String rest,val,re; -algorithm - (_,_::val::{}) := System.regex(flexCode,"define " + variable + " ([0-9]*)",2,true,false); - print("\n val is:" +val); - value := stringInt(val); - - print("\n value found"); -end findValue; - -function buildLexTable - input String flexCode; - output String buildResult; -protected - String cp,re,re1,ar1,rest,result,stTime; - Integer numMatches,pos1,pos2,len; - list resultRegex,resTable,chars; - constant String prefixScalar = " constant Integer "; - constant String prefixList = " constant Integer "; - constant String prefixList2 = "[:] = array("; - constant String suffixScalar = ";\n"; - constant String suffixList = ");\n"; -algorithm - stTime := copyright; - - cp := prefixScalar + "yy_limit = "; - - resTable := cp::{}; - - // Insert yy_limit - re := "if ( yy_current_state >= "; - re1 := "if ( yy_current_state >=[^)]*)"; - (numMatches,resultRegex) := System.regex(flexCode,re1,1,false,false); - - ar1::_ := resultRegex; - if (debug==true) then - print("\nFound regex:" + ar1); - end if; - numMatches:=0; - (numMatches,resultRegex) := System.regex("if ( yy_current_state >= 65 )","[0-9]*",2,false,false); - if (debug==true) then - print("\nNumMatches:" + intString(numMatches)); - end if; - cp::_ := resultRegex; - if (debug==true) then - print("\nFound regex2:" + cp); - end if; - - rest := System.stringFindString(flexCode,re); - - pos2 := System.stringFind(rest,")"); - ar1 := substring2(rest,stringLength(re)+1,pos2-1); - resTable := ar1::resTable; - - cp := suffixScalar+prefixScalar+"yy_finish = "; - resTable := cp::resTable; - re := "while ( yy_base[yy_current_state] != "; - rest := System.stringFindString(flexCode,re); - pos2 := System.stringFind(rest,")"); - ar1 := substring2(rest,stringLength(re)+1,pos2-1); - resTable := ar1::resTable; - - cp := suffixScalar+prefixList+"yy_acclist"+prefixList2; - resTable := cp::resTable; - - // match acclist - re := "yy_acclist\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(flexCode,re,1,false,false); - ar1::_ := resultRegex; - if (numMatches > 0) then - pos1 := System.stringFind(ar1,","); - pos2 := System.stringFind(ar1,"}"); - ar1 := substring2(ar1,pos1+2,pos2-1); - else - ar1 := ""; - end if; - resTable := ar1::resTable; - - - cp := suffixList+prefixList+"yy_accept"+prefixList2; - resTable := cp::resTable; - re := "yy_accept\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(flexCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(flexCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring2(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - cp := suffixList+prefixList+"yy_ec"+prefixList2; - resTable := cp::resTable; - //re := "static yyconst int yy_ec"; - re := "yy_ec\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(flexCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(flexCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring2(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - cp := suffixList+prefixList+"yy_meta"+prefixList2; - resTable := cp::resTable; - //re := "static yyconst int yy_meta"; - re := "yy_meta\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(flexCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(flexCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring2(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - cp := suffixList+prefixList+"yy_base"+prefixList2; - resTable := cp::resTable; - - //re := "static yyconst short int yy_base"; - re := "yy_base\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(flexCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(flexCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring2(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - cp := suffixList+prefixList+"yy_def"+prefixList2; - resTable := cp::resTable; - //re := "static yyconst short int yy_def"; - re := "yy_def\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(flexCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(flexCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring2(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - cp := suffixList+prefixList+"yy_nxt"+prefixList2; - resTable := cp::resTable; - //re := "static yyconst short int yy_nxt"; - re := "yy_nxt\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(flexCode,re,1,false,false); - rest::_ := resultRegex; - if (debug==true) then - print("\nREST next" + rest); - end if; - if (numMatches > 0) then - //rest := System.stringFindString(flexCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring2(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - cp := suffixList+prefixList+"yy_chk"+prefixList2; - resTable := cp::resTable; - re := "static yyconst short int yy_chk"; - re := "yy_chk\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(flexCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(flexCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring2(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - - cp := suffixList; - resTable := cp::resTable; - - resTable := listReverse(resTable); - result := stringCharListString(resTable); - buildResult := result; -end buildLexTable; - -public function getCurrentTimeStr " -returns current time in format Www Mmm dd hh:mm:ss yyyy -using the asctime() function in time.h (libc) -" - output String timeStr; - protected - Integer sec, min, hour, mday, mon, year; - algorithm - timeStr := System.getCurrentTimeStr(); - /*(sec, min, hour, mday, mon, year) := System.getCurrentDateTime(); - timeStr := intString(year) + "/" + intString(mon)+ "/" + intString(mday)+ - " " + intString(hour)+ ":" + intString(min) + ":" + intString(sec); */ -end getCurrentTimeStr; - -public function substring2 - input String inString; - input Integer start; - input Integer stop; - output String outString; -protected - list chars, result; - String c; - Integer i; -algorithm - outString := System.substring(inString,start,stop); - /* result :={}; - chars := stringListStringChar(inString); - for i in 1:stop loop - c::chars := chars; - if (i>=start) then - result := c::result; - end if; - end for; - result := listReverse(result); - outString := stringCharListString(result); */ -end substring2; - -function buildTokens - input String flexFile; - output String result; -protected - String cp,re,flexCode,s; - // Integer numMatches=0; - list resTable,tokens,tokens2,tmp; -algorithm - cp := "type TokenId = enumeration(\n "; - resTable := cp::{}; - tokens := {}; - - flexCode := System.readFile(flexFile); - for str in System.strtok(flexCode, "return ") loop - tmp := System.strtok(str,";"); - s := if listEmpty(tmp) then "" else System.trim(listGet(tmp,1)); - if 1==System.regex(s, "^[A-Z_]{2,}$",0,extended=true) then - tokens := s :: tokens; - end if; - end for; - tokens2 := "_NO_TOKEN"::List.sortedUnique(List.sort(tokens, Util.strcmpBool), stringEqual); - // numMatches := listLength(tokens2); - cp := stringDelimitList(tokens2, ",\n "); - resTable := cp::resTable; - cp := "\n);"; - resTable := cp::resTable; - - resTable := listReverse(resTable); - result := stringAppendList(resTable); -end buildTokens; - -end LexerGenerator; diff --git a/openmodelica/omcc/LexerTest.mo b/openmodelica/omcc/LexerTest.mo deleted file mode 100644 index 38fffbcdad5..00000000000 --- a/openmodelica/omcc/LexerTest.mo +++ /dev/null @@ -1,63 +0,0 @@ -encapsulated package LexerTest - -import LexerModelica; -import ParserModelica; -import ParseCodeModelica; - -import System; -import Flags; -import Error; - -public function main -"function: main - This is the main function that the MetaModelica Compiler (MMC) runtime system calls to - start the translation." - input list inStringLst; -protected - list tokens; - type Mcode_MCodeLst = list; -algorithm - _ := matchcontinue (inStringLst) - local - String ver_str,errstr,filename,grammar,ast,unparsed; - list args_1,args,chars; - String s,str; - Boolean runparser,result; - Real tp,tl,tt; - case args as _::_ - equation - {filename} = Flags.new(args); - false=(0==stringLength(filename)); - print("Parsing Modelica with file " + filename + "\n"); - System.realtimeTick(1); - // call the lexer - print("starting lexer\n"); - tokens = LexerModelica.scan(filename); - //print(OMCCTypes.printTokens(tokens,"")); - print("Tokens processed:" + intString(listLength(tokens)) + ", time: " + realString(System.realtimeTock(1)*1000) + "ms\n"); - System.realtimeTick(1); - // call the parser - result = true; - // printing the AST - - if (result) then - print("SUCCEED\n"); - else - fail(); - end if; - then (); - - case {} - equation - print("no args"); - then (); - - case _ - equation - print("\n**********Error*************"); - print("\n" +Error.printMessagesStr()); - then fail(); - end matchcontinue; -end main; - -end LexerTest; diff --git a/openmodelica/omcc/LexerTest.mos b/openmodelica/omcc/LexerTest.mos deleted file mode 100644 index 550c08c7c5b..00000000000 --- a/openmodelica/omcc/LexerTest.mos +++ /dev/null @@ -1,26 +0,0 @@ -setCommandLineOptions({"+g=MetaModelica","+d=rml"}); - -compilerSources := "../../../OMCompiler/Compiler/"; - -loadFiles({compilerSources + f for f in { - "Util/Error.mo", - "Util/ErrorExt.mo", - "FrontEnd/Dump.mo", - "Util/Print.mo", - "Util/Flags.mo", - "Global/Global.mo", - "Util/Config.mo", - "Util/Debug.mo", - "Util/List.mo", - "Util/Settings.mo", - "Util/Corba.mo", - "Util/Util.mo", - "Util/StringUtil.mo", - "Util/System.mo"}}); - -loadFile("LexerModelica.mo"); -loadFile("LexerTest.mo"); -getErrorString(); - -setCFlags(getCFlags() + " -O2 -g -DGENERATE_MAIN_EXECUTABLE "); getErrorString(); -generateCode(LexerTest.main); getErrorString(); diff --git a/openmodelica/omcc/LoadCompilerSources.mos b/openmodelica/omcc/LoadCompilerSources.mos deleted file mode 100644 index f9fd902ab76..00000000000 --- a/openmodelica/omcc/LoadCompilerSources.mos +++ /dev/null @@ -1,35 +0,0 @@ -setCommandLineOptions("+g=MetaModelica"); - -compilerSources := "../../../OMCompiler/Compiler"; -LoadCompilerSourcesRes:=boolAnd(x for x in OpenModelica.Scripting.loadFile({ - "Types.mo", - "Absyn.mo", - compilerSources + "Util/Error.mo", - compilerSources + "Util/ErrorExt.mo", - compilerSources + "FrontEnd/Dump.mo", - compilerSources + "Util/Print.mo", - compilerSources + "Util/Flags.mo", - compilerSources + "Global/Global.mo", - compilerSources + "Util/Config.mo", - compilerSources + "Util/Debug.mo", - compilerSources + "Util/List.mo", - compilerSources + "Util/Settings.mo", - compilerSources + "Util/Corba.mo", - compilerSources + "Util/Flags.mo", - compilerSources + "Util/Util.mo", - compilerSources + "Util/System.mo", - "TokenModelica.mo", - "LexTableModelica.mo", - "LexerCodeModelica.mo", - "LexerModelica.mo", - "ParseCodeModelica.mo", - "ParserModelica.mo", - "ParseTableModelica.mo", - "Main.mo" -})); - -if not LoadCompilerSourcesRes then - print("Failed to load compiler sources:\n"); - print(getErrorString()); - exit(1); -end if; diff --git a/openmodelica/omcc/Main.mo b/openmodelica/omcc/Main.mo deleted file mode 100644 index 711974acf2b..00000000000 --- a/openmodelica/omcc/Main.mo +++ /dev/null @@ -1,89 +0,0 @@ -encapsulated package Main - -import LexerModelica; -import ParserModelica; -import ParseCodeModelica; - -import Absyn; -import Util; -import RTOpts; -import System; -import Types; -import OMCCTypes; -import Flags; -import Error; - -public function main -"function: main - This is the main function that the MetaModelica Compiler (MMC) runtime system calls to - start the translation." - input list inStringLst; -protected - list tokens; - type Mcode_MCodeLst = list; -algorithm - _ := matchcontinue (inStringLst) - local - String ver_str,errstr,filename,grammar,ast,unparsed; - list args_1,args,chars; - String s,str; - Boolean runparser,result; - Real tp,tl,tt; - case args as _::_ - equation - {filename,grammar} = Flags.new(args); - runparser = match grammar - case "Modelica" then true; - case "ModelicaLexer" then false; - else equation print("Unknown grammar:" + grammar + "\n"); then fail(); - end match; - false=(0==stringLength(filename)); - print("Parsing Modelica with file " + filename + "\n"); - System.realtimeTick(1); - // call the lexer - print("starting lexer\n"); - tokens = LexerModelica.scan(filename); - //print(OMCCTypes.printTokens(tokens,"")); - print("Tokens processed:" + intString(listLength(tokens)) + ", time: " + realString(System.realtimeTock(1)*1000) + "ms\n"); - System.realtimeTick(1); - // call the parser - if runparser then - print("starting parser\n"); - (result,ParseCodeModelica.PROGRAM(astTreeModelica)) = ParserModelica.parse(tokens,filename); - print("Parser done in time: " + realString(System.realtimeTock(1)*1000) + "ms\n"); - else - result = true; - end if; - // printing the AST - - if (result) then - print("SUCCEED\n"); - else - fail(); - end if; - then (); - - case {} - equation - print("no args"); - printUsage(); - then (); - - case _ - equation - print("\n**********Error*************"); - print("\n" +Error.printMessagesStr()); - printUsage(); - then fail(); - end matchcontinue; -end main; - -public function printUsage -protected - Integer n; - List strs; -algorithm - print("\nOMCCp v0.9.2 (OpenModelica compiler-compiler Parser generator) Lexer and Parser Generator-2012\n\n"); -end printUsage; - -end Main; diff --git a/openmodelica/omcc/Makefile b/openmodelica/omcc/Makefile deleted file mode 100644 index 89672410d7a..00000000000 --- a/openmodelica/omcc/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -OMC=../../../build/bin/omc - -default: parser - -all: $(GEN_FILES) - -LexerModelica.mo: OMCC.mos lexerModelica.l parserModelica.y LexerGenerator.mo ParserGenerator.mo OMCC.mo LexerCode.tmo ParseCode.tmo OMCCBaseLexer.mo OMCCTypes.mo Parser.mo - $(OMC) $< - -omcc: - rm -f OMCC_main.makefile - $(OMC) OMCC.mos - $(MAKE) -f OMCC_main.makefile MODELICAUSERCFLAGS='-DGENERATE_MAIN_EXECUTABLE -Os' - $(CC) -o OMCC OMCC_main.so '-Wl,-rpath,$$ORIGIN' - -Main_main.so: GenerateParser.mos $(GEN_FILES) Main.mo - @rm -f $@ - $(OMC) $< - -parser: Main_main.so - $(CC) -g -O2 -o $@ $< '-Wl,-rpath,$$ORIGIN' - -parser-all: omcc - ./OMCC Modelica - $(MAKE) parser - -lexer: LexerTest_main.so - $(CC) -g -O2 -o $@ $< '-Wl,-rpath,$$ORIGIN' - -LexerTest_main.so: LexerTest.mos LexerTest.mo LexerModelica.mo - rm -f LexerTest_main.makefile - $(OMC) $< - $(MAKE) -f LexerTest_main.makefile -lexer-all: omcc - ./OMCC --lexer-only Modelica - $(MAKE) lexer - -.PHONY: ModelicaParserTests - -TESTREV=541706f5c8c40a4ab61a5739e294e3d4b6f8696d - -ModelicaParserTests: - @test -d ModelicaParserTests || git clone https://github.com/OpenModelica/ModelicaParserTests - @cd ModelicaParserTests && (git checkout -q $(TESTREV) || (git fetch && git checkout $(TESTREV))) - -FAIL=$(wildcard ModelicaParserTests/should_fail/*.mo) -WORK=$(wildcard ModelicaParserTests/should_work/*.mo) - -test: ModelicaParserTests - $(MAKE) test-internal -test-internal: $(FAIL:%.mo=%.testfail) $(WORK:%.mo=%.testsuccess) - -%.testfail: %.mo - @echo "$<" | sed "s,.*/,Parsing ," - @! ./parser "$<" Modelica > /dev/null 2>&1 -%.testsuccess: %.mo - @echo "$<" | sed "s,.*/,Parsing ," - @./parser "$<" Modelica > /dev/null 2>&1 diff --git a/openmodelica/omcc/OMCC.mo b/openmodelica/omcc/OMCC.mo deleted file mode 100644 index 37974b1f221..00000000000 --- a/openmodelica/omcc/OMCC.mo +++ /dev/null @@ -1,62 +0,0 @@ -class OMCC - -import Util; -import RTOpts; -import System; -import Absyn; -import LexerGenerator; -import ParserGenerator; -import OpenModelicaSettings; -constant String copyright = "OMCCp v0.11.0 OpenModelica lexer and parser generator (2015)"; - -public function main -"function: main -This is the main function that the MetaModelica Compiler (MMC) runtime system calls to -start the translation." - input list inStringLst; -algorithm - _ := matchcontinue (inStringLst) - local - String ver_str,errstr,filename,parser,ast; - list args_1,args,chars; - String str,omhome,oldpath,newpath,tokens; - Boolean result; - case "--lexer-only" :: args - equation - {parser} = Flags.new(args); - print("Generating FLEX grammar file lexer" + parser +".c ...\n"); - 0 = System.systemCall(OpenModelicaSettings.OPENMODELICAHOME + "/bin/flex -t -l lexer" + parser +".l > lexer" + parser +".c"); - tokens = LexerGenerator.buildTokens("lexer"+ parser +".l"); - str = LexerGenerator.genLexer("lexer"+ parser +".c", "lexer"+ parser +".l", parser, tokens=tokens); - print("Result:" + str + "\n"); - print("\nGenerated files:\n" + sum(" " + s + parser +".mo\n" for s in {"Lexer"})); - then (); - case args as _::_ - equation - {parser} = Flags.new(args); - print("Generating FLEX grammar file lexer" + parser +".c ...\n"); - 0 = System.systemCall(OpenModelicaSettings.OPENMODELICAHOME + "/bin/flex -t -l lexer" + parser +".l > lexer" + parser +".c"); - print("Generating BISON grammar file parser" + parser +".c ...\n"); - 0 = System.systemCall("bison parser" + parser +".y --output=parser" + parser +".c"); - tokens = ParserGenerator.buildTokens("parser"+ parser +".c"); - str = LexerGenerator.genLexer("lexer"+ parser +".c", "lexer"+ parser +".l", parser, tokens=tokens); - print("Result:" + str + "\n"); - str = ParserGenerator.genParser("parser"+ parser +".c","parser"+ parser +".y",parser); - print("Result:" + str + "\n"); - - print("\n 9 Files Generated for the language grammar:" + parser); - then (); - case _ - equation - print("\n**********Error*************"); - printUsage(); - then fail(); - end matchcontinue; -end main; - -public function printUsage -algorithm - print("\n" + copyright + "\n"); -end printUsage; - -end OMCC; diff --git a/openmodelica/omcc/OMCC.mos b/openmodelica/omcc/OMCC.mos deleted file mode 100644 index aa94fa62488..00000000000 --- a/openmodelica/omcc/OMCC.mos +++ /dev/null @@ -1,36 +0,0 @@ -OpenModelica.Scripting.setCFlags("-g " + getCFlags());getErrorString(); -compilerSources := "../../../OMCompiler/Compiler/"; -files := { - "OMCC.mo", - compilerSources + "/Util/List.mo", - compilerSources + "/Util/Config.mo", - compilerSources + "/Global/Global.mo", - compilerSources + "/Util/Debug.mo", - compilerSources + "/Util/ErrorExt.mo", - compilerSources + "/Util/Error.mo", - compilerSources + "/Util/Print.mo", - compilerSources + "/Util/Corba.mo", - compilerSources + "/Util/Settings.mo", - compilerSources + "/Util/Flags.mo", - compilerSources + "/Util/Util.mo", - compilerSources + "/Util/StringUtil.mo", - compilerSources + "/Util/System.mo", - "LexerGenerator.mo", - "ParserGenerator.mo"};getErrorString(); -setCommandLineOptions({"+g=MetaModelica","+d=rml"}); -res:=loadFile(files); -if min(res) == false then - print(getErrorString()); - exit(1); -end if; -getErrorString(); -loadString("package OpenModelicaSettings - constant String OPENMODELICAHOME = \""+getInstallationDirectoryPath()+"\"; -end OpenModelicaSettings;"); -// OMCC.main({"Modelica"});getErrorString(); -if not generateCode(OMCC.main) then - print(getErrorString()); - exit(1); -else - print(getErrorString()); -end if; diff --git a/openmodelica/omcc/OMCCBaseLexer.mo b/openmodelica/omcc/OMCCBaseLexer.mo deleted file mode 100644 index 00e7cdecfe5..00000000000 --- a/openmodelica/omcc/OMCCBaseLexer.mo +++ /dev/null @@ -1,448 +0,0 @@ -encapsulated partial package OMCCBaseLexer "Implements the DFA of OMCC" - -import System; - -import arrayGet = MetaModelica.Dangerous.arrayGetNoBoundsChecking; // Bounds checked with debug=true -import stringGet = MetaModelica.Dangerous.stringGetNoBoundsChecking; -import MetaModelica.Dangerous.listReverseInPlace; - -constant Boolean debug = false; - -replaceable package LexTable - constant Integer yy_limit; - constant Integer yy_finish; - constant Integer yy_acclist[:]; - constant Integer yy_accept[:]; - constant Integer yy_ec[:]; - constant Integer yy_meta[:]; - constant Integer yy_base[:]; - constant Integer yy_def[:]; - constant Integer yy_nxt[:]; - constant Integer yy_chk[:]; -end LexTable; - -replaceable partial function action - input Integer act; - input Integer startSt; - input Integer mm_currSt,mm_pos,mm_sPos,mm_ePos,mm_linenr,lineNrStart; - input Integer buffer; - input Boolean debug; - input String fileNm; - input String fileContents; - output Token.Token token; - output Integer mm_startSt; - output Integer bufferRet; -end action; - -function scan "Scan starts the lexical analysis, load the tables and consume the program to output the tokens" - input String fileName "input source code file"; - output list tokens "return list of tokens"; -protected - String contents; -algorithm - contents := loadSourceCode(fileName); - tokens := lex(fileName,contents); -end scan; - -function scanString "Scan starts the lexical analysis, load the tables and consume the program to output the tokens" - input String fileSource "input source code file"; - output list tokens "return list of tokens"; -algorithm - tokens := lex("",fileSource); -end scanString; - -protected - -function loadSourceCode - input String fileName "input source code file"; - output String contents; -algorithm - System.realtimeTick(2); - contents := System.readFile(fileName); - print("loadSourceCode finished in: " + realString(System.realtimeTock(2)*1000) + "ms\n"); -end loadSourceCode; - -function lex "Scan starts the lexical analysis, load the tables and consume the program to output the tokens" - input String fileName "input source code file"; - input String contents; - output list tokens "return list of tokens"; -protected - Integer startSt,numStates,i,r,cTok,cTok2,currSt,pos,sPos,ePos,linenr,contentLen,numBacktrack,buffer,lineNrStart; - list cProg,cProg2; - list chars; - array states; - String s1,s2; -algorithm - // load arrays - - // Initialize the Env Variables - startSt := 1; - currSt := 1; - pos := 1; - sPos := 0; - ePos := 0; - linenr := 1; - lineNrStart := 1; - buffer := 0; - // TODO: All - states := arrayCreate(128,1); - numStates := 1; - - if (debug==true) then - print("\nLexer analyzer LexerCode..." + fileName + "\n"); - //printAny("\nLexer analyzer LexerCode..." + fileName + "\n"); - end if; - - tokens := {}; - if (debug) then - print("\n TOTAL Chars:"); - print(intString(stringLength(contents))); - end if; - contentLen := stringLength(contents); - i := 1; - while i <= contentLen loop - cTok := stringGet(contents,i); - (tokens,numBacktrack,startSt,currSt,pos,sPos,ePos,linenr,lineNrStart,buffer,states,numStates) := consume(cTok,tokens,contents,startSt,currSt,pos,sPos,ePos,linenr,lineNrStart,buffer,states,numStates,fileName); - i := i - numBacktrack + 1; - end while; - tokens := listReverseInPlace(tokens); -end lex; - -function consume - input Integer cp; - input list tokens; - input String fileContents; - input Integer startSt; - input Integer currSt,pos,sPos,ePos,linenr,inLineNrStart; - input Integer inBuffer; - input array inStates; - input Integer inNumStates; - input String fileName; - output list resToken; - output Integer bkBuffer = 0; - output Integer mm_startSt; - output Integer mm_currSt,mm_pos,mm_sPos,mm_ePos,mm_linenr,lineNrStart; - output Integer buffer; - output array states; - output Integer numStates; -protected - Token.Token tok; - Integer act,buffer2; - Integer c,baseCond; -algorithm - mm_startSt := startSt; - mm_currSt := currSt; - mm_pos := pos; - mm_sPos := sPos; - mm_ePos := ePos; - mm_linenr := linenr; - lineNrStart := inLineNrStart; - buffer := inBuffer; - states := inStates; - numStates := inNumStates; - - baseCond := LexTable.yy_base[mm_currSt]; - if (debug==true) then - print("\nPROGRAM:{" + intString(cp) + "} "); - print("\nBUFFER:{" + intString(buffer) + "} "); - print("base:" + intString(baseCond) + " st:" + intString(mm_currSt)+" "); - end if; - - buffer := buffer+1; - mm_pos := mm_pos+1; - - if (cp==10) then - mm_linenr := mm_linenr+1; - mm_sPos := 0; - else - mm_sPos := mm_sPos+1; - end if; - if (debug==true) then - print("\n[Reading:'" + intStringChar(cp) +"' at p:" + intString(mm_pos-1) + " line:"+ intString(mm_linenr) + " rPos:" + intString(mm_sPos) +"]"); - end if; - c := LexTable.yy_ec[cp]; - - if (debug==true) then - print(" evalState Before[c" + intString(c) + ",s"+ intString(mm_currSt)+"]"); - end if; - (mm_currSt,c) := evalState(mm_currSt,c); - if (debug==true) then - print(" After[c" + intString(c) + ",s"+ intString(mm_currSt)+"]"); - end if; - if (mm_currSt>0) then - mm_currSt := LexTable.yy_base[mm_currSt]; - // print("BASE:"+ intString(mm_currSt)+"]"); - mm_currSt := LexTable.yy_nxt[mm_currSt + c]; - // print("NEXT:"+ intString(mm_currSt)+"]"); - else - mm_currSt := LexTable.yy_nxt[c]; - end if; - numStates := numStates+1; // TODO: BAD BAD BAD. At least arrayUpdate should be a safe operation... We need to grow the number of states on demand though. - arrayUpdate(states,numStates,mm_currSt); - // printAny(states); - // print("[c" + intString(c) + ",s"+ intString(mm_currSt)+"]"); - // print("[B:" + intString(arrayGet(mm_base,mm_currSt))+"]"); - - baseCond := LexTable.yy_base[mm_currSt]; - if (baseCond==LexTable.yy_finish) then - if (debug==true) then - print("\n[RESTORE=" + intString(LexTable.yy_accept[mm_currSt]) + "]"); - end if; - - (act, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates) := findRule(fileContents, mm_currSt, mm_pos, mm_sPos, mm_ePos, mm_linenr, buffer, bkBuffer, states, numStates); - - if (debug==true) then - print("\nFound rule: " + String(act)); - end if; - - (tok,mm_startSt,buffer2) := action(act,mm_startSt,mm_currSt,mm_pos,mm_sPos,mm_ePos,mm_linenr,lineNrStart,buffer,debug,fileName,fileContents); - - if (debug==true) then - print("\nDid action"); - end if; - - mm_currSt := mm_startSt; - arrayUpdate(states,1,mm_startSt); - numStates := 1; - - /* Either a token was output (get new positions for next token). Or a whitespace was emitted. */ - if buffer <> buffer2 then - mm_ePos := mm_sPos; - lineNrStart := linenr; - end if; - buffer := buffer2; - - resToken := match tok - case Token.TOKEN(id=-1) then tokens; - else tok::tokens; - end match; - if(debug) then - print("\n CountTokens:" + intString(listLength(resToken))); - end if; - else - bkBuffer := 0; // consume the character - resToken := tokens; - end if; - -end consume; - - -function findRule - input String fileContents; - input Integer currSt; - input Integer pos; - input Integer sPos; - input Integer mm_ePos; - input Integer linenr; - input Integer inBuffer; - input Integer inBkBuffer; - input array inStates; - input Integer inNumStates; - output Integer action; - output Integer mm_currSt; - output Integer mm_pos; - output Integer mm_sPos; - output Integer mm_linenr; - output Integer buffer; - output Integer bkBuffer; - output array states; - output Integer numStates; -protected - array mm_accept,mm_ec,mm_meta,mm_base,mm_def,mm_nxt,mm_chk,mm_acclist; - Integer lp,lp1,stCmp; - Boolean st; -algorithm - mm_currSt := currSt; - mm_pos := pos; - mm_sPos := sPos; - mm_linenr := linenr; - buffer := inBuffer; - bkBuffer := inBkBuffer; - states := inStates; - numStates := inNumStates; - - stCmp := arrayGet(states,numStates); - lp := LexTable.yy_accept[stCmp]; - lp1 := LexTable.yy_accept[stCmp+1]; - - st := intGt(lp,0) and intLt(lp,lp1); - (action, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates) := match(numStates,st) - local - Integer act,cp; - list restBuff; - case (_,true) - algorithm - if debug then - checkArrayModelica(LexTable.yy_accept,stCmp,sourceInfo()); - checkArrayModelica(LexTable.yy_acclist,lp,sourceInfo()); - end if; - lp := LexTable.yy_accept[stCmp]; - act := LexTable.yy_acclist[lp]; - then (act, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates); - case (_,false) - algorithm - cp := stringGet(fileContents,mm_pos-1); - buffer := buffer-1; - bkBuffer := bkBuffer+1; - mm_pos := mm_pos - 1; - mm_sPos := mm_sPos -1; - if (cp==10) then - mm_sPos := mm_ePos; - mm_linenr := mm_linenr-1; - end if; - if debug then - checkArray(states,numStates,sourceInfo()); - end if; - mm_currSt := arrayGet(states,numStates); - numStates := numStates - 1; - (act, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates) := findRule(fileContents, mm_currSt, mm_pos, mm_sPos, mm_ePos, mm_linenr, buffer, bkBuffer, states, numStates); - then (act, mm_currSt, mm_pos, mm_sPos, mm_linenr, buffer, bkBuffer, states, numStates); - - end match; -end findRule; - -function evalState - input Integer cState; - input Integer c; - output Integer new_state; - output Integer new_c; -protected - Integer cState1=cState; - Integer c1=c; - Integer val,val2,chk; -algorithm - chk := LexTable.yy_base[cState1]; - chk := chk + c1; - val := LexTable.yy_chk[chk]; - val2 := LexTable.yy_base[cState1] + c1; - // print("{val2=" + intString(val2) + "}\n"); - (new_state,new_c) := match (cState1==val) - local - Integer s,c2; - case (true) - then (cState1,c1); - case (false) - algorithm - cState1 := LexTable.yy_def[cState1]; - //print("[newS:" + intString(cState)+"]"); - //c2 = c; - if ( cState1 >= LexTable.yy_limit ) then - c1 := LexTable.yy_meta[c1]; - // print("META[c:" + intString(c)+"]"); - end if; - if (cState1>0) then - (cState1,c1) := evalState(cState1,c1); - end if; - then (cState1,c1); - end match; - -end evalState; - -function getInfo - input Integer len; - input Integer sPos; - input Integer ePos; - input Integer lineNrStart; - input Integer mm_linenr; - input String programName; - output SourceInfo info; -protected - Integer mm_sPos; - Integer c; -algorithm - info := SOURCEINFO(programName,false,lineNrStart,ePos+1,mm_linenr /* flineNr */, sPos+1 /* frPos+1 */,Absyn.dummyTimeStamp); -end getInfo; - -function printBuffer2 - input list inList; - input String cBuff; - output String outList; -protected - list inList1=inList; - String cBuff1=cBuff; -algorithm - (outList) := match(inList,cBuff) - local - Integer c; - String new,tout; - list rest; - case ({},_) - then (cBuff1); - else - algorithm - c::rest := inList1; - new := cBuff1 + intStringChar(c); - (tout) := printBuffer2(rest,new); - then (tout); - end match; -end printBuffer2; - -function printBuffer - input list inList; - output String outList; -protected - list inList1=inList; - Integer c; -algorithm - outList := ""; - while (listEmpty(inList1)==false) loop - c::inList1 := inList1; - outList := outList + intStringChar(c); - end while; -end printBuffer; - -function printStack - input list inList; - input String cBuff; - output String outList; -protected - list inList1=inList; - String cBuff1=cBuff; -algorithm - (outList) := match(inList,cBuff) - local - Integer c; - String new,tout; - list rest; - case ({},_) - then (cBuff1); - else - algorithm - c::rest := inList1; - new := cBuff1 + "|" + intString(c); - (tout) := printStack(rest,new); - then (tout); - end match; -end printStack; - -function checkArray - input array arr; - input Integer index; - input SourceInfo info; -protected - String filename; - Integer lineStart; -algorithm - if index<1 or index>arrayLength(arr) then - SOURCEINFO(fileName=filename, lineNumberStart=lineStart) := info; - print("\n[" + filename + ":" + String(lineStart) + "]: checkArray failed: arrayLength="+String(arrayLength(arr))+" index=" + String(index) + "\n"); - fail(); - end if; -end checkArray; - -function checkArrayModelica - input Integer arr[:]; - input Integer index; - input SourceInfo info; -protected - String filename; - Integer lineStart; -algorithm - if index<1 or index>size(arr,1) then - SOURCEINFO(fileName=filename, lineNumberStart=lineStart) := info; - print("\n[" + filename + ":" + String(lineStart) + "]: checkArray failed: arrayLength="+String(size(arr,1))+" index=" + String(index) + "\n"); - fail(); - end if; -end checkArrayModelica; - -end OMCCBaseLexer; diff --git a/openmodelica/omcc/OMCCTypes.mo b/openmodelica/omcc/OMCCTypes.mo deleted file mode 100644 index c755da62962..00000000000 --- a/openmodelica/omcc/OMCCTypes.mo +++ /dev/null @@ -1,70 +0,0 @@ -encapsulated package OMCCTypes - -replaceable type TokenType = Integer; -replaceable constant TokenType noTokenConst = -1; - -uniontype Token - record TOKEN - String name; - TokenType id; // Is Integer for Bison, enumeration for pure flex - String fileContents; - Integer byteOffset,length; - Integer lineNumberStart; - Integer columnNumberStart; - Integer lineNumberEnd; - Integer columnNumberEnd; - end TOKEN; -end Token; - -constant Token noToken = TOKEN("",noTokenConst,"",0,0,0,0,0,0); - -function printToken - input Token token; - output String strTk; -protected - String tokName,contents; - Integer idtk,lns,cns,lne,cne,byteOffset,length; -algorithm - TOKEN(name=tokName,id=idtk,lineNumberStart=lns,columnNumberStart=cns,lineNumberEnd=lne,columnNumberEnd=cne) := token; - contents := getStringValue(token); - strTk := "[TOKEN:" + tokName + " '" + contents + "' (" + intString(lns) + ":" + intString(cns) + "-"+ intString(lne) + ":" + intString(cne) +")]"; -end printToken; - -function makeInfo - input Token tok; - input String fileName; - output Info info; -protected - Integer lns,cns,lne,cne; -algorithm - TOKEN(lineNumberStart=lns,columnNumberStart=cns,lineNumberEnd=lne,columnNumberEnd=cne) := tok; - info := SOURCEINFO(fileName,false,lns,cns,lne,cne,Absyn.dummyTimeStamp); -end makeInfo; - -function getStringValue - input Token tok; - output String str; -protected - String contents; - Integer byteOffset,length; -algorithm - TOKEN(fileContents=contents,byteOffset=byteOffset,length=length) := tok; - str := if length>0 then substring(contents,byteOffset,byteOffset+length-1) else ""; -end getStringValue; - -function getMergeTokenValue - input Token token1; - input Token token2; - output String value; -algorithm - value := getStringValue(token1) + getStringValue(token2); -end getMergeTokenValue; - -function printShortToken - input Token token; - output String strTk; -algorithm - strTk := "'" + getStringValue(token) +"'"; -end printShortToken; - -end OMCCTypes; diff --git a/openmodelica/omcc/ParseCode.tmo b/openmodelica/omcc/ParseCode.tmo deleted file mode 100644 index 5cc2f6d3912..00000000000 --- a/openmodelica/omcc/ParseCode.tmo +++ /dev/null @@ -1,132 +0,0 @@ -encapsulated package %ParseCode% // %time% -import Types; - -constant Boolean debug = false; -// Note: AstItem must be defined, and TOKEN(someToken) must return a valid AstItem (usually a record in the uniontype) - -%prologue% - -uniontype AstStack - record ASTSTACK - list stackToken; - list stack; - end ASTSTACK; -end AstStack; - -function initAstStack - output AstStack astStack; - algorithm - astStack := ASTSTACK({},{}); -end initAstStack; - -function actionRed - input Integer act; - input AstStack astStack; - input String fileName; - output AstStack outStack; - output Boolean error=false; - output String errorMsg=""; -protected - list stackToken; - list stack; - AstItem yyval; -algorithm - ASTSTACK(stackToken=stackToken,stack=stack) := astStack; - if debug then - print("reduce: " + intString(act) + ", " + intString(listLength(stack)) + " on stack with top token ctor " + intString(valueConstructor(listGet(stackToken,1))) + "\n"); - end if; - _ := match act - local - //local variables -%caseAction% - else - equation - error = true; - then (); - end match; - if debug then - print("reduce: " + intString(act) + " to " + intString(listLength(stack)) + " on stack\n"); - end if; - outStack := ASTSTACK(stackToken=stackToken,stack=stack); -end actionRed; - -function mergeStackTokens - input list skToken; - input Integer nTokens(min=2); - output list skTokenRes; -protected - list skToken1:=skToken; - OMCCTypes.Token token; - SourceInfo tmpInfo; - Integer lns,cns,lne,cne,i; - String fn; -algorithm - for i in 1:nTokens loop - token::skToken1 := skToken1; - if (i==nTokens) then - OMCCTypes.TOKEN(lineNumberStart=lns,columnNumberStart=cns) := token; - end if; - if (i==1) then - OMCCTypes.TOKEN(lineNumberEnd=lne,columnNumberEnd=cne) := token; - end if; - end for; - // TODO: merge the contents also? - token := OMCCTypes.TOKEN("grouped token",0,"",0,0,lns,cns,lne,cne); - skTokenRes := token::skToken1; -end mergeStackTokens; - -function push - input AstStack astStk; - input OMCCTypes.Token token; - output AstStack astStk2; -protected - list stackToken; - list stack; -algorithm - ASTSTACK(stackToken=stackToken,stack=stack) := astStk; - stackToken := token::stackToken; - stack := TOKEN(token)::stack; - astStk2 := ASTSTACK(stackToken=stackToken,stack=stack); -end push; - -/* TODO: Add these. - -function makeInfo - input Token tok; - input String fileName; - output Info info; -protected - Integer lns,cns,lne,cne; -algorithm - TOKEN(lineNumberStart=lns,columnNumberStart=cns,lineNumberEnd=lne,columnNumberEnd=cne) := tok; - info := SOURCEINFO(fileName,false,lns,cns,lne,cne,Absyn.dummyTimeStamp); -end makeInfo; - -function getMergeTokenValue - input Token token1; - input Token token2; - output String value; -algorithm - value := getStringValue(token1) + getStringValue(token2); -end getMergeTokenValue; - -function getInfo - input Integer len; - input Integer sPos; - input Integer ePos; - input Integer lineNrStart; - input Integer mm_linenr; - input String programName; - output SourceInfo info; -protected - Integer mm_sPos; - Integer c; -algorithm - info := SOURCEINFO(programName,false,lineNrStart,ePos+1,mm_linenr /* flineNr */, sPos+1 /* frPos+1 */,Absyn.dummyTimeStamp); -end getInfo; - -*/ - -%epilogue% - -end %ParseCode%; diff --git a/openmodelica/omcc/Parser.mo b/openmodelica/omcc/Parser.mo deleted file mode 100644 index 8d5e42fe4c8..00000000000 --- a/openmodelica/omcc/Parser.mo +++ /dev/null @@ -1,906 +0,0 @@ -encapsulated package Parser -import Types; -import Absyn; -import Error; -import OMCCTypes; -import List; -import LexerModelica; -import ParseCode; -import ParseTable; -import System; - -import arrayGet = MetaModelica.Dangerous.arrayGetNoBoundsChecking; - -constant Boolean debug = false; - -uniontype Env - record ENV - OMCCTypes.Token crTk,lookAhTk; - list state; - list errMessages; - Integer errStatus,sState,cState; - list program,progBk; - list stateBackup; - ParseCode.AstStack astStackBackup; - end ENV; -end Env; - -uniontype ParseData - record PARSE_TABLE - array translate; - array prhs; - array rhs; - array rline; - array tname; - array toknum; - array r1; - array r2; - array defact; - array defgoto; - array pact; - array pgoto; - array table; - array check; - array stos; // to be replaced - String fileName; - end PARSE_TABLE; -end ParseData; - - /* when the error is positive the parser runs in recovery mode, - if the error is negative, the parser runs in testing candidate mode - if the error is cero, then no error is present or has been recovered - The error value decreases with each shifted token */ -constant Integer maxErrShiftToken = 3; -constant Integer maxCandidateTokens = 4; -constant Integer maxErrRecShift = -5; - -constant Integer ERR_TYPE_DELETE = 1; -constant Integer ERR_TYPE_INSERT = 2; -constant Integer ERR_TYPE_REPLACE = 3; -constant Integer ERR_TYPE_INSEND = 4; -constant Integer ERR_TYPE_MERGE = 5; - -type AstTree = ParseCode.AstTree; - -function parse "realize the syntax analysis over the list of tokens and generates the AST tree" - input list tokens "list of tokens from the lexer"; - input String fileName "file name of the source code"; - output Boolean result "result of the parsing"; - output ParseCode.AstItem ast "AST tree that is returned when the result output is true"; -protected - list tokens1:=tokens; - array mm_tname; - array mm_translate, mm_prhs, mm_rhs, mm_rline, mm_toknum, mm_r1, mm_r2, mm_defact, mm_defgoto, - mm_pact, mm_pgoto, mm_table, mm_check, mm_stos; - ParseData pt; - Env env; - OMCCTypes.Token emptyTok; - OMCCTypes.Token emptyTok1:=emptyTok; - ParseCode.AstStack astStk; - - list rToks; - list stateStk; - list errStk; - //Boolean result; -algorithm - - if (debug) then - print("\nParsing tokens ParseCode ..." + fileName + "\n"); - end if; - mm_translate := listArray(ParseTable.yytranslate); - mm_prhs := listArray(ParseTable.yyprhs); - mm_rhs := listArray(ParseTable.yyrhs); - mm_rline := listArray(ParseTable.yyrline); - mm_tname := listArray(ParseTable.yytname); - mm_toknum := listArray(ParseTable.yytoknum); - mm_r1 := listArray(ParseTable.yyr1); - mm_r2 := listArray(ParseTable.yyr2); - mm_defact := listArray(ParseTable.yydefact); - mm_defgoto := listArray(ParseTable.yydefgoto); - mm_pact := listArray(ParseTable.yypact); - mm_pgoto := listArray(ParseTable.yypgoto); - mm_table := listArray(ParseTable.yytable); - mm_check := listArray(ParseTable.yycheck); - mm_stos := listArray(ParseTable.yystos); - - pt := PARSE_TABLE(mm_translate,mm_prhs,mm_rhs,mm_rline,mm_tname,mm_toknum,mm_r1,mm_r2 - ,mm_defact,mm_defgoto,mm_pact,mm_pgoto,mm_table,mm_check,mm_stos,fileName); - stateStk := {0}; - errStk := {}; - astStk := ParseCode.initAstStack(); - env := ENV(emptyTok1,emptyTok1,stateStk,errStk,0,0,0,tokens,{},stateStk,astStk); - - - while (List.isEmpty(tokens1)==false) loop - if (debug) then - print("\nTokens remaining:"); - print(intString(listLength(tokens1))); - end if; - // printAny("\nTokens remaining:"); - // printAny(intString(listLength(tokens))); - (tokens1,env,astStk,result) := processToken(tokens1,env,astStk,pt); - if (result==false) then - break; - end if; - end while; - - ParseCode.ASTSTACK(stack={ast}) := astStk; - - if (debug) then - printAny(ast); - end if; - - /*if (result==true) then - print("\n SUCCEED - (AST)"); - else - print("\n FAILED PARSING"); - end if;*/ -end parse; - -function addSourceMessage - input list errStk; - input OMCCTypes.Info info; -algorithm - Error.addSourceMessage(Error.COMPILER_ERROR,errStk,info); - //print(printSemStack(listReverse(errStk),"")); -end addSourceMessage; - -function printErrorMessages - input list errStk; -algorithm - // print("\n ***ERROR(S) FOUND*** "); - // print(printSemStack(listReverse(errStk),"")); -end printErrorMessages; - -function processToken - input list tokens; - input Env env; - input ParseCode.AstStack inAstStk; - input ParseData pt; - output list rTokens; - output Env env2; - output ParseCode.AstStack astStk := inAstStk; - output Boolean result; -protected - list tokens1:=tokens; - list tempTokens; - // parse tables - array mm_tname; - array mm_translate, mm_prhs, mm_rhs, mm_rline, mm_toknum, mm_r1, mm_r2, mm_defact, mm_defgoto, - mm_pact, mm_pgoto, mm_table, mm_check, mm_stos; - // env variables - OMCCTypes.Token cTok,nTk; - ParseCode.AstStack astSkBk; - list stateStk,stateSkBk; - list errStk; - String astTmp; - Integer sSt,cSt,lSt,errSt,cFinal,cPactNinf,cTableNinf; - list prog,prgBk; -algorithm - PARSE_TABLE(translate=mm_translate,prhs=mm_prhs,rhs=mm_rhs,rline=mm_rline,tname=mm_tname,toknum=mm_toknum,r1=mm_r1,r2=mm_r2 - ,defact=mm_defact,defgoto=mm_defgoto,pact=mm_pact,pgoto=mm_pgoto,table=mm_table,check=mm_check,stos=mm_stos) := pt; - - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk,errMessages=errStk,errStatus=errSt, - sState=sSt,cState=cSt,program=prog,progBk=prgBk,stateBackup=stateSkBk,astStackBackup=astSkBk):= env; - if (debug) then - print("\n[State:" + intString(cSt) +"]{" + printStack(stateStk,"") + "}\n"); - end if; - - // Start the LALR(1) Parsing - cFinal := ParseTable.YYFINAL; - cPactNinf := ParseTable.YYPACT_NINF; - cTableNinf := ParseTable.YYTABLE_NINF; - prog := tokens1; - // cFinal==cSt is a final state? then ACCEPT - // mm_pact[cSt]==cPactNinf if this REDUCE or ERROR - result := true; - env2 := env; - (rTokens,result) := match (tokens,pt,cFinal==cSt,arrayGet(mm_pact,cSt+1)==cPactNinf) - local - list rest; - list vl; - OMCCTypes.Token c =cTok; - OMCCTypes.Token nt =nTk; - Integer n,len,val,tok,tmTok,chkVal; - String nm,semVal; - Absyn.Ident idVal; - case ({},_,false,false) - equation - c =cTok; - nt =nTk; - if (debug) then - print("\nNow at end of input:\n"); - end if; - n = arrayGet(mm_pact,cSt+1); - rest = {}; - if (debug) then - print("[n:" + intString(n) + "]"); - end if; - if (n < 0 or ParseTable.YYLAST < n or arrayGet(mm_check,n+1) <> 0) then - //goto yydefault; - n = arrayGet(mm_defact,cSt+1); - if (n==0) then - // Error Handler - if (debug) then - print("\n Syntax Error found yyerrlab5:" + intString(errSt)); - //printAny("\n Syntax Error found yyerrlab5:" + intString(errSt)); - end if; - if (errSt>=0) then - (env2,semVal,result) = errorHandler(cTok,env,pt); - ENV(crTk=cTok, lookAhTk=nTk, state=stateStk, errMessages=errStk, errStatus=errSt, sState=sSt, cState=cSt, program=prog, progBk=prgBk, stateBackup=stateSkBk, astStackBackup=astSkBk)= env2; - else - result=false; - end if; - end if; - if (debug) then - print(" REDUCE4"); - end if; - (env2,astStk)=reduce(n,env,astStk,pt); - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk,errMessages=errStk,errStatus=errSt,sState=sSt,cState=cSt, - program=prog,progBk=prgBk,stateBackup=stateSkBk,astStackBackup=astSkBk)= env2; - - else - n = arrayGet(mm_table,n+1); - if (n<=0) then - if (n==0 or n==cTableNinf) then - // Error Handler - if (debug) then - print("\n Syntax Error found yyerrlab4:" + intString(n)); - end if; - if (errSt>=0) then - (env2,semVal,result) = errorHandler(cTok,env,pt); - else - result = false; - end if; - ENV(crTk=cTok, lookAhTk=nTk, state=stateStk, errMessages=errStk, errStatus=errSt, sState=sSt, cState=cSt, program=prog, progBk=prgBk, stateBackup=stateSkBk, astStackBackup=astSkBk)= env2; - end if; - n = -n; - if (debug) then - print(" REDUCE5"); - end if; - (env2,astStk)=reduce(n,env,astStk,pt); - ENV(crTk=cTok, lookAhTk=nTk, state=stateStk, errMessages=errStk, errStatus=errSt, sState=sSt, cState=cSt, program=prog, progBk=prgBk, stateBackup=stateSkBk, astStackBackup=astSkBk)= env2; - - else - if (debug) then - print(" SHIFT"); - end if; - if (errSt<0) then // reduce the shift error lookup - if (debug) then - print("\n***-RECOVERY TOKEN INSERTED IS SHIFTED-***"); - end if; - errSt = maxErrRecShift; - end if; - cSt = n; - stateStk = cSt::stateStk; - env2 = ENV(c,nt,stateStk,errStk,errSt,sSt,cSt,rest,rest,stateSkBk,astSkBk); - - end if; - end if; - if (result==true and errSt>maxErrRecShift) then //stops when it finds and error - if (debug) then - print("\nReprocesing at the END"); - end if; - (rest,env2,astStk,result) = processToken(rest,env2,astStk,pt); - end if; - - then ({},result); - case (_,_,true,_) - equation - if (debug) then - print("\n\n***************-ACCEPTED-***************\n"); - end if; - result = true; - if (List.isEmpty(errStk)==false) then - printErrorMessages(errStk); - result = false; - end if; - then ({},result); - case (_,_,false,true) - equation - n = arrayGet(mm_defact,cSt+1); - if (n == 0) then - // Error Handler - if (debug) then - print("\n Syntax Error found yyerrlab3:" + intString(n)); - end if; - if (errSt>=0) then - (env2,semVal,result) = errorHandler(cTok,env,pt); - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk,errMessages=errStk,errStatus=errSt,sState=sSt,cState=cSt, program=prog,progBk=prgBk,stateBackup=stateSkBk,astStackBackup=astSkBk)= env2; - else - result = false; - end if; - end if; - // reduce; - if (debug) then - print("REDUCE3"); - end if; - - (env2,astStk)=reduce(n,env,astStk,pt); - - if (result==true) then //stops when it finds and error - (rest,env2,astStk,result) = processToken(tokens,env2,astStk,pt); - end if; - - then (rest,result); - case (_,_,false,false) - equation - /* Do appropriate processing given the current state. Read a - lookahead token if we need one and don't already have one. */ - c::rest = tokens1; - cTok = c; - OMCCTypes.TOKEN(id=tmTok,name=nm) = c; - tok = translate(tmTok,pt); - - /* First try to decide what to do without reference to lookahead token. */ - - n = arrayGet(mm_pact,cSt+1); - if (debug) then - print("[n:" + intString(n) + "-"); - end if; - - n = n + tok; - if (debug) then - print("NT:" + intString(n) + "]"); - end if; - chkVal = n+1; - if (chkVal<=0) then - chkVal = 1; - end if; - if (n < 0 or ParseTable.YYLAST < n or arrayGet(mm_check,chkVal) <> tok) then - //goto yydefault; - n = arrayGet(mm_defact,cSt+1); - if (n==0) then - // Error Handler - if (debug) then - print("\n Syntax Error found yyerrlab2:" + intString(n)); - end if; - if (errSt>=0) then - (env2,semVal,result) = errorHandler(cTok,env,pt); - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk,errMessages=errStk,errStatus=errSt,sState=sSt,cState=cSt,program=prog,progBk=prgBk,stateBackup=stateSkBk,astStackBackup=astSkBk)= env2; - else - errSt = maxErrRecShift; - result = false; - end if; - else - if (debug) then - print(" REDUCE2"); - end if; - (env2,astStk)=reduce(n,env,astStk,pt); - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk,errMessages=errStk,errStatus=errSt,sState=sSt,cState=cSt,program=prog,progBk=prgBk,stateBackup=stateSkBk,astStackBackup=astSkBk)= env2; - rest = tokens1; - end if; - else - // try to get the value for the action in the table array - n = arrayGet(mm_table,n+1); - if (n<=0) then - // - if (n==0 or n==cTableNinf) then - // Error Handler - if (debug) then - print("\n Syntax Error found yyerrlab:" + intString(n)); - end if; - if (errSt>=0) then - (env2,semVal,result) = errorHandler(cTok,env,pt); - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk,errMessages=errStk,errStatus=errSt,sState=sSt,cState=cSt,program=prog,progBk=prgBk,stateBackup=stateSkBk,astStackBackup=astSkBk)= env2; - else - result = false; - errSt = maxErrRecShift; - end if; - else - n = -n; - if (debug) then - print(" REDUCE"); - end if; - (env2,astStk)=reduce(n,env,astStk,pt); - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk,errMessages=errStk,errStatus=errSt,sState=sSt,cState=cSt,program=prog,progBk=prgBk,stateBackup=stateSkBk,astStackBackup=astSkBk)= env2; - rest = tokens1; - end if; - else - if (debug) then - print(" SHIFT1"); - end if; - cSt = n; - stateStk = cSt::stateStk; - astStk = ParseCode.push(astStk,cTok); - astSkBk = astStk; - stateSkBk = stateStk; - if (errSt<>0) then // reduce the shift error lookup - errSt = errSt - 1; - end if; - env2 = ENV(c,nt,stateStk,errStk,errSt,sSt,cSt,rest,rest,stateSkBk,astSkBk); - end if; - end if; - - - if (errSt<>0 or List.isEmpty(rest)) then - if ((result==true) and (errSt>maxErrRecShift)) then //stops when it finds and error - (rest,env2,astStk,result) = processToken(rest,env2,astStk,pt); - end if; - end if; - then (rest,result); - end match; - // return the AST - -end processToken; - -function errorHandler - input OMCCTypes.Token currTok; - input Env env; - input ParseData pt; - output Env env2; - output String errorMsg; - output Boolean result; - // env variables -protected - OMCCTypes.Token cTok,nTk; - ParseCode.AstStack astSkBk; - Integer sSt,cSt,errSt; - list prog,prgBk; - list stateStk,stateSkBk; - list errStk; - // parse tables - array mm_tname; - array mm_translate, mm_prhs, mm_rhs, mm_rline, mm_toknum, mm_r1, mm_r2, mm_defact, mm_defgoto, - mm_pact, mm_pgoto, mm_table, mm_check, mm_stos; - - list redStk; - Integer numTokens; - String msg,semVal,fileName; - -algorithm - PARSE_TABLE(fileName=fileName,translate=mm_translate,prhs=mm_prhs,rhs=mm_rhs,rline=mm_rline,tname=mm_tname,toknum=mm_toknum,r1=mm_r1,r2=mm_r2 - ,defact=mm_defact,defgoto=mm_defgoto,pact=mm_pact,pgoto=mm_pgoto,table=mm_table,check=mm_check,stos=mm_stos) := pt; - - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk,sState=sSt,errMessages=errStk,errStatus=errSt,cState=cSt, - program=prog,progBk=prgBk,stateBackup=stateSkBk,astStackBackup=astSkBk):= env; - - if (debug) then - print("\nERROR RECOVERY INITIATED:"); - print("\n[State:" + intString(cSt) +"]{" + printStack(stateStk,"") + "}\n"); - print("\n[StateStack Backup:{" + printStack(stateSkBk,"") + "}\n"); - end if; - semVal := OMCCTypes.printToken(currTok); - (errorMsg,result) := matchcontinue(errSt==0,prog) - local - String erMsg,name; - list candidates; - list rest; - Integer i,idTok; - OMCCTypes.Info info; - case (true,{}) //start error catching - equation - erMsg = OMCCTypes.printErrorToken(currTok); - // insert token - if (debug) then - print("\n Checking INSERT at the END token:"); - //printAny("\n Checking INSERT at the END token:"); - end if; - candidates = {}; - candidates = checkCandidates(candidates,env,pt,3); - if (List.isEmpty(candidates)==false) then - erMsg = erMsg + ", INSERT at the End token " + printCandidateTokens(candidates,"") ; - end if; - errStk = erMsg::errStk; - - info = OMCCTypes.makeInfo(currTok,fileName); - addSourceMessage(errStk,info); - - printErrorMessages(errStk); - errSt = maxErrShiftToken; - then (erMsg,false); //end error catching - case (true,_) //start error catching - equation - - //OMCCTypes.TOKEN(id=idTok) = currTok; - //erMsg = OMCCTypes.printErrorToken(currTok); - erMsg = OMCCTypes.printErrorLine(currTok); - - if (debug) then - print("\n Check MERGE token until next token"); - end if; - nTk::_ = prog; - OMCCTypes.TOKEN(id=idTok) = nTk; - if (checkToken(idTok,env,pt,5)==true) then - _::nTk::_ = prog; - erMsg = erMsg + ", MERGE tokens " + OMCCTypes.printShortToken(currTok) - + " and " + OMCCTypes.printShortToken(nTk); - end if; - - // insert token - if (debug) then - print("\n Checking INSERT token:"); - end if; - candidates = {}; - candidates = checkCandidates(candidates,env,pt,2); - if (List.isEmpty(candidates)==false) then - erMsg = OMCCTypes.printErrorLine2(currTok); - erMsg = erMsg + ", INSERT token " + printCandidateTokens(candidates,""); - //errStk = erMsg::errStk; - end if; - - errSt = maxErrShiftToken; - - // replace token - // erMsg = "Syntax Error near " + semVal; - if (debug) then - print("\n Checking REPLACE token:"); - end if; - candidates = {}; - candidates = checkCandidates(candidates,env,pt,3); - if (List.isEmpty(candidates)==false) then - erMsg = erMsg + ", REPLACE token with " + printCandidateTokens(candidates,""); - //errStk = erMsg::errStk; - end if; - - errSt = maxErrShiftToken; - - // try to supress the token - // erMsg = "Syntax Error near " + semVal; - if (debug) then - print("\n Check ERASE token until next token"); - end if; - nTk::_ = prog; - OMCCTypes.TOKEN(id=idTok) = nTk; - if (checkToken(idTok,env,pt,1)==true) then - erMsg = erMsg + ", ERASE token" + " " + OMCCTypes.printShortToken(currTok); - //errStk = erMsg::errStk; - end if; - //printAny(errStk); - if (List.isEmpty(errStk)==true) then - errStk = erMsg::{}; - else - errStk = erMsg::errStk; - end if; - info = OMCCTypes.makeInfo(currTok,fileName); - addSourceMessage(errStk,info); - errSt = maxErrShiftToken; - then (erMsg,true); //end error catching - case (false,_) // add one more error - equation - printErrorMessages(errStk); - erMsg = OMCCTypes.printErrorToken(currTok); - then (erMsg,false); - end matchcontinue; - if (debug==true) then - print("\nERROR NUM:" + intString(errSt) +" DETECTED:\n" + errorMsg); - end if; - env2 := ENV(cTok,nTk,stateStk,errStk,errSt,sSt,cSt,prog,prgBk,stateSkBk,astSkBk); - //env2 := env; -end errorHandler; - -function checkCandidates - input list candidates; - input Env env; - input ParseData pt; - input Integer action; - output list resCandidates; - protected - list candidates1:=candidates; - Integer n; - // env variables - OMCCTypes.Token cTok,nTk; - ParseCode.AstStack astSkBk; - Boolean debug; - Integer sSt,cSt,errSt; - list prog,prgBk; - list stateStk,stateSkBk; - list errStk; - // parse tables - array mm_tname; - array mm_translate, mm_prhs, mm_rhs, mm_rline, mm_toknum, mm_r1, mm_r2, mm_defact, mm_defgoto, - mm_pact, mm_pgoto, mm_table, mm_check, mm_stos; - - Integer numTokens,i,j=1; - String name,tokVal; - algorithm - PARSE_TABLE(tname=mm_tname) := pt; - - resCandidates := candidates1; - numTokens := 255 + ParseTable.YYNTOKENS - 1; - // exhaustive search over the tokens - for i in 258:numTokens loop - if (checkToken(i,env,pt,action)==true) then - //name := mm_tname[i-255]; - if (j<=maxCandidateTokens) then - tokVal := getTokenSemValue(i-255,pt); - resCandidates := tokVal::resCandidates; - j := j+1; - else - i := numTokens+1; - end if; - end if; - end for; -end checkCandidates; - -function checkToken - input Integer chkTok; - input Env env; - input ParseData pt; - input Integer action; // 1 delete 2 insert 3 replace - output Boolean result; -protected - Integer n; - // env variables - OMCCTypes.Token cTok,nTk; - ParseCode.AstStack astSkBk; - Integer sSt,cSt,errSt; - list prog,prgBk; - list stateStk,stateSkBk; - list errStk; - // parse tables - array mm_tname; - array mm_translate, mm_prhs, mm_rhs, mm_rline, mm_toknum, mm_r1, mm_r2, mm_defact, mm_defgoto, - mm_pact, mm_pgoto, mm_table, mm_check, mm_stos; - Integer chk2; - Env env2; - OMCCTypes.Info info; - OMCCTypes.Token candTok; - algorithm - PARSE_TABLE(translate=mm_translate,prhs=mm_prhs,rhs=mm_rhs,rline=mm_rline,tname=mm_tname,toknum=mm_toknum,r1=mm_r1,r2=mm_r2 - ,defact=mm_defact,defgoto=mm_defgoto,pact=mm_pact,pgoto=mm_pgoto,table=mm_table,check=mm_check,stos=mm_stos) := pt; - - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk,sState=sSt,errMessages=errStk,errStatus=errSt,cState=cSt,program=prog, - progBk=prgBk,stateBackup=stateSkBk,astStackBackup=astSkBk):= env; - - if (debug) then - print("\n **** Checking TOKEN: " + intString(chkTok) + " action:" + intString(action)); - //printAny("\n **** Checking TOKEN: " + intString(chkTok) + " action:" + intString(action)); - end if; - // restore back up configuration and run the machine again to check candidate - if (List.isEmpty(prog)==false) then - cTok::prog := prog; - if (debug) then - print("\n **** Last token: " + OMCCTypes.printToken(cTok)); - end if; - candTok := OMCCTypes.TOKEN(arrayGet(mm_tname,chkTok-255),chkTok,"",1,0,0,0,0,0); - else - if (debug) then - print("\n Creating Fake Token position"); - end if; - candTok := OMCCTypes.TOKEN(arrayGet(mm_tname,chkTok-255),chkTok,"",1,0,0,0,0,0); - end if; - - if (debug) then - print("\n **** Process candidate token: " + OMCCTypes.printToken(candTok) + " action: " + intString(action)); - end if; - - (prog) := matchcontinue(action) - local - String value; - list lstTokens; - case (5) // Merge - equation - if (List.isEmpty(prog)==false) then - candTok::prog = prog; - value = OMCCTypes.getMergeTokenValue(cTok,candTok); - lstTokens = Lexer.lex("fileName",value); - candTok::_ = lstTokens; - prog = candTok::prog; - end if; - then (prog); - case (2) // Insert - equation - prog = candTok::cTok::prog; - then (prog); - case (3) // replace - equation - prog = candTok::prog; - then (prog); - else then (prog); - end matchcontinue; - - cSt::_ := stateSkBk; - errStk := {}; //reset errors - errSt := -1; // no errors reset - // backup the env variables to the last shifted token - env2 := ENV(cTok,nTk,stateSkBk,errStk,errSt,sSt,cSt,prog,prgBk,stateSkBk,astSkBk); - //printAny(env2); - - result := false; - if (debug) then - //print("\n\n*****ProcessTOKENS:" + OMCCTypes.printTokens(prog,"") + " check" + intString(chkTok)); - end if; - //print("\n[State="+ intString(cSt) + " Stack Backup:{" + printStack(stateSkBk,"") + "}]\n"); - //print("\n[StateStack Backup:{" + printStack(stateSkBk,"") + "}\n"); - - (_,_,_,result) := processToken(prog,env2,astSkBk,pt); - - if (result and debug) then - print("\n **** Candidate TOKEN ADDED: " + intString(chkTok)); - end if; -end checkToken; - -function reduce - input Integer rule; - input Env env; - input ParseCode.AstStack inAstStk; - input ParseData pt; - output Env env2; - output ParseCode.AstStack astStk := inAstStk; -protected - // parse tables - array mm_tname; - array mm_translate, mm_prhs, mm_rhs, mm_rline, mm_toknum, mm_r1, mm_r2, mm_defact, mm_defgoto, - mm_pact, mm_pgoto, mm_table, mm_check, mm_stos; - // env variables - OMCCTypes.Token cTok,nTk; - ParseCode.AstStack astSkBk; - Boolean error; - list stateStk,stateSkBk; - list errStk,redStk; - String astTmp,semVal,errMsg,fileName; - Integer errSt,sSt,cSt; - list prog,prgBk; - Integer i,len,val,n, nSt,chkVal; -algorithm - PARSE_TABLE(translate=mm_translate,prhs=mm_prhs,rhs=mm_rhs,rline=mm_rline,tname=mm_tname,toknum=mm_toknum,r1=mm_r1,r2=mm_r2 - ,defact=mm_defact,defgoto=mm_defgoto,pact=mm_pact,pgoto=mm_pgoto,table=mm_table,check=mm_check,stos=mm_stos,fileName=fileName) := pt; - - ENV(crTk=cTok,lookAhTk=nTk,state=stateStk /* changes */,sState=sSt,errMessages=errStk /* changes */, - errStatus=errSt /* changes */,cState=cSt /* changes */,program=prog,progBk=prgBk, - stateBackup=stateSkBk,astStackBackup=astSkBk):= env; - if rule > 0 then - len := arrayGet(mm_r2,rule); - if (debug) then - print("[Reducing(l:" + intString(len) + ",r:" + intString(rule) +")]"); - end if; - redStk := {}; - for i in 1:len loop - val::stateStk := stateStk; - end for; - if (errSt>=0) then - (astStk,error,errMsg) := ParseCode.actionRed(rule,astStk,fileName); - end if; - if (error) then - errStk := errMsg::errStk; - errSt := maxErrShiftToken; - end if; - - cSt::_ := stateStk; - - n := arrayGet(mm_r1,rule); - - nSt := mm_pgoto[n - ParseTable.YYNTOKENS + 1]; - nSt := nSt + cSt; - chkVal := nSt +1; - if (chkVal<=0) then - chkVal := 1; - end if; - if ( (nSt >=0) and (nSt <= ParseTable.YYLAST) and (arrayGet(mm_check,chkVal) == cSt) ) then - cSt := arrayGet(mm_table,nSt+1); - else - cSt := arrayGet(mm_defgoto,n - ParseTable.YYNTOKENS+1); - end if; - if (debug) then - print("[nState:" + intString(cSt) + "]"); - end if; - stateStk := cSt::stateStk; - end if; - env2 := ENV(cTok,nTk,stateStk,errStk,errSt,sSt,cSt,prog,prgBk,stateSkBk,astSkBk); -end reduce; - -function translate - input Integer tok1; - input ParseData pt; - output Integer tok2; - protected - ParseData pt1:=pt; - array mm_translate; - Integer maxT,uTok; - algorithm - PARSE_TABLE(translate=mm_translate) := pt1; - maxT := ParseTable.YYMAXUTOK; - uTok := ParseTable.YYUNDEFTOK; - (tok2) := matchcontinue(tok1<=maxT) - local - Integer res; - case (true) - equation - - res = arrayGet(mm_translate,tok1); - //print("\nTRANSLATE TO:" + intString(res)); - then (res); - case (false) - then (uTok); - end matchcontinue; -end translate; - -function getTokenSemValue "retrieves semantic value from token id" - input Integer tokenId; - input ParseData pt; - output String tokenSemValue "returns semantic value of the token"; - protected - array values; - algorithm - - if (List.isEmpty(ParseCode.lstSemValue)==true) then - PARSE_TABLE(tname=values) := pt; - else - values := listArray(ParseCode.lstSemValue); - end if; - tokenSemValue := "'" + arrayGet(values,tokenId) + "'"; -end getTokenSemValue; - -function printBuffer - input list inList; - output String outList; - protected - list inList1:=inList; - Integer c:=0; -algorithm - outList := stringAppendList(list(intStringChar(c) for c in inList1)); -end printBuffer; - - function printSemStack - input list inList; - input String cBuff; - output String outList; - protected - list inList1:=inList; - algorithm - (outList) := matchcontinue(inList,cBuff) - local - String c; - String new,tout; - list rest; - case ({},_) - then (cBuff); - else - equation - c::rest = inList1; - new = cBuff + "\n" + c; - (tout) = printSemStack(rest,new); - then (tout); - end matchcontinue; - end printSemStack; - - function printCandidateTokens - input list inList; - input String cBuff; - output String outList; - protected - list inList1:=inList; - String cBuff1:=cBuff; - algorithm - (outList) := matchcontinue(inList,cBuff) - local - String c; - String new,tout; - list rest; - case ({},_) - equation - cBuff1 = System.substring(cBuff1,1,stringLength(cBuff1)-4); - then (cBuff1); - else - equation - c::rest = inList1; - new = cBuff1 + c + " or "; - (tout) = printCandidateTokens(rest,new); - then (tout); - end matchcontinue; - end printCandidateTokens; - - function printStack - input list inList; - input String cBuff; - output String outList; - protected - list inList1:=inList; - algorithm - (outList) := matchcontinue(inList,cBuff) - local - Integer c; - String new,tout; - list rest; - case ({},_) - then (cBuff); - else - equation - c::rest = inList1; - new = cBuff + "|" + intString(c); - (tout) = printStack(rest,new); - then (tout); - end matchcontinue; - end printStack; -end Parser; diff --git a/openmodelica/omcc/ParserGenerator.mo b/openmodelica/omcc/ParserGenerator.mo deleted file mode 100644 index adce3760c26..00000000000 --- a/openmodelica/omcc/ParserGenerator.mo +++ /dev/null @@ -1,795 +0,0 @@ -package ParserGenerator -import System; -import Util; -import OMCC.copyright; -/* - -*/ -constant Boolean debug = false; - -function genParser - input String bisonFile; - input String grammarFile; - input String outFileName; - output String result; -protected - String bisonCode,re,ar1,rest; - Boolean res1,res3,res4; - list resultRegex,resTable,chars; - array yyr2; -algorithm - //open bison file - if (outFileName<>"" and stringLength(outFileName)<15) then - if (debug==true) then - print("\nGenerating Parser from " + bisonFile); - end if; - bisonCode := System.readFile(bisonFile); - print("Reading BISON grammar file " + bisonFile + "\n"); - - (res1,yyr2) := buildParseTable(bisonCode,"ParseTable" + outFileName); - if (debug==true) then - print("\nbuild Parse table"); - end if; - - if (debug==true) then - print("Generating Token from " + bisonFile + "\n"); - end if; - - res3 := buildParserCode(bisonCode,grammarFile,outFileName,yyr2); - if (debug==true) then - print("Generating ParserCode from " + bisonFile + "\n"); - end if; - /* - if (debug==true) then - print("Build Parser ..." + "\n"); - end if; - res4 := buildParser(outFileName); - */ - res4 := buildParser(outFileName); - if (debug==true) then - print("\nBuild Parser ..."); - end if; - result := "Parser Built"; - if (res1==false) then - result := result + "\nParseTable"+ outFileName +".mo could not be generated."; - end if; - if (res3==false) then - result := result + "\nParseCode"+ outFileName +".mo could not be generated."; - end if; - if (res4==false) then - result := result + "\nParser"+ outFileName +".mo could not be generated."; - end if; - else - result := "Parser can not be generated. Invalid name"; - end if; -end genParser; - -function buildParser - input String outFileName; - output Boolean buildResult; - protected - String parser,result,stTime,cp; -algorithm - parser := System.readFile("Parser.mo"); - result := System.stringReplace(parser,"ParseTable","ParseTable" + outFileName); - result := System.stringReplace(result,"Lexer.","Lexer" + outFileName + "."); - result := System.stringReplace(result,"ParseCode","ParseCode" + outFileName); - cp := "package Parser" + outFileName + " \" " + copyright + "\""; - result := System.stringReplace(result,"package Parser",cp ); - result := System.stringReplace(result,"end Parser;","end Parser" + outFileName + ";"); - System.writeFile("Parser" + outFileName + ".mo",result); - buildResult := true; -end buildParser; - - -function readPrologEpilog - input String parserCode; - input String grammarFileName; - output String parserCodeIncluded; - protected - String grammarFile,epilog,prolog,re,ar1,astRootType; - Integer numMatches,pos1,pos2; - list resultRegex; -algorithm - grammarFile := System.readFile(grammarFileName); - - //find prologue - - pos1 := System.stringFind(grammarFile,"%{"); - pos2 := System.stringFind(grammarFile,"%}"); - - ar1 := substring(grammarFile,pos1+3,pos2-1); - parserCodeIncluded := System.stringReplace(parserCode,"%prologue%",ar1); - - // -/* ar1 := System.stringFindString(grammarFile,"AstTree"); - pos1 := System.stringFind(ar1,"="); - pos2 := System.stringFind(ar1,";"); - astRootType := substring(ar1,pos1+2,pos2); - astRootType := System.trim(astRootType," "); - parserCodeIncluded := System.stringReplace(parserCodeIncluded,"%astTree%",astRootType); */ - - //find epilogue - re := "%%"; - ar1 := System.stringFindString(grammarFile,re); - ar1 := substring(ar1,3,stringLength(ar1)); - ar1 := System.stringFindString(ar1,re); - ar1 := substring(ar1,3,stringLength(ar1)); - parserCodeIncluded := System.stringReplace(parserCodeIncluded,"%epilogue%",ar1); - - -end readPrologEpilog; - - -function buildParserCode - input String bisonCode; - input String grammarFile; - input String outFileName; - input array yyr2; - output Boolean buildResult; -protected - list resTable; - String parseCode,result,rest,stTime,cp,caseAction,re,typeTok,astValType,astRootType,resultRegex,regexError,lineStr,origFile,fileInfoAnnotation; - Integer i,numRules,pos,pos2,posBegin,valBegin; - list types; - Integer ix,maxReduce,numReduce,numMatches; -algorithm - types := {"String","Integer"}; - maxReduce := 0; - parseCode := System.readFile("ParseCode.tmo"); - stTime := copyright; - result := System.stringReplace(parseCode,"%ParseCode%","ParseCode" + outFileName); - result := System.stringReplace(result,"%time%",stTime); - result := readPrologEpilog(result,grammarFile); - - - caseAction := ""; - resTable := {}; - if (debug==true) then - print("\nFind value ynrules..."); - end if; - numRules := findValue(bisonCode,"YYNRULES"); - re := "switch (yyn)"; - rest := System.stringFindString(bisonCode,re); - - for i in 2:numRules loop - cp := "\n case "; - resTable := cp::resTable; - cp := intString(i); - resTable := cp::resTable; - - re := "case " + intString(i) + ":"; - if (debug==true) then - print("\n" + re); - printAny("\n" + re); - end if; - pos := System.stringFind(bisonCode,re); - if (pos<0) then - print("\nError in rule " + intString(i) + ". Case not found."); - end if; - rest := System.stringFindString(bisonCode,re); - - re := "#line"; - (3,_::lineStr::origFile::_) := System.regex(rest,"#line *([0-9]*) *(\"[A-Za-z0-9.]*\")",3,extended=true); - fileInfoAnnotation := " annotation(__OpenModelica_FileInfo=("+origFile+","+lineStr+"));\n"; - - pos2 := System.stringFind(rest,"break;"); - rest := substring(rest,1,pos2-1); - //re := "{[^}]*;}"; - re := "[{] *(.*;) *[}]"; - (numMatches,regexError::resultRegex::_) := System.regex(rest,re,2,extended=true); - if numMatches == 2 then - cp := "\n equation\n"; - resTable := cp::resTable; - if (debug==true) then - print("Rule " + intString(i) + ":" + resultRegex + "\n"); - end if; - print("Rule " + intString(i) + ":" + resultRegex + "\n"); - ix := arrayGet(yyr2,i); - (cp,types) := processRule(resultRegex,types,ix); - maxReduce := max(maxReduce, ix); - cp := cp + "\n stack = yyval::stack;\n"; - cp := System.stringReplace(cp,";\n",fileInfoAnnotation); - resTable := cp::resTable; - cp := " then ();\n"; - resTable := cp::resTable; - else - print("Rule "+intString(i)+" not found: \n"); - print(regexError); - print(rest); - fail(); - end if; - end for; - - resTable := listReverse(resTable); - caseAction := stringCharListString(resTable); - - - // generate variables and typesStack - astValType := ""; - types := "Token"::types; //stack to push tokens - - astValType := " AstItem " + stringDelimitList(list("yysp_" + intString(i) for i in 1:maxReduce), ",") + ";\n"; - - caseAction := astValType + caseAction; - - astRootType := "AstItem"; // substring(rest,stringLength(re)+1,pos2); - - result := System.stringReplace(result,"%astTree%",astRootType); - - result := System.stringReplace(result,"%caseAction%",caseAction); - - System.writeFile("ParseCode" + outFileName + ".mo",result); - buildResult := true; -end buildParserCode; - -function processRule - input String inRule; - input list types; - input Integer numTokensInRule; - output String processedRules; - output list types2; -protected - Integer pos1,pos2,i; - list resTable; - String cp,tokRes,re,typeTok,rule,var; - algorithm - rule := inRule; - resTable := {}; - types2 := types; - if numTokensInRule >=2 then - cp := " stackToken = mergeStackTokens(stackToken,"+intString(numTokensInRule)+");\n"; - resTable := cp::resTable; - elseif numTokensInRule == 0 then - // We need to add something to the stack... - cp := " stackToken = OMCCTypes.noToken::stackToken;\n"; - resTable := cp::resTable; - end if; - - for i in numTokensInRule:-1:1 loop - var := "yysp_"+intString(i); - re := "(yyvsp[("+intString(i)+") - ("+intString(numTokensInRule)+")])"; - cp := " "+var+"::stack = stack;\n"; - rule := System.stringReplace(rule,re,var); - resTable := cp::resTable; - end for; - - resTable := (" "+rule)::resTable; - processedRules := stringAppendList(listReverse(resTable)); - processedRules := System.stringReplace(processedRules, "yyinfo", "OMCCTypes.makeInfo(listGet(stackToken,1),fileName)"); -end processRule; - -function replaceTokenVal - input String rule; - input Integer tok; - output String result; - protected - Integer pos,pos2,numTok; - String re,rest,typeTok,cp; - algorithm - numTok := numTokens(rule); - typeTok := findTypeToken(rule,tok); - re := "(yyvsp[(" + intString(tok) + ") - (" + intString(numTok) + ")])[" + typeTok + "]"; - pos := System.stringFind(rule, re); - if (pos<0) then - re := "(yyvsp[(" + intString(tok) + ") - (" + intString(numTok) + ")])"; - end if; - cp := "(v" + intString(tok) + typeTok + ")"; - if (findTypeResult(rule)=="Integer" and typeTok=="String") then - cp := "(stringInt(v" + intString(tok) + typeTok + "))"; - end if; - //print(re); - result := System.stringReplace(rule,re,cp); - //print(result); -end replaceTokenVal; - -function reduceToken - input String rule; - input Integer tok; - output String reduce; - protected - Integer pos,pos2; - String re,rest,typeTok; - algorithm - typeTok := findTypeToken(rule,tok); - reduce := " v" + intString(tok) + typeTok +"::sk" + typeTok + " = sk" + typeTok + ";\n"; - //print(reduce); -end reduceToken; - -function findTypeResult - input String rule; - output String typeTok; - protected - Integer pos,pos2,posAST; - String re,rest; - algorithm - //print("\n Rule-" + rule + "-"); - re := "(absyntree)["; - posAST := System.stringFind(rule,re); - re := "(yyval)"; - pos2 := System.stringFind(rule,re); - re := "(yyval)["; - pos := System.stringFind(rule,re); - if (pos>=0) then - rest := System.stringFindString(rule,re); - pos2 := System.stringFind(rest,"]"); - typeTok := substring(rest,stringLength(re)+1,pos2); - elseif (posAST>=0) then - re := "(absyntree)["; - rest := System.stringFindString(rule,re); - pos2 := System.stringFind(rest,"]"); - typeTok := substring(rest,stringLength(re)+1,pos2); - else - if (pos2>=0) then - typeTok := "String"; - end if; - end if; - if (debug==true) then - print("\n TypeTok-" + typeTok + "-"); - end if; -end findTypeResult; - -function findTypeToken - input String rule; - input Integer tok; - output String typeTok; - protected - Integer pos,pos2,numTok; - String re,rest; - algorithm - numTok := numTokens(rule); - re := "(yyvsp[(" + intString(tok) + ") - (" + intString(numTok) + ")])["; - - pos := System.stringFind(rule,re); - - if (pos<0) then - typeTok := "String"; - else - rest := substring(rule,pos+stringLength(re)+1,stringLength(rule)-1); - pos2 := System.stringFind(rest,"]"); - typeTok := substring(rest,1,pos2); - if (debug==true) then - print("\nTypeToken[" + typeTok + "]"); - end if; - end if; - -end findTypeToken; - -function numTokens - input String rule; - output Integer num; - protected - Integer pos,pos2; - String re,rest,val; - algorithm - re := ") - ("; - pos := System.stringFind(rule,re); - - if (pos<0) then - num := 0; - else - rest := System.stringFindString(rule,re); - pos2 := System.stringFind(rest,")]"); - - val := substring(rest,stringLength(re)+1,pos2); - if (debug==true) then - print("\n found numTokens:" + val); - end if; - num := stringInt(val); - end if; -end numTokens; - -function findValue - input String bisonCode; - input String variable; - output Integer value; - protected - Integer pos; - String rest,val,re; - algorithm - re := "define " + variable; - rest := System.stringFindString(bisonCode,re); - pos := System.stringFind(rest,"\n"); - val := substring(rest,stringLength(re)+1,pos); - if (debug==true) then - print("\n found value:" + val); - end if; - value := stringInt(val); -end findValue; - -function buildTokens - input String bisonCode; - output String result; - protected - String cp,re,ar1,rest,stTime,rest2; - Integer pos1,pos2,len,numMatches; - list resultRegex,resTable,chars,tokens; -algorithm - stTime := copyright; - cp := "encapsulated package Token\n"; - resTable := cp::{}; - - //re := "enum yytokentype {"; - re := "enum yytokentype[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,"{"); - pos2 := System.stringFind(rest,"}"); - end if; - rest := substring(rest,pos1+2,pos2-4); - tokens := System.strtok(rest,","); - while (listEmpty(tokens)==false) loop - cp := "\n constant Integer "; - resTable := cp::resTable; - cp::tokens := tokens; - cp := System.trim(cp,"\n"); - resTable := cp::resTable; - cp := ";"; - resTable := cp::resTable; - end while; - - cp := "\nend Token;"; - resTable := cp::resTable; - - resTable := listReverse(resTable); - result := stringCharListString(resTable); -end buildTokens; - -function buildParseTable - input String bisonCode; - input String outFileName; - output Boolean buildResult; - output array yyr2; -protected - String cp,re,ar1,rest,result,stTime; - Integer pos1,pos2,len,numMatches; - list resultRegex,resTable,chars; -algorithm - - stTime := copyright; - cp := "encapsulated package " + outFileName +" // " + stTime + " \n\nconstant Integer YYFINAL = "; - resTable := cp::{}; - - // Insert YYFINAL - re := "define YYFINAL"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant Integer YYLAST = "; - resTable := cp::resTable; - re := "#define YYLAST"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant Integer YYNTOKENS ="; - resTable := cp::resTable; - re := "define YYNTOKENS"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant Integer YYNNTS = "; - resTable := cp::resTable; - re := "define YYNNTS"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant Integer YYNRULES = "; - resTable := cp::resTable; - re := "define YYNRULES"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant Integer YYNSTATES = "; - resTable := cp::resTable; - re := "define YYNSTATES"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant Integer YYUNDEFTOK = "; - resTable := cp::resTable; - re := "define YYUNDEFTOK"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant Integer YYMAXUTOK = "; - resTable := cp::resTable; - re := "define YYMAXUTOK"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant Integer YYPACT_NINF = "; - resTable := cp::resTable; - re := "define YYPACT_NINF"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant Integer YYTABLE_NINF = "; - resTable := cp::resTable; - re := "define YYTABLE_NINF"; - rest := System.stringFindString(bisonCode,re); - pos2 := System.stringFind(rest,"\n"); - ar1 := substring(rest,stringLength(re)+1,pos2); - resTable := ar1::resTable; - - cp := ";\n\nconstant list yytranslate = {\n"; - resTable := cp::resTable; - //re := "static const yytype_uint8 yytranslate"; - re := "yytranslate\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - cp := "};\n\nconstant list yyprhs = {\n"; - resTable := cp::resTable; - //re := "static const yytype_uint8 yyprhs"; - re := "yyprhs\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - cp := "};\n\nconstant list yyrhs = "; - resTable := cp::resTable; - //re := "static const yytype_int8 yyrhs"; - re := "yyrhs\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,"{"); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+1,pos2+1); - resTable := ar1::resTable; - end if; - - cp := ";\n\nconstant list yyrline := {\n"; - resTable := cp::resTable; - re := "static const yytype_uint8 yyrline"; - re := "yyrline\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - cp := "};\n\nconstant list yytname = {\n"; - resTable := cp::resTable; - //re := "static const char *const yytname"; - re := "yytname[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - - rest::_ := resultRegex; - - //print("\nNumMatches:" + intString(numMatches) + "\n" + rest); - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - (2,_::ar1::_) := System.regex(rest,",([^#]*),.*(0|YY_NULL)",2,true,false); - resTable := ar1::resTable; - end if; - - cp := "};\n\nconstant list yytoknum = {\n"; - resTable := cp::resTable; - //re := "static const yytype_uint16 yytoknum"; - re := "yytoknum\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - cp := "};\n\nconstant list yyr1 = {\n"; - resTable := cp::resTable; - //re := "static const yytype_uint8 yyr1"; - re := "yyr1\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - end if; - - cp := "};\n\nconstant list yyr2 = {"; - resTable := cp::resTable; - re := "yyr2\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,","); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+2,pos2-1); - resTable := ar1::resTable; - yyr2 := listArray(List.map(System.strtok(ar1,","), stringInt)); - else - print("Failed to find yyr2\n"); - fail(); - end if; - - cp := "};\n\nconstant list yydefact = "; - resTable := cp::resTable; - //re := "static const yytype_uint8 yydefact"; - re := "yydefact\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,"{"); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+1,pos2+1); - resTable := ar1::resTable; - end if; - - cp := ";\n\nconstant list yydefgoto = "; - resTable := cp::resTable; - //re := "static const yytype_int8 yydefgoto"; - re := "yydefgoto\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,"{"); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+1,pos2+1); - resTable := ar1::resTable; - end if; - - cp := ";\n\nconstant list yypact = "; - resTable := cp::resTable; - //re := "static const yytype_int8 yypact"; - re := "yypact\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,"{"); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+1,pos2+1); - resTable := ar1::resTable; - end if; - - cp := ";\n\nconstant list yypgoto = "; - resTable := cp::resTable; - //re := "static const yytype_int8 yypgoto"; - re := "yypgoto\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,"{"); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+1,pos2+1); - resTable := ar1::resTable; - end if; - - cp := ";\n\nconstant list yytable = "; - resTable := cp::resTable; - //re := "static const yytype_uint8 yytable"; - re := "yytable\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,"{"); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+1,pos2+1); - resTable := ar1::resTable; - end if; - - cp := ";\n\nconstant list yycheck ="; - resTable := cp::resTable; - //re := "static const yytype_int8 yycheck"; - re := "yycheck\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,"{"); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+1,pos2+1); - resTable := ar1::resTable; - end if; - - cp := ";\n\nconstant list yystos = "; - resTable := cp::resTable; - //re := "static const yytype_uint8 yystos"; - re := "yystos\\[[0-9]*\\] =[^}]*}"; - (numMatches,resultRegex) := System.regex(bisonCode,re,1,false,false); - rest::_ := resultRegex; - if (numMatches > 0) then - //rest := System.stringFindString(bisonCode,re); - pos1 := System.stringFind(rest,"{"); - pos2 := System.stringFind(rest,"}"); - ar1 := substring(rest,pos1+1,pos2+1); - resTable := ar1::resTable; - end if; - - cp := ";\n\nend " + outFileName + ";"; - resTable := cp::resTable; - - resTable := listReverse(resTable); - result := stringCharListString(resTable); - System.writeFile(outFileName + ".mo",result); - buildResult := true; -end buildParseTable; - -public function getCurrentTimeStr " -returns current time in format Www Mmm dd hh:mm:ss yyyy -using the asctime() function in time.h (libc) -" -output String timeStr; -protected -Integer sec, min, hour, mday, mon, year; -algorithm - timeStr := System.getCurrentTimeStr(); - /* (sec, min, hour, mday, mon, year) := System.getCurrentDateTime(); - timeStr := intString(year) + "/" + intString(mon)+ "/" + intString(mday)+ - " " + intString(hour)+ ":" + intString(min) + ":" + intString(sec);*/ -end getCurrentTimeStr; - - -public function substring3 -input String inString; -input Integer start; -input Integer stop; -output String outString; -protected -list chars, result; -String c; -Integer i; -algorithm - - result :={}; - chars := stringListStringChar(inString); - for i in 1:stop loop - c::chars := chars; - if (i>=start) then - result := c::result; - end if; - end for; - result := listReverse(result); - outString := stringCharListString(result); -end substring3; - -end ParserGenerator; diff --git a/openmodelica/omcc/Readme.txt b/openmodelica/omcc/Readme.txt deleted file mode 100644 index dc719fe1aaf..00000000000 --- a/openmodelica/omcc/Readme.txt +++ /dev/null @@ -1,25 +0,0 @@ -// This file provides you how to compile and test the OMCCp -// There are two folders named omcc and omcc_test in the directory trunk/openmodelica/testsuite/ -// the "omcc" folder contains the implemented code and the "omcc_test" folder contains the test cases -// look for the file SCRIPT.mos in the folder "omcc" -// to make the compilation process easier a Makefile is created.(look into the omcc folder) - -1) Open the mingw terminal if you are a windows user and normal terminal for linux user - -2) In the terminal window go to the path /OpenModelica/testsuite/openmodelica/omcc - -3) at present the code is tested with testing environment rtest, and the baseline is added to makefile so set the basline by typing - "make baseline" in the terminal without quotes. baseline will be set. You have to set the baseline first everytime before you test your models - -4) Then type the command "make test" or "make" in the terminal window, the omccp will be compiled and ready to run - -5) some c files and other lib files will be created after running make, you can run again "make clean" to delete those generated files - -6) The parser runs and produces the output for the testcases which can be seen in output. - -7) if you want to test your own models or some other models look for the file "SCRIPT.mos" in the folder omcc - -8) Open the file "SCRIPT.mos" and look for the comments // add your testfiles here - -Note: you can look a clear picture of the output in the file SCRIPT.mos. -Note: to run the omcc without use of make file use the following ../../../build/bin/omc +g=MetaModelica +d=rml SCRIPT.mos diff --git a/openmodelica/omcc/SCRIPT.mos b/openmodelica/omcc/SCRIPT.mos deleted file mode 100644 index 2bfa02c7183..00000000000 --- a/openmodelica/omcc/SCRIPT.mos +++ /dev/null @@ -1,76 +0,0 @@ -// name: OMCC -// status: correct - -setCommandLineOptions({"+g=MetaModelica","+d=rml"}); -// getInstallationDirectoryPath(); -loadFile("Types.mo"); -loadFile("../../../Compiler/FrontEnd/Absyn.mo"); -loadFile("../../../Compiler/Util/Error.mo"); -loadFile("../../../Compiler/Util/ErrorExt.mo"); -loadFile("../../../Compiler/FrontEnd/Dump.mo"); -loadFile("../../../Compiler/Util/Print.mo"); -loadFile("../../../Compiler/Util/Flags.mo"); -loadFile("../../../Compiler/Global/Global.mo"); -//loadFile("../../../Compiler/Util/Pool.mo"); -loadFile("../../../Compiler/Util/Config.mo"); -loadFile("../../../Compiler/Util/Debug.mo"); -loadFile("../../../Compiler/Util/List.mo"); -loadFile("../../../Compiler/Util/Settings.mo"); -loadFile("../../../Compiler/Util/Corba.mo"); -//loadFile("../../../Compiler/Util/Name.mo"); -//loadFile("../../../Compiler/Util/Scope.mo"); -loadFile("../../../Compiler/Util/Util.mo"); -loadFile("../../../Compiler/Util/System.mo"); -loadFile("TokenModelica.mo"); -loadFile("LexTableModelica.mo"); -loadFile("LexerCodeModelica.mo"); -loadFile("LexerModelica.mo"); -loadFile("ParseCodeModelica.mo"); -loadFile("ParserModelica.mo"); -loadFile("ParseTableModelica.mo"); -loadFile("Main.mo"); - -// add your test files here - -{Main.main({"../../../Examples/" + file,"Modelica"}) for file in {"BouncingBall.mo"}}; - - /* -{Main.main({"../../flattening/modelica/algorithms-functions/" + file,"Modelica"}) for file in {"Algorithm1.mo","Algorithm3.mo","AlgorithmElseOpt.mo","AlgorithmFor1.mo", - "AlgorithmFor2.mo","AlgorithmFor3.mo","AlgorithmFor4.mo","AlgorithmFor5.mo", - "AlgorithmFor6.mo"}}; - - - -{Main.main({"../../flattening/modelica/built-in-functions/" + file,"Modelica"}) for file in {"Abs.mo","Abs1.mo","Delay.mo","Delay2.mo","Delay3.mo", - "Delay4.mo","Delay6.mo","DerConstant1.mo","DerConstant2.mo"}}; - -{Main.main({"../../flattening/modelica/arrays/" + file,"Modelica"}) for file in {"Array1.mo","Array2.mo","Array3.mo","Array4.mo","Array5.mo","Array6.mo","Array7.mo","Array8.mo", - "Array9.mo","Array10.mo","Array13.mo","Array14.mo","ArrayAccess.mo","ArrayAddition.mo","ArrayAddition2.mo", - "ArrayBrackets.mo","ArrayCurlyBrackets.mo","ArrayDeclaration1.mo","ArrayDeclaration2.mo","ArrayDeclaration3.mo", - "ArrayDeclaration4.mo","ArrayDeclaration5.mo"}}; - -{Main.main({"../../flattening/modelica/operators/" + file,"Modelica"}) for file in {"And.mo"}}; - -{Main.main({"../../flattening/modelica/external-functions/" + file,"Modelica"}) for file in {"AddReal1.mo"}}; - -{Main.main({"../../flattening/modelica/others/" + file,"Modelica"}) for file in{"BooleanLiterals.mo","Class1.mo", - "Comment1.mo"}}; - -{Main.main({"../../../Examples/" + file,"Modelica"}) for file in {"BouncingBall.mo","bubblesort.mo","Circle.mo","dcmotor.mo","ExternalLibraries.mo" - ,"HelloWorld.mo","Influenza.mo","SimpleIntegrator.mo","Switch.mo","VanDerPol.mo" - ,"visualize_3D_BouncingBall.mo"}}; - - -{Main.main({"../../flattening/modelica/arrays/" + file,"Modelica"}) for file in {"ArrayDivision.mo","ArrayEWOps1.mo","ArrayEWOps2.mo","ArrayEWOps3.mo", - "ArrayEWOps4.mo","ArrayEWOps5.mo","ArrayEWOps6.mo","ArrayEWOpsCEval1.mo", - "ArrayEWOpsCEval2.mo","ArrayEWOpsCEval3.mo","ArrayEWOpsCEval4.mo","ArrayEWOpsCEval5.mo", - "ArrayExtend.mo","ArrayExtendsUnknown.mo","ArrayIndex.mo","ArrayIndex2.mo", - "ArrayLogic.mo","ArrayMatrixSimplifier.mo"}}; - - -{Main.main({"../../flattening/modelica/declarations/" + file,"Modelica"}) for file in{"DeclarationOrder.mo","DeclarationOrder1.mo","DeclarationOrder2.mo"}}; - -*/ - -getErrorString(); - diff --git a/openmodelica/omcc/lexerModelica.l b/openmodelica/omcc/lexerModelica.l deleted file mode 100644 index 6e2351e3547..00000000000 --- a/openmodelica/omcc/lexerModelica.l +++ /dev/null @@ -1,221 +0,0 @@ -%{ - -%} - -%x c_comment -%x c_linecomment -%x c_string - -whitespace [ \t\n]+ -letter [a-zA-Z] -wild [_] -digit [0-9] -digits {digit}+ -ident (({letter}|{wild})|['\'']({letter}|{digit}|[-*+/^=])*['\''])({letter}|{digit}|{wild})* -exponent ([e]|[E])([+]|[-])?{digits} -real {digits}[\.]({digits})?({exponent})? -real2 {digits}{exponent} -real3 [\.]{digits}({exponent})? -endif "end"{whitespace}"if" -endfor "end"{whitespace}"for" -endparfor "end"{whitespace}"parfor" -endwhile "end"{whitespace}"while" -endwhen "end"{whitespace}"when" -endmatch "end"{whitespace}"match" -endmatchcontinue "end"{whitespace}"matchcontinue" -initialequation "initial"{whitespace}"equation" -initialalgorithm "initial"{whitespace}"algorithm" -endident "end"{whitespace}{ident} - -/* Lex style lexical syntax of tokens in the MODELICA language */ - - - - -%% -{whitespace} ; -{real} return UNSIGNED_REAL; -{real2} return UNSIGNED_REAL; -{real3} { sToken = LexerModelica.printBuffer(listReverse(buffer)); - Error.addSourceMessage(6000,{"Treating "+ sToken +" as 0"+sToken+". This is not standard Modelica and only done for compatibility with old code. Support for this feature may be removed in the future."},info); - ;} return UNSIGNED_REAL; // throw a warning -{endif} return ENDIF; -{endfor} return ENDFOR; -{endparfor} return ENDPARFOR; -{endwhile} return ENDWHILE; -{endwhen} return ENDWHEN; -{endmatchcontinue} return ENDMATCHCONTINUE; -{endmatch} return ENDMATCH; -{initialequation} return INITIALEQUATION; -{initialalgorithm} return INITIALALGORITHM; -{endident} return ENDCLASS; -"algorithm" return T_ALGORITHM; -"and" return T_AND; -"annotation" return T_ANNOTATION; -"block" return BLOCK; -"class" return CLASS; -"connect" return CONNECT; -"connector" return CONNECTOR; -"constant" return CONSTANT; -"discrete" return DISCRETE; -"der" return DER; -"defineunit" return DEFINEUNIT; -"each" return EACH; -"else" return ELSE; -"elseif" return ELSEIF; -"elsewhen" return ELSEWHEN; -"end" return T_END; -"enumeration" return ENUMERATION; -"equation" return EQUATION; -"encapsulated" return ENCAPSULATED; -"expandable" return EXPANDABLE; -"extends" return EXTENDS; -"constrainedby" return CONSTRAINEDBY; -"external" return EXTERNAL; -"false" return T_FALSE; -"final" return FINAL; -"flow" return FLOW; -"for" return FOR; -"function" return FUNCTION; -"if" return IF; -"import" return IMPORT; -"in" return T_IN; -"initial" return T_INITIAL; -"inner" return INNER; -"input" return T_INPUT; -"loop" return LOOP; -"model" return MODEL; -"not" return T_NOT; -"outer" return T_OUTER; -"operator" return OPERATOR; -"overload" return OVERLOAD; -"or" return T_OR; -"output" return T_OUTPUT; -"package" return T_PACKAGE; -"parameter" return PARAMETER; -"partial" return PARTIAL; -"protected" return PROTECTED; -"public" return PUBLIC; -"record" return RECORD; -"redeclare" return REDECLARE; -"replaceable" return REPLACEABLE; -"results" return RESULTS; -"then" return THEN; -"true" return T_TRUE; -"type" return TYPE; -"unsigned_real" return UNSIGNED_REAL; -"when" return WHEN; -"while" return WHILE; -"within" return WITHIN; -"return" return RETURN; -"break" return BREAK; - -"(" return LPAR; -")" return RPAR; -"[" return LBRACK; -"]" return RBRACK; -"{" return LBRACE; -"}" return RBRACE; -"==" return EQEQ; -"=" return EQUALS; -"," return COMMA; -":=" return ASSIGN; -"::" return COLONCOLON; -":" return COLON; -";" return SEMICOLON; - -"$Code" return CODE; -"$TypeName" return CODE_NAME; -"$Exp" return CODE_EXP; -"$Var" return CODE_VAR; - -"pure" return PURE; -"impure" return IMPURE; -"optimization" return T_OPTIMIZATION; -"parallel" return T_PARALLEL; -"parkernel" return T_KERNEL; -"parfor" return PARFOR; -"parlocal" return T_PARLOCAL; -"parglobal" return T_PARGLOBAL; - -".+" return PLUS_EW; -".-" return MINUS_EW; -".*" return STAR_EW; -"./" return SLASH_EW; -".^" return POWER_EW; - -"*" return STAR; -"-" return MINUS; -"+" return PLUS; -"<=" return LESSEQ; -"<>" return LESSGT; -"<" return LESS; -">" return GREATER; -">=" return GREATEREQ; - -"^" return POWER; -"/" return SLASH; - -"as" return AS; -"case" return CASE; -"equality" return EQUALITY; -"failure" return FAILURE; -"guard" return GUARD; -"local" return LOCAL; -"match" return MATCH; -"matchcontinue" return MATCHCONTINUE; -"uniontype" return UNIONTYPE; -"__" return ALLWILD; -"_" return WILD; -"subtypeof" return SUBTYPEOF; -"\%" return MOD; - -"stream" return STREAM; - -"\." return DOT; - -%"[\"][^\"]*[\"]" return STRING; - -{ident} return IDENT; -{digits} return UNSIGNED_INTEGER; - -"\"" { - BEGIN(c_string) keepBuffer; - } - -{ - "\\"+"\"" { keepBuffer; } - "\\"+"\\" { keepBuffer; } - "\"" { BEGIN(INITIAL) return STRING; } - [^\n] {keepBuffer; } - \n {keepBuffer; } -} - -"/\*" { - BEGIN(c_comment); - } - -{ - "\*/" { BEGIN(INITIAL); } - "/\*" { yyerror("Suspicious comment"); } - [^\n] ; - \n ; - <> { - yyerror("Unterminated comment"); - yyterminate(); - } -} - -"//" { - BEGIN(c_linecomment) keepBuffer; - } - - -{ - \n { BEGIN(INITIAL); } - [^\n] ; -} - - - -%% diff --git a/openmodelica/omcc/lexerModelicaDiff.l b/openmodelica/omcc/lexerModelicaDiff.l deleted file mode 100644 index 3d1e9c461fd..00000000000 --- a/openmodelica/omcc/lexerModelicaDiff.l +++ /dev/null @@ -1,175 +0,0 @@ -%{ - -%} - -%x c_comment -%x c_linecomment -%x c_string - -whitespace1 [ \t]+ -whitespace2 [ \t]*\n -letter [a-zA-Z] -wild [_] -digit [0-9] -digits {digit}+ -ident (({letter}|{wild})|['\'']({letter}|{digit}|[-*+/^=])*['\''])({letter}|{digit}|{wild})* -exponent ([e]|[E])([+]|[-])?{digits} -real {digits}[\.]({digits})?({exponent})? -real2 {digits}{exponent} -real3 [\.]{digits}({exponent})? -initialequation "initial"{whitespace}"equation" -initialalgorithm "initial"{whitespace}"algorithm" - -/* Lex style lexical syntax of tokens in the MODELICA language - * Including whitespace and comments as tokens in order to create textual - * diffs of Modelica code. - */ - -%% -{whitespace1} return WHITESPACE; -{whitespace2} return WHITESPACE; -{real} return UNSIGNED_REAL; -{real2} return UNSIGNED_REAL; -{real3} return UNSIGNED_REAL; -"algorithm" return T_ALGORITHM; -"and" return T_AND; -"annotation" return T_ANNOTATION; -"block" return BLOCK; -"class" return CLASS; -"connect" return CONNECT; -"connector" return CONNECTOR; -"constant" return CONSTANT; -"discrete" return DISCRETE; -"der" return DER; -"defineunit" return DEFINEUNIT; -"each" return EACH; -"else" return ELSE; -"elseif" return ELSEIF; -"elsewhen" return ELSEWHEN; -"end" return T_END; -"enumeration" return ENUMERATION; -"equation" return EQUATION; -"encapsulated" return ENCAPSULATED; -"expandable" return EXPANDABLE; -"extends" return EXTENDS; -"constrainedby" return CONSTRAINEDBY; -"external" return EXTERNAL; -"false" return T_FALSE; -"final" return FINAL; -"flow" return FLOW; -"for" return FOR; -"function" return FUNCTION; -"if" return IF; -"import" return IMPORT; -"in" return T_IN; -"initial" return T_INITIAL; -"inner" return INNER; -"input" return T_INPUT; -"loop" return LOOP; -"model" return MODEL; -"not" return T_NOT; -"outer" return T_OUTER; -"operator" return OPERATOR; -"overload" return OVERLOAD; -"or" return T_OR; -"output" return T_OUTPUT; -"package" return T_PACKAGE; -"parameter" return PARAMETER; -"partial" return PARTIAL; -"protected" return PROTECTED; -"public" return PUBLIC; -"record" return RECORD; -"redeclare" return REDECLARE; -"replaceable" return REPLACEABLE; -"results" return RESULTS; -"then" return THEN; -"true" return T_TRUE; -"type" return TYPE; -"when" return WHEN; -"while" return WHILE; -"within" return WITHIN; -"return" return RETURN; -"break" return BREAK; - -"(" return LPAR; -")" return RPAR; -"[" return LBRACK; -"]" return RBRACK; -"{" return LBRACE; -"}" return RBRACE; -"==" return EQEQ; -"=" return EQUALS; -"," return COMMA; -":=" return ASSIGN; -"::" return COLONCOLON; -":" return COLON; -";" return SEMICOLON; - -"pure" return PURE; -"impure" return IMPURE; -"optimization" return T_OPTIMIZATION; - -".+" return PLUS_EW; -".-" return MINUS_EW; -".*" return STAR_EW; -"./" return SLASH_EW; -".^" return POWER_EW; - -"*" return STAR; -"-" return MINUS; -"+" return PLUS; -"<=" return LESSEQ; -"<>" return LESSGT; -"<" return LESS; -">" return GREATER; -">=" return GREATEREQ; - -"^" return POWER; -"/" return SLASH; - -"subtypeof" return SUBTYPEOF; - -"stream" return STREAM; - -"\." return DOT; - -{ident} return IDENT; -{digits} return UNSIGNED_INTEGER; - -"\"" { - BEGIN(c_string) keepBuffer; - } - -{ - "\\"+"\"" { keepBuffer; } - "\\"+"\\" { keepBuffer; } - "\"" { BEGIN(INITIAL) return STRING; } - [^\n] {keepBuffer; } - \n {keepBuffer; } -} - -"/\*" { - BEGIN(c_comment) keepBuffer; - } - -{ - "\*/" { BEGIN(INITIAL); return BLOCK_COMMENT; } - [^\n] {keepBuffer;} - \n {keepBuffer;} - <> { - yyerror("Unterminated comment"); - yyterminate(); - } -} - -"//" { - BEGIN(c_linecomment) keepBuffer; - } - - -{ - \n { BEGIN(INITIAL); return LINE_COMMENT; } - [^\n] { keepBuffer; }; -} - -%% diff --git a/openmodelica/omcc/parserModelica.y b/openmodelica/omcc/parserModelica.y deleted file mode 100644 index 670404ee0d4..00000000000 --- a/openmodelica/omcc/parserModelica.y +++ /dev/null @@ -1,1650 +0,0 @@ -%{ -import Absyn; -import OMCCTypes; -import System; - -constant list lstSemValue3 = {}; -constant list lstSemValue = { - "error", "$undefined", "ALGORITHM", "AND", "ANNOTATION", - "BLOCK", "CLASS", "CONNECT", "CONNECTOR", "CONSTANT", "DISCRETE", "DER", - "DEFINEUNIT", "EACH", "ELSE", "ELSEIF", "ELSEWHEN", "END", - "ENUMERATION", "EQUATION", "ENCAPSULATED", "EXPANDABLE", "EXTENDS", - "CONSTRAINEDBY", "EXTERNAL", "FALSE", "FINAL", "FLOW", "FOR", - "FUNCTION", "IF", "IMPORT", "IN","INITIALEQUATION","INITIALALGORITHM","T_INITIAL", "INNER", "INPUT", - "LOOP", "MODEL", "NOT", "OUTER", "OPERATOR", "OVERLOAD", "OR", - "OUTPUT", "PACKAGE", "PARAMETER", "PARTIAL", "PROTECTED", "PUBLIC", - "RECORD", "REDECLARE", "REPLACEABLE", "RESULTS", "THEN", "TRUE", - "TYPE", "REAL", "WHEN", "WHILE", "WITHIN", "RETURN", "BREAK", - ".", "(", ")", "[", "]", "{", "}", "=", - "ASSIGN", "COMMA", "COLON", "SEMICOLON", "CODE", "CODE_NAME", "CODE_EXP", - "CODE_VAR", "PURE", "IMPURE", "Identity", "DIGIT", "INTEGER", - "*", "-", "+", "<=", "<>", "<", ">", - ">=", "==", "^", "SLASH","OPTIMIZATION","PARFOR","ENDPARFOR","PARLOCAL","PARGLOBAL", - "PARALLEL","KERNEL","STRING", ".+", ".-", - ".*", "./", ".*", "STREAM", "AS", "CASE", "EQUALITY", - "FAILURE", "GUARD", "LOCAL", "MATCH", "MATCHCONTINUE", "UNIONTYPE", - "ALLWILD", "WILD", "SUBTYPEOF", "COLONCOLON", "MOD", "ENDIF", "ENDFOR", - "ENDWHILE", "ENDWHEN", "ENDCLASS", "ENDMATCHCONTINUE", "ENDMATCH", - "$accept", - "program", "within", "classes_list", "class", "classprefix", - "encapsulated", "partial", "restriction","classdef2","classdef", - "classdefenumeration", "classdefderived", "enumeration", "enumlist", - "enumliteral", "classparts", "classpart", "restClass", - "algorithmsection", "algorithmitem", "algorithm", "if_algorithm", - "algelseifs", "algelseif", "when_algorithm", "algelsewhens", - "algelsewhen", "equationsection", "equationitem", "equation", - "when_equation", "elsewhens", "elsewhen", "foriterators", "foriterator", - "if_equation", "elseifs", "elseif", "elementItems", "elementItem", - "element", "componentclause", "componentitems", "componentitem", - "component", "modification", "redeclarekeywords", "innerouter", - "importelementspec", "classelementspec", "import", "elementspec", - "elementAttr","parallelism", "variability", "direction", "typespec", "arrayComplex", - "typespecs", "arraySubscripts", "arrayDim", "functioncall", - "functionargs", "namedargs", "namedarg", "exp", "matchcont", "if_exp", - "expelseifs", "expelseif", "matchlocal", "cases", "case", "casearg", - "simpleExp", "headtail", "rangeExp", "logicexp", "logicterm", - "logfactor", "relterm", "addterm", "term", "factor", "expElement", - "tuple", "explist", "explist2", "cref", "woperator", "soperator", - "power", "relOperator", "path", "ident", "string", "comment"}; - -uniontype AstItem - record TOKEN - OMCCTypes.Token tok; - end TOKEN; - record BOOLEAN - Boolean bool; - end BOOLEAN; - record PROGRAM - Absyn.Program program; - end PROGRAM; - record WITHIN - Absyn.Within _within; - end WITHIN; - record CLASSES - list classes; - end CLASSES; - record CLASS - Absyn.Class _class; - end CLASS; - record STRING - String string; - end STRING; - record PATH - Absyn.Path path; - end PATH; - record CLASSDEF - Absyn.ClassDef classdef; - end CLASSDEF; - record CLASSPART - Absyn.ClassPart part; - end CLASSPART; - record CLASSPARTS - list parts; - end CLASSPARTS; - record IMPORT - Absyn.Import _import; - end IMPORT; - record ELEMENTITEM - Absyn.ElementItem item; - end ELEMENTITEM; - record ELEMENTITEMS - list items; - end ELEMENTITEMS; - record ELEMENT - Absyn.Element element; - end ELEMENT; - record ELEMENTSPEC - Absyn.ElementSpec spec; - end ELEMENTSPEC; - record ELEMENTATTRIBUTES - Absyn.ElementAttributes attrs; - end ELEMENTATTRIBUTES; - record COMMENT - Absyn.Comment comment; - end COMMENT; - record DIRECTION - Absyn.Direction direction; - end DIRECTION; - record EXP - Absyn.Exp exp; - end EXP; - record EXPS - list exps; - end EXPS; - record MATRIX - list> matrix; - end MATRIX; - record SUBSCRIPT - Absyn.Subscript subscript; - end SUBSCRIPT; - record ARRAYDIM - list dim; - end ARRAYDIM; - record OPERATOR - Absyn.Operator op; - end OPERATOR; - record CASE - Absyn.Case _case; - end CASE; - record CASES - list cases; - end CASES; - record MATCHTYPE - Absyn.MatchType matchType; - end MATCHTYPE; - record RESTRICTION - Absyn.Restriction restriction; - end RESTRICTION; - record INNEROUTER - Absyn.InnerOuter innerOuter; - end INNEROUTER; - record CREF - Absyn.ComponentRef cref; - end CREF; - record PARALLELISM - Absyn.Parallelism parallelism; - end PARALLELISM; - record VARIABILITY - Absyn.Variability variability; - end VARIABILITY; - record REDECLAREKEYWORDS - Absyn.RedeclareKeywords redeclareKeywords; - end REDECLAREKEYWORDS; - record NAMEDARG - Absyn.NamedArg arg; - end NAMEDARG; - record TYPESPEC - Absyn.TypeSpec spec; - end TYPESPEC; - record TYPESPECS - list specs; - end TYPESPECS; - record COMPONENTITEM - Absyn.ComponentItem item; - end COMPONENTITEM; - record COMPONENTITEMS - list items; - end COMPONENTITEMS; - record COMPONENT - Absyn.Component component; - end COMPONENT; - record EQUATIONITEM - Absyn.EquationItem item; - end EQUATIONITEM; - record EQUATIONITEMS - list items; - end EQUATIONITEMS; - record EQUATION - Absyn.Equation eq; - end EQUATION; - record ELSEIF - tuple> elseIf; - end ELSEIF; - record ELSEIFS - list>> elseIfs; - end ELSEIFS; - record FORITERATOR - Absyn.ForIterator iterator; - end FORITERATOR; - record FORITERATORS - list iterators; - end FORITERATORS; - record ELSEWHEN - tuple> elseWhen; - end ELSEWHEN; - record ELSEWHENS - list>> elseWhens; - end ELSEWHENS; - record FUNCTIONARGS - Absyn.FunctionArgs args; - end FUNCTIONARGS; - record NAMEDARGS - list arg; - end NAMEDARGS; - record ALGORITHMITEM - Absyn.AlgorithmItem item; - end ALGORITHMITEM; - record ALGORITHMITEMS - list items; - end ALGORITHMITEMS; - record ALGORITHM - Absyn.Algorithm alg; - end ALGORITHM; - record ALGELSEIF - tuple> elseIf; - end ALGELSEIF; - record ALGELSEIFS - list>> elseIfs; - end ALGELSEIFS; - record ALGELSEWHEN - tuple> elseWhen; - end ALGELSEWHEN; - record ALGELSEWHENS - list>> elseWhens; - end ALGELSEWHENS; - record EXPELSEIF - tuple elseIf; - end EXPELSEIF; - record EXPELSEIFS - list> elseIfs; - end EXPELSEIFS; - record ENUMDEF - Absyn.EnumDef def; - end ENUMDEF; - record ENUMLITERAL - Absyn.EnumLiteral literal; - end ENUMLITERAL; - record ENUMLITERALS - list literals; - end ENUMLITERALS; - record MODIFICATION - Absyn.Modification mod; - end MODIFICATION; - record CLASSPREFIX - Boolean encap,part; - end CLASSPREFIX; - record ELEMENTARG - Absyn.ElementArg arg; - end ELEMENTARG; - record ELEMENTARGS - list args; - end ELEMENTARGS; - record EACH - Absyn.Each _each; - end EACH; - record EQMOD - Absyn.EqMod mod; - end EQMOD; - record EXTERNALDECL - Absyn.ExternalDecl decl; - end EXTERNALDECL; - record ANNOTATION - Absyn.Annotation ann; - end ANNOTATION; - record CONSTRAINCLASS - Absyn.ConstrainClass cc; - end CONSTRAINCLASS; -end AstItem; - -%} - -%token T_ALGORITHM -%token T_AND -%token T_ANNOTATION -%token BLOCK -%token CLASS -%token CONNECT -%token CONNECTOR -%token CONSTANT -%token DISCRETE -%token DER -%token DEFINEUNIT -%token EACH -%token ELSE -%token ELSEIF -%token ELSEWHEN -%token T_END -%token ENUMERATION -%token EQUATION -%token ENCAPSULATED -%token EXPANDABLE -%token EXTENDS -%token CONSTRAINEDBY -%token EXTERNAL -%token T_FALSE -%token FINAL -%token FLOW -%token FOR -%token FUNCTION -%token IF -%token IMPORT -%token T_IN -%token INITIALEQUATION -%token INITIALALGORITHM -%token T_INITIAL -%token INNER -%token T_INPUT -%token LOOP -%token MODEL -%token T_NOT -%token T_OUTER -%token OPERATOR -%token OVERLOAD -%token T_OR -%token T_OUTPUT -%token T_PACKAGE -%token PARAMETER -%token PARTIAL -%token PROTECTED -%token PUBLIC -%token RECORD -%token REDECLARE -%token REPLACEABLE -%token RESULTS -%token THEN -%token T_TRUE -%token TYPE -%token UNSIGNED_REAL -%token WHEN -%token WHILE -%token WITHIN -%token RETURN -%token BREAK -%token DOT -%token LPAR -%token RPAR -%token LBRACK -%token RBRACK -%token LBRACE -%token RBRACE -%token EQUALS -%token ASSIGN -%token COMMA -%token COLON -%token SEMICOLON -%token CODE -%token CODE_NAME -%token CODE_EXP -%token CODE_VAR -%token PURE -%token IMPURE -%token IDENT -%token DIGIT -%token UNSIGNED_INTEGER - -%token STAR -%token MINUS -%token PLUS -%token LESSEQ -%token LESSGT -%token LESS -%token GREATER -%token GREATEREQ -%token EQEQ -%token POWER -%token SLASH -%token T_OPTIMIZATION -%token PARFOR -%token ENDPARFOR -%token T_PARLOCAL -%token T_PARGLOBAL -%token T_PARALLEL -%token T_KERNEL -%token STRING - -%token PLUS_EW -%token MINUS_EW -%token STAR_EW -%token SLASH_EW -%token POWER_EW - -%token STREAM - -%token AS -%token CASE -%token EQUALITY -%token FAILURE -%token GUARD -%token LOCAL -%token MATCH -%token MATCHCONTINUE -%token UNIONTYPE -%token ALLWILD -%token WILD -%token SUBTYPEOF -%token COLONCOLON -%token MOD -%token ENDIF -%token ENDFOR -%token ENDWHILE -%token ENDWHEN -%token ENDCLASS -%token ENDMATCHCONTINUE -%token ENDMATCH -//%expect 42 - - - -%% - -/* Yacc BNF grammar of the Modelica+MetaModelica language */ - -program : classes_list - { $$ = PROGRAM(Absyn.PROGRAM(getClasses($1),Absyn.TOP(),Absyn.TIMESTAMP(0.0,1.0))); } - | within classes_list - { $$ = PROGRAM(Absyn.PROGRAM(getClasses($2),getWithin($1),Absyn.TIMESTAMP(0.0,1.0))); } - - -within : WITHIN path SEMICOLON { $$ = WITHIN(Absyn.WITHIN(getPath($2))); } - - - -classes_list : class2 SEMICOLON { $$ = CLASSES(getClass($1)::{}); } - | class2 SEMICOLON classes_list { $$ = CLASSES(getClass($1)::getClasses($3)); } - /* restriction IDENT classdef T_END IDENT SEMICOLON - { if (not stringEqual($2,$5) ) then print(Types.printInfoError(info) + " Error: The identifier at start and end are different '" + $2 + "'"); - true = ($2 == $5); - end if; $$[Class] = Absyn.CLASS($2,false,false,false,$1[Restriction],$3[ClassDef],yyinfo); } - */ - -class2 : FINAL classprefix restriction IDENT classdef { $$ = CLASS(Absyn.CLASS(getString($4),getClassPrefixPartial($1),true,getClassPrefixEncapsulated($1),getRestriction($3),getClassDef($5),yyinfo)); } - | FINAL restriction IDENT classdef - { $$ = CLASS(Absyn.CLASS(getString($3),false,true,false,getRestriction($2),getClassDef($4),yyinfo)); } - | class { $$ = $1; } - -class : restriction IDENT classdef - { $$ = CLASS(Absyn.CLASS(getString($2),false,false,false,getRestriction($1),getClassDef($3),yyinfo)); } - | restriction EXTENDS IDENT elementargs classparts ENDCLASS - { $$ = CLASS(Absyn.CLASS(getString($3),false,false,false,getRestriction($1),Absyn.CLASS_EXTENDS(getString($3),getElementArgs($4),NONE(),getClassParts($5),{}),yyinfo)); } - | restriction EXTENDS IDENT elementargs string classparts ENDCLASS - { $$ = CLASS(Absyn.CLASS(getString($3),false,false,false,getRestriction($1),Absyn.CLASS_EXTENDS(getString($3),getElementArgs($4),SOME(getString($5)),getClassParts($6),{}),yyinfo)); } - | classprefix restriction IDENT classdef - { $$ = CLASS(Absyn.CLASS(getString($3),getClassPrefixPartial($1),false,getClassPrefixEncapsulated($1),getRestriction($2),getClassDef($4),yyinfo)); } - | classprefix restriction EXTENDS IDENT elementargs classparts ENDCLASS - { $$ = CLASS(Absyn.CLASS(getString($4),getClassPrefixPartial($1),false,getClassPrefixEncapsulated($1),getRestriction($2),Absyn.CLASS_EXTENDS(getString($4),getElementArgs($5),NONE(),getClassParts($6),{}),yyinfo)); } - | classprefix restriction EXTENDS IDENT elementargs string classparts ENDCLASS - { $$ = CLASS(Absyn.CLASS(getString($4),getClassPrefixPartial($1),false,getClassPrefixEncapsulated($1),getRestriction($2),Absyn.CLASS_EXTENDS(getString($4),getElementArgs($5),SOME(getString($6)),getClassParts($7),{}),yyinfo)); } - -classdef : string ENDCLASS - { $$ = CLASSDEF(Absyn.PARTS({},{},{},{},SOME(getString($1)))); } - |ENDCLASS - { $$ = CLASSDEF(Absyn.PARTS({},{},{},{},NONE())); } - - |classparts ENDCLASS - { $$ = CLASSDEF(Absyn.PARTS({},{},getClassParts($1),{},NONE())); } - - |classparts annotation SEMICOLON ENDCLASS - { $$ = CLASSDEF(Absyn.PARTS({},{},getClassParts($1),{getAnnotation($2)},NONE())); } - - |LPAR namedargs RPAR classparts ENDCLASS - { $$ = CLASSDEF(Absyn.PARTS({},getNamedArgs($2),getClassParts($4),{},NONE())); } - - | string classparts ENDCLASS - { $$ = CLASSDEF(Absyn.PARTS({},{},getClassParts($2),{},SOME(getString($1)))); } - - | string classparts annotation SEMICOLON ENDCLASS - { $$ = CLASSDEF(Absyn.PARTS({},{},getClassParts($2),{getAnnotation($3)},SOME(getString($1)))); } - - | classdefenumeration - { $$ = $1; }; - | classdefderived - { $$ = $1; }; - -classprefix : ENCAPSULATED partial - { $$ = CLASSPREFIX(true,getBoolean($2)); } - | PARTIAL - { $$ = CLASSPREFIX(false,true); } - - -// encapsulated : ENCAPSULATED { $$[Boolean] = true; } -// | /* empty */ { $$[Boolean] = false; } - -partial : PARTIAL { $$ = BOOLEAN(true); } - | /* empty */ { $$ = BOOLEAN(false); } - -final : FINAL { $$ = BOOLEAN(true); } - | /* empty */ { $$ = BOOLEAN(false); } - -restriction : CLASS { $$ = RESTRICTION(Absyn.R_CLASS()); } - | MODEL { $$ = RESTRICTION(Absyn.R_MODEL()); } - | RECORD { $$ = RESTRICTION(Absyn.R_RECORD()); } - | T_PACKAGE { $$ = RESTRICTION(Absyn.R_PACKAGE()); } - | TYPE { $$ = RESTRICTION(Absyn.R_TYPE()); } - | T_OPTIMIZATION { $$ = RESTRICTION(Absyn.R_OPTIMIZATION()); } - - | FUNCTION { $$ = RESTRICTION(Absyn.R_FUNCTION(Absyn.FR_NORMAL_FUNCTION(Absyn.PURE()))); } - /* PARMODELICA EXTENSIONS */ - | T_PARALLEL FUNCTION { $$ = RESTRICTION(Absyn.R_FUNCTION(Absyn.FR_PARALLEL_FUNCTION())); } - | T_KERNEL FUNCTION { $$ = RESTRICTION(Absyn.R_FUNCTION(Absyn.FR_KERNEL_FUNCTION())); } - | UNIONTYPE { $$ = RESTRICTION(Absyn.R_UNIONTYPE()); } - | BLOCK { $$ = RESTRICTION(Absyn.R_BLOCK()); } - | CONNECTOR { $$ = RESTRICTION(Absyn.R_CONNECTOR()); } - | EXPANDABLE CONNECTOR { $$ = RESTRICTION(Absyn.R_EXP_CONNECTOR()); } - | ENUMERATION { $$ = RESTRICTION(Absyn.R_ENUMERATION()); } - | OPERATOR FUNCTION { $$ = RESTRICTION(Absyn.R_FUNCTION(Absyn.FR_OPERATOR_FUNCTION())); } - | OPERATOR RECORD { $$ = RESTRICTION(Absyn.R_OPERATOR_RECORD()); } - | OPERATOR { $$ = RESTRICTION(Absyn.R_OPERATOR()); } - - - -classdefenumeration : EQUALS ENUMERATION LPAR enumeration RPAR comment - { $$ = CLASSDEF(Absyn.ENUMERATION(getEnumDef($4),SOME(getComment($6)))); } - -classdefderived : EQUALS typespec elementargs2 comment - { $$ = CLASSDEF(Absyn.DERIVED(getTypeSpec($2),Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(), Absyn.BIDIR(),{}),getElementArgs($3),SOME(getComment($4)))); } - | EQUALS elementAttr typespec elementargs2 comment - { $$ = CLASSDEF(Absyn.DERIVED(getTypeSpec($3),getElementAttributes($2),getElementArgs($4),SOME(getComment($5)))); } - - -enumeration : enumlist { $$ = ENUMDEF(Absyn.ENUMLITERALS(getEnumLiterals($1))); } - | COLON { $$ = ENUMDEF(Absyn.ENUM_COLON()); } - -enumlist : enumliteral { $$ = ENUMLITERALS(getEnumLiteral($1)::{}); } - | enumliteral COMMA enumlist { $$ = ENUMLITERALS(getEnumLiteral($1)::getEnumLiterals($3)); } - -enumliteral : ident comment { $$ = ENUMLITERAL(Absyn.ENUMLITERAL(getString($1),SOME(getComment($2)))); } - -classparts : classpart { $$ = CLASSPARTS(getClassPart($1)::{}); } - | classpart classparts { $$ = CLASSPARTS(getClassPart($1)::getClassParts($2)); } - |/*EMPTY*/ { $$ = CLASSPARTS({}); } - -classpart : elementItems { $$ = CLASSPART(Absyn.PUBLIC(getElementItems($1))); } - | restClass { $$ = $1; } - -restClass : PUBLIC optelement { $$ = CLASSPART(Absyn.PUBLIC(getElementItems($2))); } - | PROTECTED optelement { $$ = CLASSPART(Absyn.PROTECTED(getElementItems($2))); } - | EQUATION optequationsection { $$ = CLASSPART(Absyn.EQUATIONS(getEquationItems($2))); } - | T_ALGORITHM optalgorithmsection { $$ = CLASSPART(Absyn.ALGORITHMS(getAlgorithmItems($2))); } - | INITIALEQUATION equationsection { $$ = CLASSPART(Absyn.INITIALEQUATIONS(getEquationItems($2))); } - | INITIALALGORITHM algorithmsection { $$ = CLASSPART(Absyn.INITIALALGORITHMS(getAlgorithmItems($2))); } - | external { $$ = $1; } - - -optelement : elementItems { $$ = $1; } - | /* empty */ { $$ = ELEMENTITEMS({}); } - -optequationsection : equationsection { $$ = $1; } - | /* empty */ { $$ = EQUATIONITEMS({}); } - -optalgorithmsection : algorithmsection { $$ = $1; } - | /* empty */ { $$ = ALGORITHMITEMS({}); } - -external : EXTERNAL SEMICOLON { $$ = CLASSPART(Absyn.EXTERNAL(Absyn.EXTERNALDECL(NONE(),NONE(),NONE(),{},NONE()),NONE())); } - | EXTERNAL externalDecl SEMICOLON { $$ = CLASSPART(Absyn.EXTERNAL(getExternalDecl($2),NONE())); } - | EXTERNAL externalDecl SEMICOLON annotation SEMICOLON { $$ = CLASSPART(Absyn.EXTERNAL(getExternalDecl($2),SOME(getAnnotation($3)))); } - - -externalDecl : string { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(NONE(),SOME(getString($1)),NONE(),{},NONE())); } - | string annotation { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(NONE(),SOME(getString($1)),NONE(),{},SOME(getAnnotation($2)))); } - | string cref EQUALS ident LPAR explist2 RPAR { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(SOME(getString($4)),SOME(getString($1)),SOME(getCref($2)),getExps($6),NONE())); } - | string cref EQUALS ident LPAR explist2 RPAR annotation { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(SOME(getString($4)),SOME(getString($1)),SOME(getCref($2)),getExps($6),SOME(getAnnotation($8)))); } - | string ident LPAR explist2 RPAR annotation { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(SOME(getString($2)),SOME(getString($1)),NONE(),getExps($4),SOME(getAnnotation($6)))); } - | string ident LPAR explist2 RPAR { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(SOME(getString($2)),SOME(getString($1)),NONE(),getExps($4),NONE())); } - | cref EQUALS ident LPAR explist2 RPAR { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(SOME(getString($3)),NONE(),SOME(getCref($1)),getExps($5),NONE())); } - | cref EQUALS ident LPAR explist2 RPAR annotation { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(SOME(getString($3)),NONE(),SOME(getCref($1)),getExps($5),SOME(getAnnotation($7)))); } - | ident LPAR explist2 RPAR annotation { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(SOME(getString($1)),NONE(),NONE(),getExps($3),SOME(getAnnotation($5)))); } - | ident LPAR explist2 RPAR { $$ = EXTERNALDECL(Absyn.EXTERNALDECL(SOME(getString($1)),NONE(),NONE(),getExps($3),NONE())); } - - -/* ALGORITHMS */ - -algorithmsection : algorithmitem SEMICOLON { $$ = ALGORITHMITEMS(getAlgorithmItem($1)::{}); } - | algorithmitem SEMICOLON algorithmsection { $$ = ALGORITHMITEMS(getAlgorithmItem($1)::getAlgorithmItems($3)); } - | /*empty*/ { $$ = ALGORITHMITEMS({}); } - -algorithmitem : algorithm comment - { $$ = ALGORITHMITEM(Absyn.ALGORITHMITEM(getAlgorithm($1),SOME(getComment($2)),yyinfo)); } - -algorithm : simpleExp ASSIGN exp - { $$ = ALGORITHM(Absyn.ALG_ASSIGN(getExp($1),getExp($3))); } - | cref functioncall - { $$ = ALGORITHM(Absyn.ALG_NORETCALL(getCref($1),getFunctionArgs($2))); } - | RETURN - { $$ = ALGORITHM(Absyn.ALG_RETURN()); } - | BREAK - { $$ = ALGORITHM(Absyn.ALG_BREAK()); } - | if_algorithm - { $$ = $1; } - | when_algorithm - { $$ = $1; } - | FOR foriterators LOOP algorithmsection ENDFOR - { $$ = ALGORITHM(Absyn.ALG_FOR(getForIterators($2),getAlgorithmItems($4))); } - /*PARMODELICA EXTENSIONS*/ - | PARFOR foriterators LOOP algorithmsection ENDPARFOR - { $$ = ALGORITHM(Absyn.ALG_PARFOR(getForIterators($2),getAlgorithmItems($4))); } - - | WHILE exp LOOP algorithmsection ENDWHILE - { $$ = ALGORITHM(Absyn.ALG_WHILE(getExp($2),getAlgorithmItems($4))); } - -if_algorithm : IF exp THEN ENDIF { $$ = ALGORITHM(Absyn.ALG_IF(getExp($2),{},{},{})); } // warning empty if - | IF exp THEN algorithmsection ENDIF { $$ = ALGORITHM(Absyn.ALG_IF(getExp($2),getAlgorithmItems($4),{},{})); } - | IF exp THEN algorithmsection ELSE algorithmsection ENDIF { $$ = ALGORITHM(Absyn.ALG_IF(getExp($2),getAlgorithmItems($4),{},getAlgorithmItems($6))); } - | IF exp THEN algorithmsection ELSE ENDIF { $$ = ALGORITHM(Absyn.ALG_IF(getExp($2),getAlgorithmItems($4),{},{})); } - | IF exp THEN algorithmsection algelseifs ENDIF { $$ = ALGORITHM(Absyn.ALG_IF(getExp($2),getAlgorithmItems($4),getAlgElseIfs($5),{})); } - | IF exp THEN algorithmsection algelseifs ELSE algorithmsection ENDIF { $$ = ALGORITHM(Absyn.ALG_IF(getExp($2),getAlgorithmItems($4),getAlgElseIfs($5),getAlgorithmItems($7))); } - | IF exp THEN algorithmsection algelseifs ELSE ENDIF { $$ = ALGORITHM(Absyn.ALG_IF(getExp($2),getAlgorithmItems($4),getAlgElseIfs($5),{})); } - -algelseifs : algelseif { $$ = ALGELSEIFS(getAlgElseIf($1)::{}); } - | algelseif algelseifs { $$ = ALGELSEIFS(getAlgElseIf($1)::getAlgElseIfs($2)); } - | /*empty*/ { $$ = ALGELSEIFS({}); } - -algelseif : ELSEIF exp THEN algorithmsection { $$ = ALGELSEIF((getExp($2),getAlgorithmItems($4))); } - -when_algorithm : WHEN exp THEN algorithmsection ENDWHEN - { $$ = ALGORITHM(Absyn.ALG_WHEN_A(getExp($2),getAlgorithmItems($4),{})); } - | WHEN exp THEN algorithmsection algelsewhens ENDWHEN - { $$ = ALGORITHM(Absyn.ALG_WHEN_A(getExp($2),getAlgorithmItems($4),getAlgElseWhens($5))); } - -algelsewhens : algelsewhen { $$ = ALGELSEWHENS(getAlgElseWhen($1)::{}); } - | algelsewhen algelsewhens { $$ = ALGELSEWHENS(getAlgElseWhen($1)::getAlgElseWhens($2)); } - -algelsewhen : ELSEWHEN exp THEN algorithmsection { $$ = ALGELSEWHEN((getExp($2),getAlgorithmItems($4))); } - - -/* EQUATIONS */ -equationsection : equationitem SEMICOLON { $$ = EQUATIONITEMS(getEquationItem($1)::{}); } - | equationitem SEMICOLON equationsection { $$ = EQUATIONITEMS(getEquationItem($1)::getEquationItems($3)); } - | /*empty */ { $$ = EQUATIONITEMS({}); } - -equationitem : equation comment - { $$ = EQUATIONITEM(Absyn.EQUATIONITEM(getEquation($1),SOME(getComment($2)),yyinfo)); } - -equation : exp EQUALS exp - { $$ = EQUATION(Absyn.EQ_EQUALS(getExp($1),getExp($3))); } - | if_equation - { $$ = $1; } - | when_equation - { $$ = $1; } - | CONNECT LPAR cref COMMA cref RPAR - { $$ = EQUATION(Absyn.EQ_CONNECT(getCref($3),getCref($5))); } - | FOR foriterators LOOP equationsection ENDFOR - { $$ = EQUATION(Absyn.EQ_FOR(getForIterators($2),getEquationItems($4))); } - | cref functioncall { $$ = EQUATION(Absyn.EQ_NORETCALL(getCref($1),getFunctionArgs($2))); } - -when_equation : WHEN exp THEN equationsection ENDWHEN - { $$ = EQUATION(Absyn.EQ_WHEN_E(getExp($2),getEquationItems($4),{})); } - | WHEN exp THEN equationsection elsewhens ENDWHEN - { $$ = EQUATION(Absyn.EQ_WHEN_E(getExp($2),getEquationItems($4),getElseWhens($5))); } - -elsewhens : elsewhen { $$ = ELSEWHENS(getElseWhen($1)::{}); } - | elsewhen elsewhens { $$ = ELSEWHENS(getElseWhen($1)::getElseWhens($2)); } - -elsewhen : ELSEWHEN exp THEN equationsection { $$ = ELSEWHEN((getExp($2),getEquationItems($4))); } - -foriterators : foriterator { $$ = FORITERATORS(getForIterator($1)::{}); } - | foriterator COMMA foriterators { $$ = FORITERATORS(getForIterator($1)::getForIterators($2)); } - -foriterator : IDENT { $$ = FORITERATOR(Absyn.ITERATOR(getString($1),NONE(),NONE())); } - | IDENT T_IN exp { $$ = FORITERATOR(Absyn.ITERATOR(getString($1),NONE(),SOME(getExp($3)))); } - -if_equation : IF exp THEN equationsection ENDIF - { $$ = EQUATION(Absyn.EQ_IF(getExp($2),getEquationItems($4),{},{})); } - | IF exp THEN equationsection ELSE equationsection ENDIF - { $$ = EQUATION(Absyn.EQ_IF(getExp($2),getEquationItems($4),{},getEquationItems($6))); } - | IF exp THEN equationsection ELSE ENDIF - { $$ = EQUATION(Absyn.EQ_IF(getExp($2),getEquationItems($4),{},{})); } - | IF exp THEN equationsection elseifs ENDIF - { $$ = EQUATION(Absyn.EQ_IF(getExp($2),getEquationItems($4),getElseIfs($5),{})); } - | IF exp THEN equationsection elseifs ELSE equationsection ENDIF - { $$ = EQUATION(Absyn.EQ_IF(getExp($2),getEquationItems($4),getElseIfs($5),getEquationItems($7))); } - | IF exp THEN equationsection elseifs ELSE ENDIF - { $$ = EQUATION(Absyn.EQ_IF(getExp($2),getEquationItems($4),getElseIfs($5),{})); } - -elseifs : elseif { $$ = ELSEIFS(getElseIf($1)::{}); } - | elseif elseifs { $$ = ELSEIFS(getElseIf($1)::getElseIfs($2)); } - |/*empty */ { $$ = ELSEIFS({}); } - -elseif : ELSEIF exp THEN equationsection { $$ = ELSEIF((getExp($2),getEquationItems($4))); } - -/* Expressions and Elements */ - -elementItems : elementItem { $$ = ELEMENTITEMS(getElementItemAllowAnnotation($1)::{}); } - | elementItem elementItems { $$ = ELEMENTITEMS(getElementItem($1)::getElementItems($2)); } - - -elementItem : element SEMICOLON { $$ = ELEMENTITEM(Absyn.ELEMENTITEM(getElement($1))); } - /* | annotation SEMICOLON { $$ = ELEMENTITEM(Absyn.ANNOTATIONITEM(getAnnotation($1))); } */ - -element : componentclause - { $$ = $1; } - | classElement2 - { $$ = $1; } - | importelementspec - { $$ = ELEMENT(Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),getElementSpec($1),yyinfo,NONE())); } - | extends - { $$ = ELEMENT(Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),getElementSpec($1),yyinfo,NONE())); } - | unitclause - { $$ = $1; } - -unitclause : DEFINEUNIT ident { $$ = ELEMENT(Absyn.DEFINEUNIT(getString($2),{})); } - | DEFINEUNIT ident LPAR namedargs RPAR { $$ = ELEMENT(Absyn.DEFINEUNIT(getString($2),getNamedArgs($4))); } - - -classElement2 : classelementspec - { $$ = ELEMENT(Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),getElementSpec($1),yyinfo,NONE())); } - - |classelementspec constraining_clause - { $$ = ELEMENT(Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),getElementSpec($1),yyinfo,SOME(getConstrainClass($2)))); } - - | REDECLARE classelementspec - { $$ = ELEMENT(Absyn.ELEMENT(false,SOME(Absyn.REDECLARE()),Absyn.NOT_INNER_OUTER(),getElementSpec($2),yyinfo,NONE())); } - - - - -componentclause : elementspec - { $$ = ELEMENT(Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),getElementSpec($1),yyinfo,NONE())); } - | innerouter elementspec - { $$ = ELEMENT(Absyn.ELEMENT(false,NONE(),getInnerOuter($1),getElementSpec($2),yyinfo,NONE())); } - | redeclarekeywords final innerouter elementspec - { $$ = ELEMENT(Absyn.ELEMENT(getBoolean($2),SOME(getRedeclareKeywords($1)),getInnerOuter($3),getElementSpec($4),yyinfo,NONE())); } - | redeclarekeywords final elementspec - { $$ = ELEMENT(Absyn.ELEMENT(getBoolean($2),SOME(getRedeclareKeywords($1)),Absyn.NOT_INNER_OUTER(),getElementSpec($3),yyinfo,NONE())); } - | redeclarekeywords final elementspec constraining_clause - { $$ = ELEMENT(Absyn.ELEMENT(getBoolean($2),SOME(getRedeclareKeywords($1)),Absyn.NOT_INNER_OUTER(),getElementSpec($3),yyinfo,SOME(getConstrainClass($4)))); } - | FINAL elementspec - { $$ = ELEMENT(Absyn.ELEMENT(true,NONE(),Absyn.NOT_INNER_OUTER(),getElementSpec($2),yyinfo,NONE())); } - | FINAL innerouter elementspec - { $$ = ELEMENT(Absyn.ELEMENT(true,NONE(),getInnerOuter($2),getElementSpec($3),yyinfo,NONE())); } - -componentitems : componentitem { $$ = COMPONENTITEMS(getComponentItem($1)::{}); } - | componentitem COMMA componentitems { $$ = COMPONENTITEMS(getComponentItem($1)::getComponentItems($3)); } - -componentitem : component comment { $$ = COMPONENTITEM(Absyn.COMPONENTITEM(getComponent($1),NONE(),SOME(getComment($2)))); } - | component componentcondition comment { $$ = COMPONENTITEM(Absyn.COMPONENTITEM(getComponent($1),SOME(getExp($2)),SOME(getComment($3)))); } - -componentcondition : IF exp { $$ = $2; } - -component : ident arraySubscripts modification { $$ = COMPONENT(Absyn.COMPONENT(getString($1),getArrayDim($2),SOME(getModification($3)))); } - | ident arraySubscripts { $$ = COMPONENT(Absyn.COMPONENT(getString($1),getArrayDim($2),NONE())); } - -modification : EQUALS exp { $$ = MODIFICATION(Absyn.CLASSMOD({},Absyn.EQMOD(getExp($2),yyinfo))); } - | ASSIGN exp { $$ = MODIFICATION(Absyn.CLASSMOD({},Absyn.EQMOD(getExp($2),yyinfo))); } - | class_modification { $$ = $1; } - -class_modification : elementargs - { $$ = MODIFICATION(Absyn.CLASSMOD(getElementArgs($1),Absyn.NOMOD())); } - | elementargs EQUALS exp - { $$ = MODIFICATION(Absyn.CLASSMOD(getElementArgs($1),Absyn.EQMOD(getExp($3),yyinfo))); } - -annotation : T_ANNOTATION elementargs { $$ = ANNOTATION(Absyn.ANNOTATION(getElementArgs($2))); } - -elementargs : LPAR argumentlist RPAR { $$ = $2; } - -elementargs2 : LPAR argumentlist RPAR { $$ = $2; } - | /* empty */ { $$ = ELEMENTARGS({}); } - -argumentlist : elementarg { $$ = ELEMENTARGS({getElementArg($1)}); } - | elementarg COMMA argumentlist { $$ = ELEMENTARGS(getElementArg($1)::getElementArgs($3)); } - -elementarg : element_mod_rep { $$ = $1; } - | element_redec { $$ = $1; } - -element_mod_rep : element_mod { $$ = $1; } - | element_rep { $$ = $1; } - -element_mod : eachprefix final path - { $$ = ELEMENTARG(Absyn.MODIFICATION(getBoolean($2),getEach($1),getPath($3),NONE(),NONE(),yyinfo)); } - | eachprefix final path modification - { $$ = ELEMENTARG(Absyn.MODIFICATION(getBoolean($2),getEach($1),getPath($3),SOME(getModification($4)),NONE(),yyinfo)); } - | eachprefix final path string - { $$ = ELEMENTARG(Absyn.MODIFICATION(getBoolean($2),getEach($1),getPath($3),NONE(),SOME(getString($4)),yyinfo)); } - | eachprefix final path modification string - { $$ = ELEMENTARG(Absyn.MODIFICATION(getBoolean($2),getEach($1),getPath($3),SOME(getModification($4)),SOME(getString($5)),yyinfo)); } - - -element_rep : REPLACEABLE eachprefix final classelementspec - { $$ = ELEMENTARG(Absyn.REDECLARATION(getBoolean($3),Absyn.REPLACEABLE(),getEach($2),getElementSpec($4),NONE(),yyinfo)); } - | REPLACEABLE eachprefix final elementspec2 - { $$ = ELEMENTARG(Absyn.REDECLARATION(getBoolean($3),Absyn.REPLACEABLE(),getEach($2),getElementSpec($4),NONE(),yyinfo)); } - | REPLACEABLE eachprefix final classelementspec constraining_clause - { $$ = ELEMENTARG(Absyn.REDECLARATION(getBoolean($3),Absyn.REDECLARE(),getEach($2),getElementSpec($4),SOME(getConstrainClass($5)),yyinfo)); } - | REDECLARE REPLACEABLE eachprefix final classelementspec constraining_clause - { $$ = ELEMENTARG(Absyn.REDECLARATION(getBoolean($4),Absyn.REDECLARE_REPLACEABLE(),getEach($3),getElementSpec($5),SOME(getConstrainClass($6)),yyinfo)); } - | REDECLARE REPLACEABLE eachprefix final classelementspec - { $$ = ELEMENTARG(Absyn.REDECLARATION(getBoolean($4),Absyn.REDECLARE_REPLACEABLE(),getEach($3),getElementSpec($5),NONE(),yyinfo)); } - | REPLACEABLE eachprefix final elementspec2 constraining_clause - { $$ = ELEMENTARG(Absyn.REDECLARATION(getBoolean($3),Absyn.REDECLARE(),getEach($2),getElementSpec($4),SOME(getConstrainClass($5)),yyinfo)); } - - -element_redec : REDECLARE eachprefix final classelementspec - { $$ = ELEMENTARG(Absyn.REDECLARATION(getBoolean($3),Absyn.REDECLARE(),getEach($2),getElementSpec($4),NONE(),yyinfo)); } - | REDECLARE eachprefix final elementspec2 - { $$ = ELEMENTARG(Absyn.REDECLARATION(getBoolean($3),Absyn.REDECLARE(),getEach($2),getElementSpec($4),NONE(),yyinfo)); } - - -elementspec2 : elementAttr typespec componentitems2 // arraydim from typespec should be in elementAttr arraydim - { $$ = fixArray($1,$2,$3); } - | typespec componentitems2 // arraydim from typespec should be in elementAttr arraydim - { $$ = fixArray(ELEMENTATTRIBUTES(Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(), Absyn.BIDIR(),{})),$1,$2); } - -componentitems2 : component comment { $$ = COMPONENTITEMS({Absyn.COMPONENTITEM(getComponent($1),NONE(),SOME(getComment($2)))}); } - -eachprefix : EACH { $$ = EACH(Absyn.EACH()); } - | /* empty */ { $$ = EACH(Absyn.NON_EACH()); } - -redeclarekeywords : REDECLARE { $$ = REDECLAREKEYWORDS(Absyn.REDECLARE()); } - | REPLACEABLE { $$ = REDECLAREKEYWORDS(Absyn.REPLACEABLE()); } - | REDECLARE REPLACEABLE { $$ = REDECLAREKEYWORDS(Absyn.REDECLARE_REPLACEABLE()); } - -innerouter : INNER { $$ = INNEROUTER(Absyn.INNER()); } - | T_OUTER { $$ = INNEROUTER(Absyn.OUTER()); } - | INNER T_OUTER { $$ = INNEROUTER(Absyn.INNER_OUTER()); } - //| /* empty */ { $$[InnerOuter] = Absyn.NOT_INNER_OUTER(); } - - -importelementspec : import comment { $$ = ELEMENTSPEC(Absyn.IMPORT(getImport($1),SOME(getComment($2)),yyinfo)); } - -classelementspec : class { $$ = ELEMENTSPEC(Absyn.CLASSDEF(false,getClass($1))); } - | REPLACEABLE class { $$ = ELEMENTSPEC(Absyn.CLASSDEF(true,getClass($2))); } - -import : IMPORT path { $$ = IMPORT(Absyn.QUAL_IMPORT(getPath($2))); } - | IMPORT path STAR_EW { $$ = IMPORT(Absyn.UNQUAL_IMPORT(getPath($2))); } - | IMPORT ident EQUALS path { $$ = IMPORT(Absyn.NAMED_IMPORT(getString($2),getPath($4))); } - -extends : EXTENDS path elementargs2 - { $$ = ELEMENTSPEC(Absyn.EXTENDS(getPath($2),getElementArgs($3),NONE())); } - | EXTENDS path elementargs2 annotation - { $$ = ELEMENTSPEC(Absyn.EXTENDS(getPath($2),getElementArgs($3),SOME(getAnnotation($4)))); } - -constraining_clause : extends { $$ = CONSTRAINCLASS(Absyn.CONSTRAINCLASS(getElementSpec($1),NONE())); } - | CONSTRAINEDBY path elementargs2 { $$ = CONSTRAINCLASS(Absyn.CONSTRAINCLASS(Absyn.EXTENDS(getPath($2),getElementArgs($3),NONE()),NONE())); } - | CONSTRAINEDBY path elementargs2 comment - { $$ = CONSTRAINCLASS(Absyn.CONSTRAINCLASS(Absyn.EXTENDS(getPath($2),getElementArgs($3),NONE()),SOME(getComment($4)))); } - -elementspec : elementAttr typespec componentitems // arraydim from typespec should be in elementAttr arraydim - { $$ = fixArray($1,$2,$3); } - | typespec componentitems // arraydim from typespec should be in elementAttr arraydim - { $$ = fixArray(ELEMENTATTRIBUTES(Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(), Absyn.BIDIR(),{})),$1,$2); } - -elementAttr : parallelism direction - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(false,false,getParallelism($1),Absyn.VAR(),getDirection($2),{})); } - - |parallelism - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(false,false,getParallelism($1),Absyn.VAR(),Absyn.BIDIR(),{})); } - - |direction - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(), getDirection($1),{})); } - |variability - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),getVariability($1), Absyn.BIDIR(),{})); } - - | variability direction - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),getVariability($1), getDirection($2),{})); } - - | STREAM variability direction - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(false,true,Absyn.NON_PARALLEL(),getVariability($2), getDirection($3),{})); } - | FLOW variability direction - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(true,false,Absyn.NON_PARALLEL(),getVariability($2), getDirection($3),{})); } - | FLOW direction - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(true,false,Absyn.NON_PARALLEL(),Absyn.VAR(), getDirection($2),{})); } - | FLOW - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(true,false,Absyn.NON_PARALLEL(),Absyn.VAR(),Absyn.BIDIR(),{})); } - | STREAM - { $$ = ELEMENTATTRIBUTES(Absyn.ATTR(false,true,Absyn.NON_PARALLEL(),Absyn.VAR(),Absyn.BIDIR(),{})); } - -parallelism : T_PARGLOBAL { $$ = PARALLELISM(Absyn.PARGLOBAL()); } - |T_PARLOCAL { $$ = PARALLELISM(Absyn.PARLOCAL()); } - // | /* empty */ { $$[Parallelism] = Absyn.NON_PARALLEL(); } - - -variability : PARAMETER { $$ = VARIABILITY(Absyn.PARAM()); } - | CONSTANT { $$ = VARIABILITY(Absyn.CONST()); } - | DISCRETE { $$ = VARIABILITY(Absyn.DISCRETE()); } - // | /* empty */ { $$[Variability] = Absyn.VAR(); } - -direction : T_INPUT { $$ = DIRECTION(Absyn.INPUT()); } - | T_OUTPUT { $$ = DIRECTION(Absyn.OUTPUT()); } - // | /* empty */ { $$[Direction] = Absyn.BIDIR(); } - - -/* Type specification */ - -typespec : path arraySubscripts { $$ = TYPESPEC(Absyn.TPATH(getPath($1),SOME(getArrayDim($2)))); } - | path arrayComplex { $$ = TYPESPEC(Absyn.TCOMPLEX(getPath($1),getTypeSpecs($2),NONE())); } - -arrayComplex : LESS typespecs GREATER { $$ = $1; } - -typespecs : typespec { $$ = TYPESPECS({getTypeSpec($1)}); } - | typespec COMMA typespecs { $$ = TYPESPECS(getTypeSpec($1)::getTypeSpecs($2)); } - -arraySubscripts : LBRACK arrayDim RBRACK { $$ = $2; } - | /* empty */ { $$ = ARRAYDIM({}); } - -arrayDim : subscript { $$ = ARRAYDIM({getSubscript($1)}); } - | subscript COMMA arrayDim { $$ = ARRAYDIM(getSubscript($1)::getArrayDim($3)); } - -subscript : exp { $$ = SUBSCRIPT(Absyn.SUBSCRIPT(getExp($1))); } - | COLON { $$ = SUBSCRIPT(Absyn.NOSUB()); } - -/* function calls */ - -functioncall : LPAR functionargs RPAR { $$ = $2; } - -functionargs : namedargs - { $$ = FUNCTIONARGS(Absyn.FUNCTIONARGS({},getNamedArgs($1))); } - | functionargs2 { $$ = $1; } - | functionargs3 { $$ = $1; } - - - -functionargs2 : explist2 - { $$ = FUNCTIONARGS(Absyn.FUNCTIONARGS(getExps($1),{})); } - | explist2 COMMA namedargs - { $$ = FUNCTIONARGS(Absyn.FUNCTIONARGS(getExps($1),getNamedArgs($3))); } - - - -functionargs3 : exp FOR foriterators - { $$ = FUNCTIONARGS(Absyn.FOR_ITER_FARG(getExp($1),getForIterators($3))); } - - -namedargs : namedarg { $$ = NAMEDARGS({getNamedArg($1)}); } - | namedarg COMMA namedargs { $$ = NAMEDARGS(getNamedArg($1)::getNamedArgs($3)); } - - -namedarg : ident EQUALS exp { $$ = NAMEDARG(Absyn.NAMEDARG(getString($1),getExp($3))); } - -/* expressions */ - -exp : simpleExp { $$ = $1; } - | if_exp { $$ = $1; } - | matchcont { $$ = $1; } - -matchcont : MATCH exp cases ENDMATCH { $$ = EXP(Absyn.MATCHEXP(Absyn.MATCH(),getExp($2),{},getCases($3),NONE())); } - | MATCH exp matchlocal cases ENDMATCH { $$ = EXP(Absyn.MATCHEXP(Absyn.MATCH(),getExp($2),getElementItems($3),getCases($4),NONE())); } - | MATCHCONTINUE exp cases ENDMATCHCONTINUE { $$ = EXP(Absyn.MATCHEXP(Absyn.MATCHCONTINUE(),getExp($2),{},getCases($3),NONE())); } - | MATCHCONTINUE exp matchlocal cases ENDMATCHCONTINUE { $$ = EXP(Absyn.MATCHEXP(Absyn.MATCHCONTINUE(),getExp($2),getElementItems($3),getCases($4),NONE())); } - - -if_exp : IF exp THEN exp ELSE exp { $$ = EXP(Absyn.IFEXP(getExp($2),getExp($4),getExp($6),{})); } - | IF exp THEN exp expelseifs ELSE exp { $$ = EXP(Absyn.IFEXP(getExp($2),getExp($4),getExp($7),getExpElseIfs($5))); } - -expelseifs : expelseif { $$ = EXPELSEIFS({getExpElseIf($1)}); } - | expelseif expelseifs { $$ = EXPELSEIFS(getExpElseIf($1)::getExpElseIfs($2)); } - -expelseif : ELSEIF exp THEN exp { $$ = EXPELSEIF((getExp($2),getExp($4))); } - - -matchlocal : LOCAL elementItems { $$ = $2; } - -cases : case { $$ = CASES({getCase($1)}); } - | case cases { $$ = CASES(getCase($1)::getCases($2)); } - -case : CASE casearg THEN exp SEMICOLON - { $$ = CASE(Absyn.CASE(getExp($2),NONE(),yyinfo,{},{},getExp($4),yyinfo,NONE(),yyinfo)); } - | CASE casearg EQUATION THEN exp SEMICOLON - { $$ = CASE(Absyn.CASE(getExp($2),NONE(),yyinfo,{},{},getExp($4),yyinfo,NONE(),yyinfo)); } - | CASE casearg EQUATION equationsection THEN exp SEMICOLON - { $$ = CASE(Absyn.CASE(getExp($2),NONE(),yyinfo,{},getEquationItems($4),getExp($6),yyinfo,NONE(),yyinfo)); } - | ELSE THEN exp SEMICOLON - { $$ = CASE(Absyn.ELSE({},{},getExp($3),yyinfo,NONE(),yyinfo)); } - | ELSE EQUATION equationsection THEN exp SEMICOLON - { $$ = CASE(Absyn.ELSE({},getEquationItems($3),getExp($5),yyinfo,NONE(),yyinfo)); } - -casearg : exp { $$ = $1; } - - -simpleExp : logicexp { $$ = $1; } - | rangeExp { $$ = $1; } - | headtail { $$ = $1; } - | ident AS simpleExp { $$ = EXP(Absyn.AS(getString($1),getExp($3))); } - -headtail : logicexp COLONCOLON logicexp { $$ = EXP(Absyn.CONS(getExp($1),getExp($3))); } - | logicexp COLONCOLON headtail { $$ = EXP(Absyn.CONS(getExp($1),getExp($3))); } - -rangeExp : logicexp COLON logicexp { $$ = EXP(Absyn.RANGE(getExp($1),NONE(),getExp($3))); } - | logicexp COLON logicexp COLON logicexp { $$ = EXP(Absyn.RANGE(getExp($1),SOME(getExp($3)),getExp($5))); } - -logicexp : logicterm { $$ = $1; } - | logicexp T_OR logicterm { $$ = EXP(Absyn.LBINARY(getExp($1),Absyn.OR(),getExp($3))); } - -logicterm : logfactor { $$ = $1; } - | logicterm T_AND logfactor { $$ = EXP(Absyn.LBINARY(getExp($1),Absyn.AND(),getExp($3))); } - -logfactor : relterm { $$ = $1; } - | T_NOT relterm { $$ = EXP(Absyn.LUNARY(Absyn.NOT(),getExp($2))); } - -relterm : addterm { $$ = $1; } - | addterm relOperator addterm { $$ = EXP(Absyn.RELATION(getExp($1),getOperator($2),getExp($3))); } - -addterm : term { $$ = $1; } - | unoperator term { $$ = EXP(Absyn.UNARY(getOperator($1),getExp($2))); } - | addterm woperator term { $$ = EXP(Absyn.BINARY(getExp($1),getOperator($2),getExp($3))); } - -term : factor { $$ = EXP(getExp($1)); } - | term soperator factor { $$ = EXP(Absyn.BINARY(getExp($1),getOperator($2),getExp($3))); } - -factor : expElement { $$ = EXP(getExp($1)); } - | expElement power factor { $$ = EXP(Absyn.BINARY(getExp($1),getOperator($2),getExp($3))); } - -expElement : number { $$ = $1; } - | cref { $$ = EXP(Absyn.CREF(getCref($1))); } - | T_FALSE { $$ = EXP(Absyn.BOOL(false)); } - | T_TRUE { $$ = EXP(Absyn.BOOL(true)); } - | string { $$ = EXP(Absyn.STRING(getString($1))); } - | tuple { $$ = $1; } - | LBRACE explist2 RBRACE { $$ = EXP(Absyn.ARRAY(getExps($2))); } - | LBRACE functionargs RBRACE { $$ = EXP(Absyn.CALL(Absyn.CREF_IDENT("array",{}),getFunctionArgs($2))); } - | LBRACK matrix RBRACK { $$ = EXP(Absyn.MATRIX(getMatrix($2))); } - | cref functioncall { $$ = EXP(Absyn.CALL(getCref($1),getFunctionArgs($2))); } - | FUNCTION cref functioncall { $$ = EXP(Absyn.PARTEVALFUNCTION(getCref($2),getFunctionArgs($3))); } - | DER functioncall { $$ = EXP(Absyn.CALL(Absyn.CREF_IDENT("der",{}),getFunctionArgs($2))); } - | T_INITIAL functioncall { $$ = EXP(Absyn.CALL(Absyn.CREF_IDENT("initial",{}),getFunctionArgs($2))); } - | LPAR exp RPAR { $$ = $2; } - | T_END { $$ = EXP(Absyn.END()); } - -number : UNSIGNED_INTEGER { $$ = EXP(Absyn.INTEGER(stringInt(getString($1)))); } - | UNSIGNED_REAL { $$ = EXP(Absyn.REAL(getString($1))); } - -matrix : explist2 { $$ = MATRIX({getExps($1)}); } - | explist2 SEMICOLON matrix { $$ = MATRIX(getExps($1)::getMatrix($3)); } - -tuple : LPAR explist RPAR { $$ = EXP(Absyn.TUPLE(getExps($2))); } - -explist : exp COMMA exp { $$ = EXPS({getExp($1),getExp($3)}); } - | exp COMMA explist { $$ = EXPS(getExp($1)::getExps($3)); } - | /* empty */ { $$ = EXPS({}); } - -explist2 : exp { $$ = EXPS({getExp($1)}); } - | explist2 COMMA exp { $$ = EXPS(listReverse(getExp($3)::listReverse(getExps($1)))); } - | /* empty */ { $$ = EXPS({}); } - -cref : ident arraySubscripts { $$ = CREF(Absyn.CREF_IDENT(getString($1),getArrayDim($2))); } - | ident arraySubscripts DOT cref { $$ = CREF(Absyn.CREF_QUAL(getString($1),getArrayDim($2),getCref($4))); } - | DOT cref { $$ = CREF(Absyn.CREF_FULLYQUALIFIED(getCref($2))); } - | WILD { $$ = CREF(Absyn.WILD()); } - | ALLWILD { $$ = CREF(Absyn.ALLWILD()); } - -unoperator : PLUS { $$ = OPERATOR(Absyn.UPLUS()); } - | MINUS { $$ = OPERATOR(Absyn.UMINUS()); } - | PLUS_EW { $$ = OPERATOR(Absyn.UPLUS_EW()); } - | MINUS_EW { $$ = OPERATOR(Absyn.UMINUS_EW()); } - - -woperator : PLUS { $$ = OPERATOR(Absyn.ADD()); } - | MINUS { $$ = OPERATOR(Absyn.SUB()); } - | PLUS_EW { $$ = OPERATOR(Absyn.ADD_EW()); } - | MINUS_EW { $$ = OPERATOR(Absyn.SUB_EW()); } - - -soperator : STAR { $$ = OPERATOR(Absyn.MUL()); } - | SLASH { $$ = OPERATOR(Absyn.DIV()); } - | STAR_EW { $$ = OPERATOR(Absyn.MUL_EW()); } - | SLASH_EW { $$ = OPERATOR(Absyn.DIV_EW()); } - -power : POWER { $$ = OPERATOR(Absyn.POW()); } - | POWER_EW { $$ = OPERATOR(Absyn.POW_EW()); } - -relOperator : LESS { $$ = OPERATOR(Absyn.LESS()); } - | LESSEQ { $$ = OPERATOR(Absyn.LESSEQ()); } - | GREATER { $$ = OPERATOR(Absyn.GREATER()); } - | GREATEREQ { $$ = OPERATOR(Absyn.GREATEREQ()); } - | EQEQ { $$ = OPERATOR(Absyn.EQUAL()); } - | LESSGT { $$ = OPERATOR(Absyn.NEQUAL()); } - -path : ident { $$ = PATH(Absyn.IDENT(getString($1))); } - | ident DOT path { $$ = PATH(Absyn.QUALIFIED(getString($1),getPath($3))); } - | DOT path { $$ = PATH(Absyn.FULLYQUALIFIED(getPath($2))); } - -ident : IDENT { $$ = $1; } - -string : STRING { $$ = STRING(trimquotes(getString($1))); } // trim the quote of the string - -comment : string { $$ = COMMENT(Absyn.COMMENT(NONE(),SOME(getString($1)))); } - | string annotation { $$ = COMMENT(Absyn.COMMENT(SOME(getAnnotation($2)),SOME(getString($1)))); } - | annotation { $$ = COMMENT(Absyn.COMMENT(SOME(getAnnotation($1)),NONE())); } - | /* empty */ { $$ = COMMENT(Absyn.COMMENT(NONE(),NONE())); } - - -%% - -public function trimquotes -"removes chars in charsToRemove from inString" - input String inString; - output String outString; - algorithm - if (stringLength(inString)>2) then - outString := System.substring(inString,2,stringLength(inString)-1); - else - outString := ""; - end if; -end trimquotes; - -/* A little more special access functions */ - -function fixArray - input AstItem elementAttributes; - input AstItem typeSpec; - input AstItem items; - output AstItem spec; -protected - Absyn.ElementAttributes v1ElementAttributes2; - Absyn.TypeSpec v2TypeSpec2; - Boolean flowPrefix,b1,b2 "flow" ; - Boolean streamPrefix "stream" ; - Absyn.Variability variability,v1 "variability ; parameter, constant etc." ; - Absyn.Direction direction,d1 "direction" ; - Absyn.Parallelism parallelism, prl; - Absyn.ArrayDim arrayDim,a1 "arrayDim" ; - Absyn.Path path,p1; - Option oa1; -algorithm - ELEMENTATTRIBUTES(Absyn.ATTR(flowPrefix=b1,streamPrefix=b2,parallelism=prl,variability=v1,direction=d1,arrayDim=a1)) := elementAttributes; - TYPESPEC(Absyn.TPATH(path=p1,arrayDim=oa1)) :=typeSpec; - a1 := match oa1 - local Absyn.ArrayDim l1; - case SOME(l1) then (l1); - case NONE() then ({}); - end match; - - v1ElementAttributes2 := Absyn.ATTR(b1,b2,prl,v1,d1,a1); - v2TypeSpec2 := Absyn.TPATH(p1,NONE()); - spec := ELEMENTSPEC(Absyn.COMPONENTS(v1ElementAttributes2,v2TypeSpec2,getComponentItems(items))); -end fixArray; - -function getString - input AstItem item; - output String out; -algorithm - out := match item - local - OMCCTypes.Token tok; - case STRING(string=out) then out; - case TOKEN(tok=tok) then OMCCTypes.getStringValue(tok); - else equation print("getString() failed\n"); then fail(); - end match; -end getString; - -function getClassPrefixPartial - input AstItem item; - output Boolean out; -algorithm - CLASSPREFIX(part=out) := item; -end getClassPrefixPartial; - -function getClassPrefixEncapsulated - input AstItem item; - output Boolean out; -algorithm - CLASSPREFIX(encap=out) := item; -end getClassPrefixEncapsulated; - -/* Type Declarations */ -function getProgram - input AstItem item; - output Absyn.Program out; -algorithm - PROGRAM(program=out) := item; -end getProgram; - -function getToken - input AstItem item; - output OMCCTypes.Token out; -algorithm - OMCCTypes.TOKEN(tok=out) := item; -end getToken; - -function getWithin - input AstItem item; - output Absyn.Within out; -algorithm - WITHIN(_within=out) := item; -end getWithin; - -function getClasses - input AstItem item; - output list out; -algorithm - CLASSES(classes=out) := item; -end getClasses; - -function getClass - input AstItem item; - output Absyn.Class out; -algorithm - CLASS(_class=out) := item; -end getClass; - -function getPath - input AstItem item; - output Absyn.Path out; -algorithm - PATH(path=out) := item; -end getPath; - -function getClassDef - input AstItem item; - output Absyn.ClassDef out; -algorithm - CLASSDEF(classdef=out) := item; -end getClassDef; - -function getClassPart - input AstItem item; - output Absyn.ClassPart out; -algorithm - CLASSPART(part=out) := item; -end getClassPart; - -function getClassParts - input AstItem item; - output list out; -algorithm - CLASSPARTS(parts=out) := item; -end getClassParts; - -function getImport - input AstItem item; - output Absyn.Import out; -algorithm - IMPORT(_import=out) := item; -end getImport; - -function getElementItem - input AstItem item; - output Absyn.ElementItem out; -algorithm - ELEMENTITEM(item=out) := item; - /* _ := match out - case (_) equation print("Error: AnnotationItem only allowed at the end of the class\n"); then fail(); - else (); - end match; */ -end getElementItem; - -function getElementItemAllowAnnotation - input AstItem item; - output Absyn.ElementItem out; -algorithm - ELEMENTITEM(item=out) := item; -end getElementItemAllowAnnotation; - -function getElementItems - input AstItem item; - output list out; -algorithm - ELEMENTITEMS(items=out) := item; -end getElementItems; - -function getElementArg - input AstItem item; - output Absyn.ElementArg out; -algorithm - ELEMENTARG(arg=out) := item; -end getElementArg; - -function getElementArgs - input AstItem item; - output list out; -algorithm - ELEMENTARGS(args=out) := item; -end getElementArgs; - -function getElementAttributes - input AstItem item; - output Absyn.ElementAttributes out; -algorithm - ELEMENTATTRIBUTES(attrs=out) := item; -end getElementAttributes; - -function getElement - input AstItem item; - output Absyn.Element out; -algorithm - ELEMENT(element=out) := item; -end getElement; - -function getElementSpec - input AstItem item; - output Absyn.ElementSpec out; -algorithm - ELEMENTSPEC(spec=out) := item; -end getElementSpec; - -function getRestriction - input AstItem item; - output Absyn.Restriction out; -algorithm - RESTRICTION(restriction=out) := item; -end getRestriction; - -function getFunctionArgs - input AstItem item; - output Absyn.FunctionArgs out; -algorithm - FUNCTIONARGS(args=out) := item; -end getFunctionArgs; - -function getNamedArg - input AstItem item; - output Absyn.NamedArg out; -algorithm - NAMEDARG(arg=out) := item; -end getNamedArg; - -function getNamedArgs - input AstItem item; - output list out; -algorithm - NAMEDARGS(arg=out) := item; -end getNamedArgs; - -function getBoolean - input AstItem item; - output Boolean out; -algorithm - BOOLEAN(bool=out) := item; -end getBoolean; - -function getEnumDef - input AstItem item; - output Absyn.EnumDef out; -algorithm - ENUMDEF(def=out) := item; -end getEnumDef; - -function getEnumLiteral - input AstItem item; - output Absyn.EnumLiteral out; -algorithm - ENUMLITERAL(literal=out) := item; -end getEnumLiteral; - -function getEnumLiterals - input AstItem item; - output list out; -algorithm - ENUMLITERALS(literals=out) := item; -end getEnumLiterals; - -function getComment - input AstItem item; - output Absyn.Comment out; -algorithm - COMMENT(comment=out) := item; -end getComment; - -function getEquation - input AstItem item; - output Absyn.Equation out; -algorithm - EQUATION(eq=out) := item; -end getEquation; - -function getEquationItem - input AstItem item; - output Absyn.EquationItem out; -algorithm - EQUATIONITEM(item=out) := item; -end getEquationItem; - -function getEquationItems - input AstItem item; - output list out; -algorithm - EQUATIONITEMS(items=out) := item; -end getEquationItems; - -function getAlgorithm - input AstItem item; - output Absyn.Algorithm out; -algorithm - ALGORITHM(alg=out) := item; -end getAlgorithm; - -function getAlgorithmItem - input AstItem item; - output Absyn.AlgorithmItem out; -algorithm - ALGORITHMITEM(item=out) := item; -end getAlgorithmItem; - -function getAlgorithmItems - input AstItem item; - output list out; -algorithm - ALGORITHMITEMS(items=out) := item; -end getAlgorithmItems; - -function getExternalDecl - input AstItem item; - output Absyn.ExternalDecl out; -algorithm - EXTERNALDECL(decl=out) := item; -end getExternalDecl; - -function getAnnotation - input AstItem item; - output Absyn.Annotation out; -algorithm - ANNOTATION(ann=out) := item; -end getAnnotation; - -function getCref - input AstItem item; - output Absyn.ComponentRef out; -algorithm - CREF(cref=out) := item; -end getCref; - -function getExp - input AstItem item; - output Absyn.Exp out; -algorithm - EXP(exp=out) := item; -end getExp; - -function getExps - input AstItem item; - output list out; -algorithm - EXPS(exps=out) := item; -end getExps; - -function getForIterator - input AstItem item; - output Absyn.ForIterator out; -algorithm - FORITERATOR(iterator=out) := item; -end getForIterator; - -function getForIterators - input AstItem item; - output list out; -algorithm - FORITERATORS(iterators=out) := item; -end getForIterators; - -function getAlgElseIf - input AstItem item; - output tuple> out; -algorithm - ALGELSEIF(elseIf=out) := item; -end getAlgElseIf; - -function getAlgElseIfs - input AstItem item; - output list>> out; -algorithm - ALGELSEIFS(elseIfs=out) := item; -end getAlgElseIfs; - -function getAlgElseWhen - input AstItem item; - output tuple> out; -algorithm - ALGELSEWHEN(elseWhen=out) := item; -end getAlgElseWhen; - -function getAlgElseWhens - input AstItem item; - output list>> out; -algorithm - ALGELSEWHENS(elseWhens=out) := item; -end getAlgElseWhens; - -function getElseWhen - input AstItem item; - output tuple> out; -algorithm - ELSEWHEN(elseWhen=out) := item; -end getElseWhen; - -function getElseWhens - input AstItem item; - output list>> out; -algorithm - ELSEWHENS(elseWhens=out) := item; -end getElseWhens; - -function getElseIf - input AstItem item; - output tuple> out; -algorithm - ELSEIF(elseIf=out) := item; -end getElseIf; - -function getElseIfs - input AstItem item; - output list>> out; -algorithm - ELSEIFS(elseIfs=out) := item; -end getElseIfs; - -function getInnerOuter - input AstItem item; - output Absyn.InnerOuter out; -algorithm - INNEROUTER(innerOuter=out) := item; -end getInnerOuter; - -function getRedeclareKeywords - input AstItem item; - output Absyn.RedeclareKeywords out; -algorithm - REDECLAREKEYWORDS(redeclareKeywords=out) := item; -end getRedeclareKeywords; - -function getConstrainClass - input AstItem item; - output Absyn.ConstrainClass out; -algorithm - CONSTRAINCLASS(cc=out) := item; -end getConstrainClass; - -function getComponent - input AstItem item; - output Absyn.Component out; -algorithm - COMPONENT(component=out) := item; -end getComponent; - -function getComponentItem - input AstItem item; - output Absyn.ComponentItem out; -algorithm - COMPONENTITEM(item=out) := item; -end getComponentItem; - -function getComponentItems - input AstItem item; - output list out; -algorithm - COMPONENTITEMS(items=out) := item; -end getComponentItems; - -function getArrayDim - input AstItem item; - output Absyn.ArrayDim out; -algorithm - ARRAYDIM(dim=out) := item; -end getArrayDim; - -function getModification - input AstItem item; - output Absyn.Modification out; -algorithm - MODIFICATION(mod=out) := item; -end getModification; - -function getEach - input AstItem item; - output Absyn.Each out; -algorithm - EACH(_each=out) := item; -end getEach; - -function getParallelism - input AstItem item; - output Absyn.Parallelism out; -algorithm - PARALLELISM(parallelism=out) := item; -end getParallelism; - -function getDirection - input AstItem item; - output Absyn.Direction out; -algorithm - DIRECTION(direction=out) := item; -end getDirection; - -function getVariability - input AstItem item; - output Absyn.Variability out; -algorithm - VARIABILITY(variability=out) := item; -end getVariability; - -function getTypeSpec - input AstItem item; - output Absyn.TypeSpec out; -algorithm - TYPESPEC(spec=out) := item; -end getTypeSpec; - -function getTypeSpecs - input AstItem item; - output list out; -algorithm - TYPESPECS(specs=out) := item; -end getTypeSpecs; - -function getSubscript - input AstItem item; - output Absyn.Subscript out; -algorithm - SUBSCRIPT(subscript=out) := item; -end getSubscript; - -function getCase - input AstItem item; - output Absyn.Case out; -algorithm - CASE(_case=out) := item; -end getCase; - -function getCases - input AstItem item; - output list out; -algorithm - CASES(cases=out) := item; -end getCases; - -function getExpElseIf - input AstItem item; - output tuple out; -algorithm - EXPELSEIF(elseIf=out) := item; -end getExpElseIf; - -function getExpElseIfs - input AstItem item; - output list> out; -algorithm - EXPELSEIFS(elseIfs=out) := item; -end getExpElseIfs; - -function getOperator - input AstItem item; - output Absyn.Operator out; -algorithm - OPERATOR(op=out) := item; -end getOperator; - -function getMatrix - input AstItem item; - output list> out; -algorithm - MATRIX(matrix=out) := item; -end getMatrix; - -function itemStr - input AstItem item; - output String str; -algorithm - str := match item - local - OMCCTypes.Token tok; - case TOKEN(tok=tok) then OMCCTypes.printToken(tok); - else anyString(item); - end match; -end itemStr;