From f7028d4ee60eef064f0b8b088d8d742bbc2f20e9 Mon Sep 17 00:00:00 2001 From: John Date: Mon, 3 Jun 2019 06:46:58 +0200 Subject: [PATCH] Readded the missing files (#1) Added the missing Julia files --- OMCompiler/Compiler/Script/MMToJuliaUtil.mo | 54 + OMCompiler/Compiler/Template/MMToJulia.tpl | 1157 ++++++++++++++ OMCompiler/Compiler/Template/MMToJuliaTV.mo | 1558 +++++++++++++++++++ OMCompiler/toJulia/Clean.jl | 9 + OMCompiler/toJulia/Graphviz.mos | 5 + OMCompiler/toJulia/lex.jl | 67 + OMCompiler/toJulia/lexer.jl | 94 ++ OMCompiler/toJulia/toJulia.jl | 45 + OMCompiler/toJulia/tokens.jl | 92 ++ 9 files changed, 3081 insertions(+) create mode 100644 OMCompiler/Compiler/Script/MMToJuliaUtil.mo create mode 100644 OMCompiler/Compiler/Template/MMToJulia.tpl create mode 100644 OMCompiler/Compiler/Template/MMToJuliaTV.mo create mode 100644 OMCompiler/toJulia/Clean.jl create mode 100644 OMCompiler/toJulia/Graphviz.mos create mode 100644 OMCompiler/toJulia/lex.jl create mode 100644 OMCompiler/toJulia/lexer.jl create mode 100644 OMCompiler/toJulia/toJulia.jl create mode 100644 OMCompiler/toJulia/tokens.jl diff --git a/OMCompiler/Compiler/Script/MMToJuliaUtil.mo b/OMCompiler/Compiler/Script/MMToJuliaUtil.mo new file mode 100644 index 00000000000..23a846e35a9 --- /dev/null +++ b/OMCompiler/Compiler/Script/MMToJuliaUtil.mo @@ -0,0 +1,54 @@ +/* + * This file is part of OpenModelica. + * + * Copyright (c) 1998-2014, Open Source Modelica Consortium (OSMC), + * c/o Linköpings universitet, Department of Computer and Information Science, + * SE-58183 Linköping, Sweden. + * + * All rights reserved. + * + * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR + * THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. + * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES + * RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, + * ACCORDING TO RECIPIENTS CHOICE. + * + * The OpenModelica software and the Open Source Modelica + * Consortium (OSMC) Public License (OSMC-PL) are obtained + * from OSMC, either from the above address, + * from the URLs: http://www.ida.liu.se/projects/OpenModelica or + * http://www.openmodelica.org, and in the OpenModelica distribution. + * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. + * + * This program is distributed WITHOUT ANY WARRANTY; without + * even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH + * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. + * + * See the full OSMC Public License conditions for more details. + * + */ + +encapsulated package MMToJuliaUtil + +uniontype Context + record FUNCTION + end FUNCTION; + record PACKAGE + end PACKAGE; + record UNIONTYPE + String name; + end UNIONTYPE; +end Context; +constant Context packageContext = PACKAGE(); +constant Context functionContext = FUNCTION(); + +function makeUniontypeContext + input String name; + output Context context; +algorithm + context := UNIONTYPE(name); +end makeUniontypeContext; + +annotation(__OpenModelica_Interface="backend"); +end MMToJuliaUtil; \ No newline at end of file diff --git a/OMCompiler/Compiler/Template/MMToJulia.tpl b/OMCompiler/Compiler/Template/MMToJulia.tpl new file mode 100644 index 00000000000..5adcea02cc4 --- /dev/null +++ b/OMCompiler/Compiler/Template/MMToJulia.tpl @@ -0,0 +1,1157 @@ +package MMToJulia + +import interface MMToJuliaTV; +import AbsynDumpTpl; +import SCodeDumpTpl; + +template dumpProgram(list program) +::= dumpElements(program, false, packageContext) +end dumpProgram; + +template dumpElements(list elements, Boolean indent, Context context) +::= dumpElements2(filterElements(elements, defaultOptions), indent, context) +end dumpElements; + +template dumpElements2(list elements, + Boolean indent, Context context) +::= + ( + elements |> el hasindex i1 fromindex 1 => + match el + case CLASS(restriction=R_UNIONTYPE(__)) then + 'abstract type <%name%> end<%\n%>' + ) + + + (elements |> el hasindex i1 fromindex 1 => + let el_str = dumpElement(el,'', context) + if indent then + << + <%el_str%><%\n%> + >> + else + << + <%el_str%><%\n%> + >>) +end dumpElements2; + +template dumpPreElementSpacing(String curSpacing, Boolean prevSpacing) +::= if not prevSpacing then curSpacing +end dumpPreElementSpacing; + +template dumpElementSpacing(SCode.Element element) +::= match element case CLASS(__) then dumpClassDefSpacing(classDef) +end dumpElementSpacing; + +template dumpClassDefSpacing(SCode.ClassDef classDef) +::= +match classDef + case CLASS_EXTENDS(__) then dumpClassDefSpacing(composition) + case PARTS(__) then '<%\n%>' +end dumpClassDefSpacing; + +template dumpElement(SCode.Element element, String each, Context context) +::= +match element + case IMPORT(__) then + dumpImport(element) + case EXTENDS(__) then dumpExtends(element) + case CLASS(__) then dumpClass(element, each) + case COMPONENT(__) then dumpComponent(element, each, context) + else error(sourceInfo(), "SCodeDump.dumpElement: Unknown element.") +end dumpElement; + +template dumpImport(SCode.Element import) +::= +match import +case IMPORT(__) then + match imp + case NAMED_IMPORT(__) then + 'import <%name%> = <%AbsynDumpTpl.dumpPath(path)%>' + case QUAL_IMPORT(__) then + 'import <%AbsynDumpTpl.dumpPath(path)%>' + case UNQUAL_IMPORT(__) then + 'import <%AbsynDumpTpl.dumpPath(path)%>.*' + else error(sourceInfo(), "SCodeDump.dumpImport: Unknown import.") +end dumpImport; + +template dumpExtends(SCode.Element extends) +::= +match extends + case EXTENDS(__) then + let bc_str = AbsynDumpTpl.dumpPath(baseClassPath) + let mod_str = dumpModifier(modifications) + let ann_str = dumpAnnotationOpt(ann) + 'extends <%bc_str%><%mod_str%><%ann_str%>' +end dumpExtends; + +template dumpClass(SCode.Element class, String each) +::= +match class + case CLASS(restriction=R_UNIONTYPE(__)) then + dumpClassDef(classDef, packageContext) + case CLASS(partialPrefix=PARTIAL(__), restriction=R_FUNCTION(__)) then + 'const <%name%> = Function' // Julia does not really support types of higher-order functions + case CLASS(classDef=p as PARTS(__), restriction=R_FUNCTION(__)) then + let cdef_str = dumpClassDef(classDef, functionContext) + let cmt_str = dumpClassComment(cmt) + let ann_str = dumpClassAnnotation(cmt) + let inputs = p.elementLst |> elt as COMPONENT(attributes=ATTR(direction=INPUT(__))) => + let type_str = dumpTypeSpec(elt.typeSpec) + let mod_str = dumpModifier(elt.modifications) + let cmt_str = dumpComment(elt.comment) + '<%elt.name%>::<%type_str%><%mod_str%><%cmt_str%>' + ; separator = "," + << + function <%name%>(<%inputs%>) + <%cmt_str%> + <%cdef_str%> + <%ann_str%> + end + >> + case CLASS(__) then + let prefix_str = dumpPrefixes(prefixes, each) + // let enc_str = dumpEncapsulated(encapsulatedPrefix) + let partial_str = dumpPartial(partialPrefix) + let res_str = dumpRestriction(restriction) + let prefixes_str = '<%prefix_str%><%partial_str%><%res_str%>' + let cdef_str1 = dumpClassDef(classDef, packageContext) + let cdef_str2 = match restriction + case R_PACKAGE(__) then + << + using MetaModelica + <%cdef_str1%> + >> + else cdef_str1 + let cdef_str = cdef_str2 + let cmt_str = dumpClassComment(cmt) + let ann_str = dumpClassAnnotation(cmt) + let header_str = dumpClassHeader(classDef, name, restriction, cmt_str) + let footer_str = dumpClassFooter(classDef, cdef_str, name, cmt_str, ann_str) + << + <%prefixes_str%> <%header_str%> <%footer_str%> + >> +end dumpClass; + +template dumpClassHeader(SCode.ClassDef classDef, String name, SCode.Restriction restr, String cmt) +::= +match classDef + case CLASS_EXTENDS(__) + then + let mod_str = dumpModifier(modifications) + 'extends <%name%><%mod_str%> <%cmt%>' + case PARTS(__) then '<%name%><%dumpRestrictionTypeVars(restr)%><%dumpRestrictionSuperType(restr)%> <%cmt%>' + else '<%name%>' +end dumpClassHeader; + +template dumpRestrictionSuperType(SCode.Restriction r) +::= +match r +case R_METARECORD(__) then '<: <%AbsynDumpTpl.dumpPath(name)%>' +end dumpRestrictionSuperType; + +template dumpClassDef(SCode.ClassDef classDef, Context context) +::= +match classDef + case p as PARTS(__) then + let el_str = dumpElements(elementLst, false, context) + let neq_str = dumpEquations(normalEquationLst) + let nal_str = dumpAlgorithmSections(p.normalAlgorithmLst) + let extdecl_str = dumpExternalDeclOpt(p.externalDecl) + let cdef_str = + << + <%el_str%> + <%neq_str%> + <%nal_str%> + <%extdecl_str%> + >> + cdef_str + case CLASS_EXTENDS(__) then + let mod_str = dumpModifier(modifications) + let cdef_str = dumpClassDef(composition, packageContext) + << + <%cdef_str%> + >> + case DERIVED(__) then + let type_str = dumpTypeSpec(typeSpec) + let mod_str = dumpModifier(modifications) + // let attr_str = dumpAttributes(attributes) + '= <%type_str%><%mod_str%>' + case ENUMERATION(__) then + let enum_str = if enumLst then + (enumLst |> enum => dumpEnumLiteral(enum) ;separator=", ") + else + ':' + '= enumeration(<%enum_str%>)' + case PDER(__) then + let func_str = AbsynDumpTpl.dumpPath(functionPath) + '= der(<%func_str%>, <%derivedVariables ;separator=", "%>)' + case OVERLOAD(__) then + '= overload(<%pathLst |> path => AbsynDumpTpl.dumpPath(path); separator=", "%>)' + else error(sourceInfo(), "SCodeDump.dumpClassDef: Unknown class definition.") +end dumpClassDef; + +template dumpTypeSpec(Absyn.TypeSpec typeSpec) +::= +match typeSpec + case TPATH(__) then + let path_str = AbsynDumpTpl.dumpPath(path) + let arraydim_str = AbsynDumpTpl.dumpArrayDimOpt(arrayDim) + '<%path_str%><%arraydim_str%>' + case TCOMPLEX(__) then + let path_str = (match path + case IDENT(name="list") then 'List' + else AbsynDumpTpl.dumpPath(path)) + let ty_str = (typeSpecs |> ty => dumpTypeSpec(ty) ;separator=", ") + let arraydim_str = AbsynDumpTpl.dumpArrayDimOpt(arrayDim) + '<%path_str%>{<%ty_str%>}<%arraydim_str%>' +end dumpTypeSpec; + +template dumpClassFooter(SCode.ClassDef classDef, String cdefStr, String name, String cmt, String ann) +::= +match classDef + case DERIVED(__) then '<%cdefStr%><%cmt%><%ann%>' + case ENUMERATION(__) then '<%cdefStr%><%cmt%><%ann%>' + case _ then + let annstr = if ann then '<%ann%> ' else '' + if cdefStr then + << + + <%cdefStr%> + <%if annstr then " "%><%annstr%> + end + >> + else + << + <%annstr%>end + >> +end dumpClassFooter; + +template dumpClassComment(SCode.Comment comment) +::= + match comment + case COMMENT(__) then dumpCommentStr(comment) +end dumpClassComment; + +template dumpClassAnnotation(SCode.Comment comment) +::= + match comment + case COMMENT(__) then dumpAnnotationOpt(annotation_) +end dumpClassAnnotation; + +template dumpComponent(SCode.Element component, String each, Context context) +::= +match component + case COMPONENT(attributes=ATTR(direction=INPUT(__))) then "" + case COMPONENT(__) then + let prefix_str = dumpPrefixes(prefixes, each) + let attr_pre_str = dumpAttributes(attributes, context) + let attr_dim_str = dumpAttributeDim(attributes) + let type_str = dumpTypeSpec(typeSpec) + let mod_str1 = dumpModifier(modifications) + let mod_str = // If stripOutputBindings is set, we need to look for the direction + mod_str1 + let cond_str = match condition case SOME(cond) then ' if <%AbsynDumpTpl.dumpExp(cond)%>' + let cmt_str = dumpComment(comment) + '<%prefix_str%><%attr_pre_str%><%attr_dim_str%> <%name%><%mod_str%>::<%type_str%><%cond_str%><%cmt_str%>' +end dumpComponent; + +template dumpEnumLiteral(SCode.Enum enum) +::= +match enum + case ENUM(__) then + let cmt_str = dumpComment(comment) + '<%literal%><%cmt_str%>' +end dumpEnumLiteral; + +template dumpEquations(list equations) +::= + equations |> eq => dumpEquation(eq) ;separator="\n" +end dumpEquations; + +template dumpEquation(SCode.Equation equation) +::= match equation case EQUATION(__) then dumpEEquation(eEquation) +end dumpEquation; + +template dumpEEquation(SCode.EEquation equation) +::= +match equation + case EQ_IF(__) then dumpIfEEquation(equation) + case EQ_EQUALS(__) then + let lhs_str = dumpLhsExp(expLeft) + let rhs_str = dumpExp(expRight) + let cmt_str = dumpComment(comment) + '<%lhs_str%> = <%rhs_str%><%cmt_str%>;' + case EQ_CONNECT(__) then + let lhs_str = dumpCref(crefLeft) + let rhs_str = dumpCref(crefRight) + let cmt_str = dumpComment(comment) + 'connect(<%lhs_str%>, <%rhs_str%>)<%cmt_str%>;' + case EQ_FOR(__) then dumpForEEquation(equation) + case EQ_WHEN(__) then dumpWhenEEquation(equation) + case EQ_ASSERT(__) then + let cond_str = dumpExp(condition) + let msg_str = dumpExp(message) + let lvl_str = dumpAssertionLevel(level) + let cmt_str = dumpComment(comment) + 'assert(<%cond_str%>, <%msg_str%><%lvl_str%>)<%cmt_str%>;' + case EQ_TERMINATE(__) then + let msg_str = dumpExp(message) + let cmt_str = dumpComment(comment) + 'terminate(<%msg_str%>)<%cmt_str%>;' + case EQ_REINIT(__) then + let cref_str = dumpExp(cref) + let exp_str = dumpExp(expReinit) + let cmt_str = dumpComment(comment) + 'reinit(<%cref_str%>, <%exp_str%>)<%cmt_str%>;' + case EQ_NORETCALL(__) then + let exp_str = dumpExp(exp) + let cmt_str = dumpComment(comment) + '<%exp_str%><%cmt_str%>;' + else error(sourceInfo(), "SCodeDump.dumpEEquation: Unknown EEquation.") +end dumpEEquation; + +template dumpIfEEquation(SCode.EEquation ifequation) +::= +match ifequation + case EQ_IF(condition = if_cond :: elseif_conds, + thenBranch = if_branch :: elseif_branches) then + let if_cond_str = dumpExp(if_cond) + let if_branch_str = (if_branch |> e => dumpEEquation(e) ;separator="\n") + let elseif_str = dumpElseIfEEquation(elseif_conds, elseif_branches) + let else_str = if elseBranch then + << + else + <%elseBranch |> e => dumpEEquation(e) ;separator="\n"%> + >> + << + if <%if_cond_str%> then + <%if_branch_str%> + <%elseif_str%> + <%else_str%> + end if; + >> +end dumpIfEEquation; + +template dumpElseIfEEquation(list condition, + list> branches) +::= +match condition + case cond :: rest_conds then + match branches + case branch :: rest_branches then + let cond_str = dumpExp(cond) + let branch_str = (branch |> e => dumpEEquation(e) ;separator="\n") + let rest_str = dumpElseIfEEquation(rest_conds, rest_branches) + << + elseif <%cond_str%> then + <%branch_str%> + <%rest_str%> + >> +end dumpElseIfEEquation; + +template dumpForEEquation(SCode.EEquation for_equation) +::= +match for_equation + case EQ_FOR(range=SOME(range)) then + let range_str = dumpExp(range) + let eq_str = (eEquationLst |> e => dumpEEquation(e) ;separator="\n") + let cmt_str = dumpComment(comment) + << + for <%index%> in <%range_str%> loop + <%eq_str%> + end for<%cmt_str%>; + >> + case EQ_FOR(__) then + let eq_str = (eEquationLst |> e => dumpEEquation(e) ;separator="\n") + let cmt_str = dumpComment(comment) + << + for <%index%> loop + <%eq_str%> + end for<%cmt_str%>; + >> +end dumpForEEquation; + +template dumpWhenEEquation(SCode.EEquation when_equation) +::= +match when_equation + case EQ_WHEN(__) then + let cond_str = dumpExp(condition) + let body_str = (eEquationLst |> e => dumpEEquation(e) ;separator="\n") + let else_str = (elseBranches |> (else_cond, else_body) => + let else_cond_str = dumpExp(else_cond) + let else_body_str = (else_body |> e => dumpEEquation(e) ;separator="\n") + << + elsewhen <%else_cond_str%> then + <%else_body_str%> + >> ;separator="\n") + let cmt_str = dumpComment(comment) + << + when <%cond_str%> then<%cmt_str%> + <%body_str%> + <%else_str%> + end when; + >> +end dumpWhenEEquation; + +template dumpAssertionLevel(Absyn.Exp exp) +::= match exp + case CREF(componentRef = CREF_FULLYQUALIFIED(componentRef = CREF_QUAL( + name = "AssertionLevel", componentRef = CREF_IDENT(name = "error")))) then "" + case CREF(componentRef = CREF_QUAL(name = "AssertionLevel", + componentRef = CREF_IDENT(name = "error"))) then "" + else ', <%dumpExp(exp)%>' +end dumpAssertionLevel; + +template dumpAlgorithmSections(list algorithms) +::= + algorithms |> al => dumpAlgorithmSection(al) ;separator="\n" +end dumpAlgorithmSections; + +template dumpAlgorithmSection(SCode.AlgorithmSection algorithm) +::= match algorithm case ALGORITHM(__) then dumpStatements(statements) +end dumpAlgorithmSection; + +template dumpStatements(list statements) +::= statements |> s => dumpStatement(s) ;separator="\n" +end dumpStatements; + +template dumpStatement(SCode.Statement statement) +::= +match statement + case ALG_ASSIGN(__) then + let lhs_str = dumpLhsExp(assignComponent) + let rhs_str = dumpExp(value) + let cmt_str = dumpComment(comment) + '<%lhs_str%> = <%rhs_str%><%cmt_str%>;' + case ALG_IF(__) then dumpIfStatement(statement) + case ALG_FOR(__) then dumpForStatement(statement) + case ALG_WHILE(__) then dumpWhileStatement(statement) + case ALG_WHEN_A(__) then dumpWhenStatement(statement) + case ALG_ASSERT(__) then + let cond_str = dumpExp(condition) + let msg_str = dumpExp(message) + let lvl_str = dumpAssertionLevel(level) + 'assert(<%cond_str%>, <%msg_str%><%lvl_str%>)' + case ALG_TERMINATE(__) then + let msg_str = dumpExp(message) + 'terminate(<%msg_str%>)' + case ALG_REINIT(__) then + let cr_str = dumpExp(cref) + let exp_str = dumpExp(newValue) + 'reinit(<%cr_str%>, <%exp_str%>)' + case ALG_NORETCALL(__) then + let exp_str = dumpExp(exp) + let cmt_str = dumpComment(comment) + '<%exp_str%><%cmt_str%>' + case ALG_RETURN(__) then + let cmt_str = dumpComment(comment) + 'return<%cmt_str%>' + case ALG_BREAK(__) then + let cmt_str = dumpComment(comment) + 'break<%cmt_str%>' + case ALG_FAILURE(stmts={stmt}) then + let cmt_str = dumpComment(comment) + 'failure(<%dumpStatement(stmt)%>)<%cmt_str%>' + case SCode.ALG_TRY(__) then dumpTryStatement(statement) + case ALG_CONTINUE(__) then + let cmt_str = dumpComment(comment) + 'continue<%cmt_str%>' + else error(sourceInfo(), "SCodeDump.dumpStatement: Unknown statement.") +end dumpStatement; + +template dumpIfStatement(SCode.Statement if_statement) +::= +match if_statement + case ALG_IF(__) then + let cond_str = dumpExp(boolExpr) + let true_branch_str = dumpStatements(trueBranch) + let else_if_str = dumpElseIfStatements(elseIfBranch) + let else_branch_str = dumpStatements(elseBranch) + let cmt_str = dumpComment(comment) + << + if <%cond_str%> then<%cmt_str%> + <%true_branch_str%> + <%else_if_str%> + else + <%else_branch_str%> + end if; + >> +end dumpIfStatement; + +template dumpElseIfStatements(list>> else_if) +::= + else_if |> eib as (cond, body) => + let cond_str = dumpExp(cond) + let body_str = dumpStatements(body) + << + elseif <%cond_str%> then + <%body_str%> + >> ;separator="\n" +end dumpElseIfStatements; + +template dumpForStatement(SCode.Statement for_statement) +::= +match for_statement + case ALG_FOR(range=SOME(e)) then + let range_str = dumpExp(e) + let body_str = dumpStatements(forBody) + let cmt_str = dumpComment(comment) + << + for <%index%> in <%range_str%> loop + <%body_str%> + end for<%cmt_str%>; + >> + case ALG_FOR(__) then + let body_str = dumpStatements(forBody) + let cmt_str = dumpComment(comment) + << + for <%index%> loop + <%body_str%> + end for<%cmt_str%>; + >> +end dumpForStatement; + +template dumpWhileStatement(SCode.Statement while_statement) +::= +match while_statement + case ALG_WHILE(__) then + let cond_str = dumpExp(boolExpr) + let body_str = dumpStatements(whileBody) + let cmt_str = dumpComment(comment) + << + while <%cond_str%> loop + <%body_str%> + end while; + >> +end dumpWhileStatement; + +template dumpWhenStatement(SCode.Statement when_statement) +::= +match when_statement + case ALG_WHEN_A(branches = ((when_cond, when_body) :: elsewhens)) then + let when_cond_str = dumpExp(when_cond) + let when_body_str = dumpStatements(when_body) + let elsewhen_str = (elsewhens |> ew as (ew_cond, ew_body) => + let ew_cond_str = dumpExp(ew_cond) + let ew_body_str = dumpStatements(ew_body) + << + elsewhen <%ew_cond_str%> then + <%ew_body_str%> + >> ;separator="\n") + let cmt_str = dumpComment(comment) + << + when <%when_cond_str%> then<%cmt_str%> + <%when_body_str%> + <%elsewhen_str%> + end when; + >> +end dumpWhenStatement; + +template dumpTryStatement(SCode.Statement try_statement) +::= +match try_statement + case s as ALG_TRY(__) then + let cmt_str = dumpComment(comment) + let algs1 = dumpStatements(body) + let algs2 = dumpStatements(elseBody) + << + try + <%algs1%> + else + <%algs2%> + end try<%cmt_str%>; + >> +end dumpTryStatement; + +template dumpPrefixes(SCode.Prefixes prefixes, String each) +::= +match prefixes + case PREFIXES(__) then + let redeclare_str = dumpRedeclare(redeclarePrefix) + let final_str = dumpFinal(finalPrefix) + let io_str = dumpInnerOuter(innerOuter) + let replaceable_str = dumpReplaceable(replaceablePrefix) + '<%redeclare_str%><%each%><%final_str%><%io_str%><%replaceable_str%>' +end dumpPrefixes; + +template dumpRedeclare(SCode.Redeclare redeclare) +::= +match redeclare + case REDECLARE(__) then 'redeclare ' +end dumpRedeclare; + +template dumpFinal(SCode.Final final) +::= +match final + case FINAL(__) then 'final ' +end dumpFinal; + +template dumpInnerOuter(Absyn.InnerOuter innerOuter) +::= +match innerOuter + case INNER(__) then 'inner ' + case OUTER(__) then 'outer ' + case INNER_OUTER(__) then 'inner outer ' +end dumpInnerOuter; + +template dumpReplaceable(SCode.Replaceable replaceable) +::= +match replaceable + case REPLACEABLE(__) then + 'replaceable ' +end dumpReplaceable; + +template dumpEach(SCode.Each each) +::= +match each + case EACH(__) then 'each ' +end dumpEach; + +template dumpEncapsulated(SCode.Encapsulated encapsulated) +::= +match encapsulated + case ENCAPSULATED(__) then 'encapsulated ' +end dumpEncapsulated; + +template dumpPartial(SCode.Partial partial) +::= +match partial + case PARTIAL(__) then 'partial ' +end dumpPartial; + +template dumpRestriction(SCode.Restriction restriction) +::= +match restriction + case R_PACKAGE(__) then 'module' + case R_METARECORD(__) then 'struct' + case R_UNIONTYPE(__) then 'uniontype' + case R_RECORD(__) then 'record' + case R_TYPE(__) then 'const' + case R_FUNCTION(__) then 'function' + else error(sourceInfo(), 'SCodeDump.dumpRestriction: Unknown restriction <%SCodeDumpTpl.dumpRestriction(restriction)%>') +end dumpRestriction; + +template dumpRestrictionTypeVars(SCode.Restriction restriction) +::= +match restriction + case R_UNIONTYPE(__) then + (if typeVars then ("{" + (typeVars |> tv => tv ; separator=",") + "}")) + else "" +end dumpRestrictionTypeVars; + +template dumpFunctionRestriction(SCode.FunctionRestriction funcRest) +::= +match funcRest + case FR_NORMAL_FUNCTION(__) then if isImpure then 'impure function' else 'function' + case FR_EXTERNAL_FUNCTION(__) then if isImpure then 'impure function' else 'function' + + case FR_OPERATOR_FUNCTION(__) then 'operator function' + case FR_RECORD_CONSTRUCTOR(__) then 'function' + else error(sourceInfo(), "SCodeDump.dumpFunctionRestriction: Unknown Function restriction.") +end dumpFunctionRestriction; + +template dumpModifier(SCode.Mod modifier) +::= +match modifier + case MOD(__) then + let binding_str = dumpModifierBinding(binding) + let submod_str = if subModLst then + '(<%(subModLst |> submod => dumpSubModifier(submod) ;separator=", ")%>)' + '<%submod_str%><%binding_str%>' +end dumpModifier; + +template dumpAnnotationModifier(SCode.Mod modifier) +::= +match modifier + case MOD(__) then + let binding_str = dumpModifierBinding(binding) + let text = subModLst |> submod => dumpAnnotationSubModifier(submod) ;separator=", " + let submod_str = if text then '(<%text%>)' + '<%submod_str%><%binding_str%>' +end dumpAnnotationModifier; + +template dumpModifierPrefix(SCode.Mod modifier) +::= +match modifier + case MOD(__) then + let final_str = dumpFinal(finalPrefix) + let each_str = dumpEach(eachPrefix) + '<%each_str%><%final_str%>' + case REDECL(__) then + let final_str = dumpFinal(finalPrefix) + let each_str = dumpEach(eachPrefix) + '<%each_str%><%final_str%>' +end dumpModifierPrefix; + +template dumpRedeclModifier(SCode.Mod modifier) +::= +match modifier + case REDECL(__) then + let each_str = dumpEach(eachPrefix) + dumpElement(element, each_str, packageContext) +end dumpRedeclModifier; + +template dumpModifierBinding(Option binding) +::= match binding case SOME(exp) then '<%\ %>= <%dumpExp(exp)%>' +end dumpModifierBinding; + +template dumpSubModifier(SCode.SubMod submod) +::= +match submod + case NAMEMOD(mod = MOD(__)) then + '<%dumpModifierPrefix(mod)%><%ident%><%dumpModifier(mod)%>' + case NAMEMOD(mod = REDECL(__)) then + '<%dumpRedeclModifier(mod)%>' +end dumpSubModifier; + +template dumpAnnotationSubModifier(SCode.SubMod submod) +::= +match submod + case NAMEMOD(mod = nameMod as MOD(__)) then + (if Config.showAnnotations() then + '<%dumpModifierPrefix(mod)%><%ident%><%dumpAnnotationModifier(nameMod)%>' + else + match ident + case "choices" + case "Documentation" + case "Dialog" + case "Diagram" + case "Icon" + case "Line" + case "Placement" + case "preferredView" + case "conversion" + case "defaultComponentName" + case "revisionId" + case "uses" + then "" + else '<%dumpModifierPrefix(nameMod)%><%ident%><%dumpAnnotationModifier(nameMod)%>') + case NAMEMOD(mod = REDECL(__)) then + '<%dumpRedeclModifier(mod)%>' +end dumpAnnotationSubModifier; + +template dumpAttributes(SCode.Attributes attributes, Context context) +::= +match attributes + case ATTR(variability=CONST(__)) then 'const ' + case ATTR(__) then dumpDirection(direction, context) +end dumpAttributes; + +template dumpVariability(SCode.Variability variability) +::= +match variability + case DISCRETE(__) then 'discrete ' + case PARAM(__) then 'parameter ' + case CONST(__) then 'const ' +end dumpVariability; + +template dumpDirection(Absyn.Direction direction, Context context) +::= +match direction + case INPUT(__) + case INPUT_OUTPUT(__) then error(sourceInfo(), 'input/output') + // Also output need to be a local, since we need to return them... + else (match context case FUNCTION(__) then 'local ') +end dumpDirection; + +template dumpAttributeDim(SCode.Attributes attributes) +::= match attributes case ATTR(__) then dumpSubscripts(arrayDims) +end dumpAttributeDim; + +template dumpAnnotationOpt(Option annotation) +::= match annotation case SOME(ann) then dumpAnnotation(ann) +end dumpAnnotationOpt; + +template dumpAnnotation(SCode.Annotation annotation) +::= + match annotation + case ANNOTATION(__) then + let modifStr = dumpAnnotationModifier(modification) + if modifStr then '<%\ %>#= annotation<%modifStr%> =#' +end dumpAnnotation; + +template dumpAnnotationElement(SCode.Annotation annotation) +::= + let annstr = '<%dumpAnnotation(annotation)%>' + if annstr then + '<%\ %><%annstr%>' +end dumpAnnotationElement; + +template dumpExternalDeclOpt(Option externalDecl) +::= match externalDecl case SOME(extdecl) then dumpExternalDecl(extdecl) +end dumpExternalDeclOpt; + +template dumpExternalDecl(SCode.ExternalDecl externalDecl) +::= +let res = match externalDecl + case EXTERNALDECL(__) then + let func_name_str = match funcName case SOME(name) then name + let func_args_str = (args |> arg => dumpExp(arg) ;separator=", ") + let func_str = if func_name_str then ' <%func_name_str%>(<%func_args_str%>)' + let lang_str = match lang case SOME(l) then ' "<%l%>"' + let ann_str = dumpAnnotationOpt(annotation_) + let output_str = match output_ case SOME(name) then ' <%dumpCref(name)%> =' + 'external<%lang_str%><%output_str%><%func_str%><%ann_str%>;' +match externalDecl + case EXTERNALDECL(lang=SOME("builtin")) then res + else res +end dumpExternalDecl; + +template dumpCommentOpt(Option comment) +::= match comment case SOME(cmt) then dumpComment(cmt) +end dumpCommentOpt; + +template dumpComment(SCode.Comment comment) +::= + match comment + case COMMENT(__) then + let ann_str = dumpAnnotationOpt(annotation_) + let cmt_str = dumpCommentStr(comment) + '<%cmt_str%><%ann_str%>' +end dumpComment; + +template dumpCommentStr(Option comment) +::= +match comment case SOME(cmt) then '<%\ %>#= <%System.escapedString(cmt,false)%> =#' +end dumpCommentStr; + +template dumpSubscripts(list subscripts) +::= + if subscripts then + let sub_str = (subscripts |> s => dumpSubscript(s) ;separator=", ") + '[<%sub_str%>]' +end dumpSubscripts; + +template dumpSubscript(Absyn.Subscript subscript) +::= +match subscript + case NOSUB(__) then ':' + case SUBSCRIPT(__) then dumpExp(subscript) +end dumpSubscript; + +template dumpExp(Absyn.Exp exp) +::= +match exp + case INTEGER(__) then value + case REAL(__) then value + case CREF(__) then dumpCref(componentRef) + case STRING(__) then ('"<%stringReplace(value,"$","\\$"); absIndent=0%>"') + case BOOL(__) then value + case e as BINARY(__) then + let lhs_str = dumpOperand(exp1, e, true) + let rhs_str = dumpOperand(exp2, e, false) + let op_str = dumpOperator(op) + '<%lhs_str%> <%op_str%> <%rhs_str%>' + case e as UNARY(__) then + let exp_str = dumpOperand(exp, e, false) + let op_str = dumpOperator(op) + '<%op_str%><%exp_str%>' + case e as LBINARY(__) then + let lhs_str = dumpOperand(exp1, e, true) + let rhs_str = dumpOperand(exp2, e, false) + let op_str = dumpOperator(op) + '<%lhs_str%> <%op_str%> <%rhs_str%>' + case e as LUNARY(__) then + let exp_str = dumpOperand(exp, e, false) + let op_str = dumpOperator(op) + '<%op_str%> <%exp_str%>' + case e as RELATION(__) then + let lhs_str = dumpOperand(exp1, e, true) + let rhs_str = dumpOperand(exp2, e, false) + let op_str = dumpOperator(op) + '<%lhs_str%> <%op_str%> <%rhs_str%>' + case IFEXP(__) then dumpIfExp(exp) + case CALL(function_=Absyn.CREF_IDENT(name="$array")) then + let args_str = dumpFunctionArgs(functionArgs) + 'list(<%args_str%>)' + case CALL(function_=function_ as CREF_IDENT(name=id)) then + let args_str = dumpFunctionArgs(functionArgs) + let func_str = (match id + case "list" then "list" + else dumpCref(function_)) + '<%func_str%>(<%args_str%>)' + case CALL(__) then + let func_str = dumpCref(function_) + let args_str = dumpFunctionArgs(functionArgs) + '<%func_str%>(<%args_str%>)' + case PARTEVALFUNCTION(__) then + let func_str = dumpCref(function_) + let args_str = dumpFunctionArgs(functionArgs) + 'function <%func_str%>(<%args_str%>)' + case ARRAY(__) then + let array_str = (arrayExp |> e => dumpExp(e) ;separator=", ") + 'list(<%array_str%>)' + case MATRIX(__) then + let matrix_str = (matrix |> row => + (row |> e => dumpExp(e) ;separator=", ") ;separator="; ") + '[<%matrix_str%>]' + case e as RANGE(step = SOME(step)) then + let start_str = dumpOperand(start, e, false) + let step_str = dumpOperand(step, e, false) + let stop_str = dumpOperand(stop, e, false) + '<%start_str%>:<%step_str%>:<%stop_str%>' + case e as RANGE(step = NONE()) then + let start_str = dumpOperand(start, e, false) + let stop_str = dumpOperand(stop, e, false) + '<%start_str%>:<%stop_str%>' + case TUPLE(__) then + let tuple_str = (expressions |> e => dumpExp(e); separator=", " ;empty) + '(<%tuple_str%>)' + case END(__) then 'end' + case AS(__) then + let exp_str = dumpExp(exp) + '<%id%> as <%exp_str%>' + case CONS(__) then + let head_str = dumpExp(head) + let rest_str = dumpExp(rest) + '<%head_str%> :: <%rest_str%>' + case MATCHEXP(__) then dumpMatchExp(exp) + case LIST(__) then + let list_str = (exps |> e => dumpExp(e) ;separator=", ") + 'list(<%list_str%>)' + case DOT(__) then + '<%dumpExp(exp)%>.<%dumpExp(index)%>' + case _ then '/* AbsynDumpTpl.dumpExp: UNHANDLED Abyn.Exp */' +end dumpExp; + +template dumpPattern(Absyn.Exp exp) +::= +match exp + case INTEGER(__) then value + case REAL(__) then value + case CREF(__) then dumpCref(componentRef) + case STRING(__) then ('"<%stringReplace(value,"$","\\$"); absIndent=0%>"') + case BOOL(__) then value + case ARRAY(arrayExp=exps) + case LIST(__) + case CALL(function_=Absyn.CREF_IDENT(name="list"), functionArgs=FUNCTIONARGS(args=exps)) + case CALL(function_=Absyn.CREF_IDENT(name="$array"), functionArgs=FUNCTIONARGS(args=exps)) then + '<%exps |> e => '<%dumpPattern(e)%> => '%> Nil()' + case CALL(function_=function_ as CREF_IDENT(name=id)) then + let args_str = dumpFunctionArgsPattern(functionArgs) + let func_str = (match id + case "list" then "list" + else dumpCref(function_)) + '<%func_str%>(<%args_str%>)' + case CALL(__) then + let func_str = dumpCref(function_) + let args_str = dumpFunctionArgsPattern(functionArgs) + '<%func_str%>(<%args_str%>)' + case TUPLE(__) then + let tuple_str = (expressions |> e => dumpPattern(e); separator=", " ;empty) + '(<%tuple_str%>)' + case AS(__) then + let exp_str = dumpPattern(exp) + '<%id%> as <%exp_str%>' + case CONS(__) then + let head_str = dumpPattern(head) + let rest_str = dumpPattern(rest) + '<%head_str%> :: <%rest_str%>' + case _ then '/* AbsynDumpTpl.dumpPattern: UNHANDLED Abyn.Exp <%dumpExp(exp)%> */' +end dumpPattern; + +template dumpLhsExp(Absyn.Exp lhs) +::= +match lhs + case IFEXP(__) then '(<%dumpExp(lhs)%>)' + else dumpExp(lhs) +end dumpLhsExp; + +template dumpOperand(Absyn.Exp operand, Absyn.Exp operation, Boolean lhs) +::= + let op_str = dumpExp(operand) + if shouldParenthesize(operand, operation, lhs) then + '(<%op_str%>)' + else + op_str +end dumpOperand; + +template dumpIfExp(Absyn.Exp if_exp) +::= +match if_exp + case IFEXP(__) then + let cond_str = dumpExp(ifExp) + let true_branch_str = dumpExp(trueBranch) + let else_branch_str = dumpExp(elseBranch) + let else_if_str = dumpElseIfExp(elseIfBranch) + 'if <%cond_str%> then <%true_branch_str%><%else_if_str%> else <%else_branch_str%>' +end dumpIfExp; + +template dumpElseIfExp(list> else_if) +::= + else_if |> eib as (cond, branch) => + let cond_str = dumpExp(cond) + let branch_str = dumpExp(branch) + ' elseif <%cond_str%> then <%branch_str%>' ;separator="\n" +end dumpElseIfExp; + +template dumpMatchExp(Absyn.Exp match_exp) +::= +match match_exp + case MATCHEXP(__) then + let ty_str = dumpMatchType(matchTy) + let decls = dumpElements2(SCodeUtil.translateEitemlist(localDecls), false, functionContext) + let input_str = dumpExp(inputExp) + let cases_str = (cases |> c => dumpMatchCase(c) ;separator="\n\n") + let cmt_str = AbsynDumpTpl.dumpStringCommentOption(comment) + << + begin + <%decls%> + <%ty_str%> <%input_str%> begin + <%cases_str%><%cmt_str%> + end + end + >> +end dumpMatchExp; + +template dumpMatchType(Absyn.MatchType match_type) +::= +match match_type + case MATCH() then "@match" + case MATCHCONTINUE() then "@matchcontinue" +end dumpMatchType; + +template dumpMatchEquations(ClassPart cp) +::= + match cp + case EQUATIONS(contents={}) then "" + case EQUATIONS(contents=eql) then + dumpEquations(SCodeUtil.translateEquations(eql, false)) + case ALGORITHMS(contents={}) then "" + case ALGORITHMS(contents=algs) then + dumpStatements(SCodeUtil.translateClassdefAlgorithmitems(algs)) +end dumpMatchEquations; + +template dumpMatchCase(Absyn.Case c) +::= +match c + case CASE(__) then + let pattern_str = dumpPattern(pattern) + let guard_str = match patternGuard case SOME(g) then 'guard <%dumpExp(g)%> ' + let eql_str = dumpMatchEquations(classPart) + let result_str = dumpExp(result) + let cmt_str = AbsynDumpTpl.dumpStringCommentOption(comment) + << + <%pattern_str%> <%guard_str%><%cmt_str%> => ( + <%eql_str%> + <%result_str%> + ) + >> + case ELSE(__) then + let eql_str = dumpMatchEquations(classPart) + let result_str = dumpExp(result) + let cmt_str = AbsynDumpTpl.dumpStringCommentOption(comment) + << + _ <%cmt_str%> => begin ( + <%eql_str%> + <%result_str%> + ) + >> +end dumpMatchCase; + +template dumpOperator(Absyn.Operator op) +::= +match op + case ADD(__) then '+' + case SUB(__) then '-' + case MUL(__) then '*' + case DIV(__) then '/' + case POW(__) then '^' + case UPLUS(__) then '+' + case UMINUS(__) then '-' + case ADD_EW(__) then '.+' + case SUB_EW(__) then '.-' + case MUL_EW(__) then '.*' + case DIV_EW(__) then './' + case POW_EW(__) then '.^' + case UPLUS_EW(__) then '.+' + case UMINUS_EW(__) then '.-' + case AND(__) then 'and' + case OR(__) then 'or' + case NOT(__) then 'not' + case LESS(__) then '<' + case LESSEQ(__) then '<=' + case GREATER(__) then '>' + case GREATEREQ(__) then '>=' + case EQUAL(__) then '==' + case NEQUAL(__) then '<>' +end dumpOperator; + +template dumpCref(Absyn.ComponentRef cref) +::= +match cref + case CREF_QUAL(__) then + '<%name%><%dumpSubscripts(subscripts)%>.<%dumpCref(componentRef)%>' + case CREF_IDENT(__) + then '<%name%><%dumpSubscripts(subscripts)%>' + case CREF_FULLYQUALIFIED(__) then '.<%dumpCref(componentRef)%>' + case WILD(__) then if Config.acceptMetaModelicaGrammar() then "_" else "" + case ALLWILD(__) then '__' +end dumpCref; + +template dumpFunctionArgs(Absyn.FunctionArgs args) +::= +match args + case FUNCTIONARGS(__) then + let args_str = (args |> arg => dumpExp(arg) ;separator=", ") + let namedargs_str = (argNames |> narg => dumpNamedArg(narg) ;separator=", ") + let separator = if args_str then if argNames then ', ' + '<%args_str%><%separator%><%namedargs_str%>' + case FOR_ITER_FARG(__) then + let exp_str = dumpExp(exp) + let iter_str = (iterators |> i => dumpForIterator(i) ;separator=", ") + '<%exp_str%> <%match iterType case THREAD(__) then "threaded "%>for <%iter_str%>' +end dumpFunctionArgs; + +template dumpFunctionArgsPattern(Absyn.FunctionArgs args) +::= +match args + case FUNCTIONARGS(__) then + let args_str = (args |> arg => dumpPattern(arg) ;separator=", ") + let namedargs_str = (argNames |> narg => dumpNamedArgPattern(narg) ;separator=", ") + let separator = if args_str then if argNames then ', ' + '<%args_str%><%separator%><%namedargs_str%>' + else 'ERROR FOR_ITER_FARG in pattern' +end dumpFunctionArgsPattern; + +template dumpNamedArg(Absyn.NamedArg narg) +::= +match narg + case NAMEDARG(__) then + '<%argName%> = <%dumpExp(argValue)%>' +end dumpNamedArg; + +template dumpNamedArgPattern(Absyn.NamedArg narg) +::= +match narg + case NAMEDARG(__) then + '<%argName%> = <%dumpPattern(argValue)%>' +end dumpNamedArgPattern; + +template dumpForIterators(Absyn.ForIterators iters) +::= (iters |> i => dumpForIterator(i) ;separator=", ") +end dumpForIterators; + +template dumpForIterator(Absyn.ForIterator iterator) +::= +match iterator + case ITERATOR(__) then + let range_str = match range case SOME(r) then ' in <%dumpExp(r)%>' + let guard_str = match guardExp case SOME(g) then ' guard <%dumpExp(g)%>' + '<%name%><%guard_str%><%range_str%>' +end dumpForIterator; + +template error(SourceInfo srcInfo, String errMessage) +"Example source template error reporting template to be used together with the sourceInfo() magic function. +Usage: error(sourceInfo(), <>) " +::= +let() = Tpl.addSourceTemplateError(errMessage, srcInfo) +<< + +#error "<% Error.infoStr(srcInfo) %> <% errMessage %>"<%\n%> +>> +end error; + +annotation(__OpenModelica_Interface="backend"); +end MMToJulia; +// vim: filetype=susan sw=2 sts= \ No newline at end of file diff --git a/OMCompiler/Compiler/Template/MMToJuliaTV.mo b/OMCompiler/Compiler/Template/MMToJuliaTV.mo new file mode 100644 index 00000000000..4e47504674f --- /dev/null +++ b/OMCompiler/Compiler/Template/MMToJuliaTV.mo @@ -0,0 +1,1558 @@ +interface package MMToJuliaTV + +package builtin + function listReverse + input list inLst; + output list outLst; + replaceable type T subtypeof Any; + end listReverse; + + function boolAnd + input Boolean b1; + input Boolean b2; + output Boolean b; + end boolAnd; + + function boolOr + input Boolean a; + input Boolean b; + output Boolean c; + end boolOr; + + function boolNot + input Boolean b; + output Boolean nb; + end boolNot; + + uniontype SourceInfo + record SOURCEINFO + String fileName; + Boolean isReadOnly; + Integer lineNumberStart; + Integer columnNumberStart; + Integer lineNumberEnd; + Integer columnNumberEnd; + end SOURCEINFO; + end SourceInfo; +end builtin; + +package Absyn + type Ident = String; + + uniontype Program + record PROGRAM + list classes; + Within within_; + end PROGRAM; + end Program; + + uniontype Within + record WITHIN + Path path; + end WITHIN; + + record TOP end TOP; + end Within; + + uniontype Class + record CLASS + Ident name; + Boolean partialPrefix; + Boolean finalPrefix; + Boolean encapsulatedPrefix; + Restriction restriction; + ClassDef body; + builtin.SourceInfo info; + end CLASS; + end Class; + + uniontype ClassDef + record PARTS + list typeVars; + list classAttrs; + list classParts; + list ann; + Option comment; + end PARTS; + + record DERIVED + TypeSpec typeSpec; + ElementAttributes attributes; + list arguments; + Option comment; + end DERIVED; + + record ENUMERATION + EnumDef enumLiterals; + Option comment; + end ENUMERATION; + + record OVERLOAD + list functionNames; + Option comment; + end OVERLOAD; + + record CLASS_EXTENDS + Ident baseClassName; + list modifications; + Option comment; + list parts; + list ann; + end CLASS_EXTENDS; + + record PDER + Path functionName; + list vars; + Option comment; + end PDER; + end ClassDef; + + uniontype TypeSpec + record TPATH + Path path; + Option arrayDim; + end TPATH; + + record TCOMPLEX + Path path; + list typeSpecs; + Option arrayDim; + end TCOMPLEX; + end TypeSpec; + + uniontype EnumDef + record ENUMLITERALS + list enumLiterals; + end ENUMLITERALS; + + record ENUM_COLON end ENUM_COLON; + end EnumDef; + + uniontype EnumLiteral + record ENUMLITERAL + Ident literal; + Option comment; + end ENUMLITERAL; + end EnumLiteral; + + uniontype ClassPart + record PUBLIC + list contents; + end PUBLIC; + + record PROTECTED + list contents; + end PROTECTED; + + record CONSTRAINTS + list contents; + end CONSTRAINTS; + + record EQUATIONS + list contents; + end EQUATIONS; + + record INITIALEQUATIONS + list contents; + end INITIALEQUATIONS; + + record ALGORITHMS + list contents; + end ALGORITHMS; + + record INITIALALGORITHMS + list contents; + end INITIALALGORITHMS; + + record EXTERNAL + ExternalDecl externalDecl; + Option annotation_; + end EXTERNAL; + end ClassPart; + + uniontype ElementItem + record ELEMENTITEM + Element element; + end ELEMENTITEM; + + record LEXER_COMMENT + String comment; + end LEXER_COMMENT; + end ElementItem; + + uniontype Element + record ELEMENT + Boolean finalPrefix; + Option redeclareKeywords; + InnerOuter innerOuter; + ElementSpec specification; + builtin.SourceInfo info; + Option constrainClass; + end ELEMENT; + + record DEFINEUNIT + Ident name; + list args; + end DEFINEUNIT; + + record TEXT + Option optName; + String string; + builtin.SourceInfo info; + end TEXT; + end Element; + + uniontype ConstrainClass + record CONSTRAINCLASS + ElementSpec elementSpec; + Option comment; + end CONSTRAINCLASS; + end ConstrainClass; + + uniontype ElementSpec + record CLASSDEF + Boolean replaceable_; + Class class_; + end CLASSDEF; + + record EXTENDS + Path path; + list elementArg; + Option annotationOpt; + end EXTENDS; + + record IMPORT + Import import_; + Option comment; + builtin.SourceInfo info; + end IMPORT; + + record COMPONENTS + ElementAttributes attributes; + TypeSpec typeSpec; + list components; + end COMPONENTS; + end ElementSpec; + + uniontype InnerOuter + record INNER end INNER; + record OUTER end OUTER; + record INNER_OUTER end INNER_OUTER; + record NOT_INNER_OUTER end NOT_INNER_OUTER; + end InnerOuter; + + uniontype Import + record NAMED_IMPORT + Ident name; + Path path; + end NAMED_IMPORT; + + record QUAL_IMPORT + Path path; + end QUAL_IMPORT; + + record UNQUAL_IMPORT + Path path; + end UNQUAL_IMPORT; + + record GROUP_IMPORT + Path prefix; + list groups; + end GROUP_IMPORT; + end Import; + + uniontype GroupImport + record GROUP_IMPORT_NAME + String name; + end GROUP_IMPORT_NAME; + + record GROUP_IMPORT_RENAME + String rename; + String name; + end GROUP_IMPORT_RENAME; + end GroupImport; + + uniontype ComponentItem + record COMPONENTITEM + Component component; + Option condition; + Option comment; + end COMPONENTITEM; + end ComponentItem; + + type ComponentCondition = Exp; + + uniontype Component + record COMPONENT + Ident name; + ArrayDim arrayDim; + Option modification; + end COMPONENT; + end Component; + + uniontype EquationItem + record EQUATIONITEM + Equation equation_; + Option comment; + end EQUATIONITEM; + + record EQUATIONITEMCOMMENT + String comment; + end EQUATIONITEMCOMMENT; + end EquationItem; + + uniontype AlgorithmItem + record ALGORITHMITEM + Algorithm algorithm_; + Option comment; + end ALGORITHMITEM; + + record ALGORITHMITEMCOMMENT + String comment; + end ALGORITHMITEMCOMMENT; + end AlgorithmItem; + + uniontype Equation + record EQ_IF + Exp ifExp; + list equationTrueItems; + list>> elseIfBranches; + list equationElseItems; + end EQ_IF; + + record EQ_EQUALS + Exp leftSide; + Exp rightSide; + end EQ_EQUALS; + + record EQ_PDE + Exp leftSide; + Exp rightSide; + ComponentRef domain; + end EQ_PDE; + + record EQ_CONNECT + ComponentRef connector1; + ComponentRef connector2; + end EQ_CONNECT; + + record EQ_FOR + ForIterators iterators; + list forEquations; + end EQ_FOR; + + record EQ_WHEN_E + Exp whenExp; + list whenEquations; + list>> elseWhenEquations; + end EQ_WHEN_E; + + record EQ_NORETCALL + ComponentRef functionName; + FunctionArgs functionArgs; + end EQ_NORETCALL; + + record EQ_FAILURE + EquationItem equ; + end EQ_FAILURE; + end Equation; + + uniontype Algorithm + record ALG_ASSIGN + Exp assignComponent; + Exp value; + end ALG_ASSIGN; + + record ALG_IF + Exp ifExp; + list trueBranch; + list>> elseIfAlgorithmBranch; + list elseBranch; + end ALG_IF; + + record ALG_FOR + ForIterators iterators; + list forBody; + end ALG_FOR; + + record ALG_PARFOR + ForIterators iterators; + list parforBody; + end ALG_PARFOR; + + record ALG_WHILE + Exp boolExpr; + list whileBody; + end ALG_WHILE; + + record ALG_WHEN_A + Exp boolExpr; + list whenBody; + list>> elseWhenAlgorithmBranch; + end ALG_WHEN_A; + + record ALG_NORETCALL + ComponentRef functionCall; + FunctionArgs functionArgs; + end ALG_NORETCALL; + + record ALG_RETURN end ALG_RETURN; + record ALG_BREAK end ALG_BREAK; + + record ALG_FAILURE + list equ; + end ALG_FAILURE; + + record ALG_TRY + list body; + list elseBody; + end ALG_TRY; + + record ALG_CONTINUE end ALG_CONTINUE; + end Algorithm; + + uniontype Modification + record CLASSMOD + list elementArgLst; + EqMod eqMod; + end CLASSMOD; + end Modification; + + uniontype EqMod + record NOMOD end NOMOD; + + record EQMOD + Exp exp; + end EQMOD; + end EqMod; + + uniontype ElementArg + record MODIFICATION + Boolean finalPrefix; + Each eachPrefix; + Path path; + Option modification; + Option comment; + end MODIFICATION; + + record REDECLARATION + Boolean finalPrefix; + RedeclareKeywords redeclareKeywords; + Each eachPrefix; + ElementSpec elementSpec; + Option constrainClass; + end REDECLARATION; + end ElementArg; + + uniontype RedeclareKeywords + record REDECLARE end REDECLARE; + record REPLACEABLE end REPLACEABLE; + record REDECLARE_REPLACEABLE end REDECLARE_REPLACEABLE; + end RedeclareKeywords; + + uniontype Each + record EACH end EACH; + record NON_EACH end NON_EACH; + end Each; + + uniontype ElementAttributes + record ATTR + Boolean flowPrefix; + Boolean streamPrefix; + Parallelism parallelism; + Variability variability; + IsField isField; + Direction direction; + ArrayDim arrayDim; + end ATTR; + end ElementAttributes; + + uniontype IsField "Is field" + record NONFIELD "variable is not a field" end NONFIELD; + record FIELD "variable is a field" end FIELD; + end IsField; + + uniontype Parallelism + record PARGLOBAL end PARGLOBAL; + record PARLOCAL end PARLOCAL; + record NON_PARALLEL end NON_PARALLEL; + end Parallelism; + + uniontype FlowStream + record FLOW end FLOW; + record STREAM end STREAM; + record NOT_FLOW_STREAM end NOT_FLOW_STREAM; + end FlowStream; + + uniontype Variability + record VAR end VAR; + record DISCRETE end DISCRETE; + record PARAM end PARAM; + record CONST end CONST; + end Variability; + + uniontype Direction + record INPUT end INPUT; + record OUTPUT end OUTPUT; + record BIDIR end BIDIR; + record INPUT_OUTPUT end INPUT_OUTPUT; + end Direction; + + uniontype ForIterator + record ITERATOR + String name; + Option guardExp; + Option range; + end ITERATOR; + end ForIterator; + + type ForIterators = list; + + uniontype Exp + record INTEGER + Integer value; + end INTEGER; + + record REAL + String value; + end REAL; + + record CREF + ComponentRef componentRef; + end CREF; + + record STRING + String value; + end STRING; + + record BOOL + Boolean value; + end BOOL; + + record BINARY + Exp exp1; + Operator op; + Exp exp2; + end BINARY; + + record UNARY + Operator op; + Exp exp; + end UNARY; + + record LBINARY + Exp exp1; + Operator op; + Exp exp2; + end LBINARY; + + record LUNARY + Operator op; + Exp exp; + end LUNARY; + + record RELATION + Exp exp1; + Operator op; + Exp exp2; + end RELATION; + + record IFEXP + Exp ifExp; + Exp trueBranch; + Exp elseBranch; + list> elseIfBranch; + end IFEXP; + + record CALL + ComponentRef function_; + FunctionArgs functionArgs ; + end CALL; + + record PARTEVALFUNCTION + ComponentRef function_; + FunctionArgs functionArgs ; + end PARTEVALFUNCTION; + + record ARRAY + list arrayExp ; + end ARRAY; + + record MATRIX + list> matrix ; + end MATRIX; + + record RANGE + Exp start; + Option step; + Exp stop; + end RANGE; + + record TUPLE + list expressions; + end TUPLE; + + record END + end END; + + record CODE + CodeNode code; + end CODE; + + record AS + Ident id; + Exp exp; + end AS; + + record CONS + Exp head; + Exp rest; + end CONS; + + record MATCHEXP + MatchType matchTy; + Exp inputExp; + list localDecls; + list cases; + Option comment; + end MATCHEXP; + + record LIST + list exps; + end LIST; + + record DOT "exp.index" + Exp exp; + Exp index; + end DOT; + + end Exp; + + uniontype Case + record CASE + Exp pattern; + Option patternGuard; + builtin.SourceInfo patternInfo; + list localDecls; + ClassPart classPart; + Exp result; + builtin.SourceInfo resultInfo; + Option comment; + builtin.SourceInfo info; + end CASE; + + record ELSE + list localDecls; + ClassPart classPart; + Exp result; + builtin.SourceInfo resultInfo; + Option comment; + builtin.SourceInfo info; + end ELSE; + end Case; + + uniontype MatchType + record MATCH end MATCH; + record MATCHCONTINUE end MATCHCONTINUE; + end MatchType; + + uniontype CodeNode + record C_TYPENAME + Path path; + end C_TYPENAME; + + record C_VARIABLENAME + ComponentRef componentRef; + end C_VARIABLENAME; + + record C_CONSTRAINTSECTION + Boolean boolean; + list equationItemLst; + end C_CONSTRAINTSECTION; + + record C_EQUATIONSECTION + Boolean boolean; + list equationItemLst; + end C_EQUATIONSECTION; + + record C_ALGORITHMSECTION + Boolean boolean; + list algorithmItemLst; + end C_ALGORITHMSECTION; + + record C_ELEMENT + Element element; + end C_ELEMENT; + + record C_EXPRESSION + Exp exp; + end C_EXPRESSION; + + record C_MODIFICATION + Modification modification; + end C_MODIFICATION; + end CodeNode; + + uniontype FunctionArgs + record FUNCTIONARGS + list args; + list argNames; + end FUNCTIONARGS; + + record FOR_ITER_FARG + Exp exp; + ReductionIterType iterType; + ForIterators iterators; + end FOR_ITER_FARG; + end FunctionArgs; + + uniontype ReductionIterType + record COMBINE + end COMBINE; + record THREAD + end THREAD; + end ReductionIterType; + + uniontype NamedArg + record NAMEDARG + Ident argName; + Exp argValue; + end NAMEDARG; + end NamedArg; + + uniontype Operator + record ADD end ADD; + record SUB end SUB; + record MUL end MUL; + record DIV end DIV; + record POW end POW; + record UPLUS end UPLUS; + record UMINUS end UMINUS; + record ADD_EW end ADD_EW; + record SUB_EW end SUB_EW; + record MUL_EW end MUL_EW; + record DIV_EW end DIV_EW; + record POW_EW end POW_EW; + record UPLUS_EW end UPLUS_EW; + record UMINUS_EW end UMINUS_EW; + record AND end AND; + record OR end OR; + record NOT end NOT; + record LESS end LESS; + record LESSEQ end LESSEQ; + record GREATER end GREATER; + record GREATEREQ end GREATEREQ; + record EQUAL end EQUAL; + record NEQUAL end NEQUAL; + end Operator; + + uniontype Subscript + record NOSUB end NOSUB; + + record SUBSCRIPT + Exp subscript; + end SUBSCRIPT; + end Subscript; + + type ArrayDim = list; + + uniontype ComponentRef + record CREF_FULLYQUALIFIED + ComponentRef componentRef; + end CREF_FULLYQUALIFIED; + record CREF_QUAL + Ident name; + list subscripts; + ComponentRef componentRef; + end CREF_QUAL; + + record CREF_IDENT + Ident name; + list subscripts; + end CREF_IDENT; + + record WILD end WILD; + record ALLWILD end ALLWILD; + end ComponentRef; + + uniontype Path + record QUALIFIED + Ident name; + Path path; + end QUALIFIED; + + record IDENT + Ident name; + end IDENT; + + record FULLYQUALIFIED + Path path; + end FULLYQUALIFIED; + end Path; + + uniontype Restriction + record R_CLASS end R_CLASS; + record R_OPTIMIZATION end R_OPTIMIZATION; + record R_MODEL end R_MODEL; + record R_RECORD end R_RECORD; + record R_BLOCK end R_BLOCK; + record R_CONNECTOR end R_CONNECTOR; + record R_EXP_CONNECTOR end R_EXP_CONNECTOR; + record R_TYPE end R_TYPE; + record R_PACKAGE end R_PACKAGE; + record R_FUNCTION + FunctionRestriction functionRestriction; + end R_FUNCTION; + record R_OPERATOR end R_OPERATOR; + record R_OPERATOR_RECORD end R_OPERATOR_RECORD; + record R_ENUMERATION end R_ENUMERATION; + record R_PREDEFINED_INTEGER end R_PREDEFINED_INTEGER; + record R_PREDEFINED_REAL end R_PREDEFINED_REAL; + record R_PREDEFINED_STRING end R_PREDEFINED_STRING; + record R_PREDEFINED_BOOLEAN end R_PREDEFINED_BOOLEAN; + record R_PREDEFINED_ENUMERATION end R_PREDEFINED_ENUMERATION; + record R_UNIONTYPE end R_UNIONTYPE; + record R_METARECORD + Path name; + Integer index; + Boolean singleton; + list typeVars; + end R_METARECORD; + record R_UNKNOWN end R_UNKNOWN; + end Restriction; + + uniontype FunctionPurity + record PURE end PURE; + record IMPURE end IMPURE; + record NO_PURITY end NO_PURITY; + end FunctionPurity; + + uniontype FunctionRestriction + record FR_NORMAL_FUNCTION + FunctionPurity purity; + end FR_NORMAL_FUNCTION; + + record FR_OPERATOR_FUNCTION end FR_OPERATOR_FUNCTION; + record FR_PARALLEL_FUNCTION end FR_PARALLEL_FUNCTION; + record FR_KERNEL_FUNCTION end FR_KERNEL_FUNCTION; + end FunctionRestriction; + + uniontype Annotation + record ANNOTATION + list elementArgs; + end ANNOTATION; + end Annotation; + + uniontype Comment + record COMMENT + Option annotation_; + Option comment; + end COMMENT; + end Comment; + + uniontype ExternalDecl + record EXTERNALDECL + Option funcName; + Option lang; + Option output_; + list args; + Option annotation_; + end EXTERNALDECL; + end ExternalDecl; + + function isClassdef + input Element inElement; + output Boolean b; + end isClassdef; + +end Absyn; + +package Config + function acceptMetaModelicaGrammar + output Boolean outBoolean; + end acceptMetaModelicaGrammar; + function showAnnotations + output Boolean show; + end showAnnotations; +end Config; + +package Dump + function shouldParenthesize + input Absyn.Exp inOperand; + input Absyn.Exp inOperator; + input Boolean inLhs; + output Boolean outShouldParenthesize; + end shouldParenthesize; + + uniontype DumpOptions + record DUMPOPTIONS + String fileName; + end DUMPOPTIONS; + end DumpOptions; + + constant DumpOptions defaultDumpOptions; + + function boolUnparseFileFromInfo + input builtin.SourceInfo info; + input DumpOptions options; + output Boolean b; + end boolUnparseFileFromInfo; + + function expPriority + input Absyn.Exp inExp; + output Integer outInteger; + end expPriority; +end Dump; + +package Tpl + function addSourceTemplateError + input String inErrMsg; + input builtin.SourceInfo inInfo; + end addSourceTemplateError; + + function addTemplateError + input String inErrMsg; + end addTemplateError; +end Tpl; + +package Flags + uniontype ConfigFlag end ConfigFlag; + constant ConfigFlag MODELICA_OUTPUT; + function getConfigBool + input ConfigFlag inFlag; + output Boolean outValue; + end getConfigBool; +end Flags; + + +package builtin + function boolNot + input Boolean inBoolean; + output Boolean outNegatedBoolean; + end boolNot; + + function intLt + input Integer x; + input Integer y; + output Boolean outResult; + end intLt; + + function intEq + input Integer x; + input Integer y; + output Boolean outResult; + end intEq; + + function listLength "Return the length of the list" + replaceable type TypeVar subtypeof Any; + input list lst; + output Integer result; + end listLength; + + uniontype SourceInfo "The Info attribute provides location information for elements and classes." + record SOURCEINFO + String fileName; + Boolean isReadOnly; + Integer lineNumberStart; + Integer columnNumberStart; + Integer lineNumberEnd; + Integer columnNumberEnd; + Real lastModification; + end SOURCEINFO; + end SourceInfo; + +end builtin; + +package SCode + type Ident = Absyn.Ident; + type Path = Absyn.Path; + type Subscript = Absyn.Subscript; + + uniontype Restriction + record R_CLASS end R_CLASS; + record R_OPTIMIZATION end R_OPTIMIZATION; + record R_MODEL end R_MODEL; + record R_RECORD + Boolean isOperator; + end R_RECORD; + record R_BLOCK end R_BLOCK; + record R_CONNECTOR + Boolean isExpandable; + end R_CONNECTOR; + record R_OPERATOR end R_OPERATOR; + record R_OPERATOR_FUNCTION end R_OPERATOR_FUNCTION; + record R_OPERATOR_RECORD end R_OPERATOR_RECORD; + record R_TYPE end R_TYPE; + record R_PACKAGE end R_PACKAGE; + record R_FUNCTION + FunctionRestriction functionRestriction; + end R_FUNCTION; + record R_EXT_FUNCTION end R_EXT_FUNCTION; + record R_ENUMERATION end R_ENUMERATION; + + record R_PREDEFINED_INTEGER end R_PREDEFINED_INTEGER; + record R_PREDEFINED_REAL end R_PREDEFINED_REAL; + record R_PREDEFINED_STRING end R_PREDEFINED_STRING; + record R_PREDEFINED_BOOLEAN end R_PREDEFINED_BOOLEAN; + record R_PREDEFINED_ENUMERATION end R_PREDEFINED_ENUMERATION; + + record R_METARECORD + Absyn.Path name; + Integer index; + list typeVars; + end R_METARECORD; + + record R_UNIONTYPE + list typeVars; + end R_UNIONTYPE; + end Restriction; + + uniontype FunctionRestriction + record FR_NORMAL_FUNCTION "a normal function" + Boolean isImpure; + end FR_NORMAL_FUNCTION; + record FR_EXTERNAL_FUNCTION "an external function" + Boolean isImpure; + end FR_EXTERNAL_FUNCTION; + + record FR_OPERATOR_FUNCTION "an operator function" end FR_OPERATOR_FUNCTION; + record FR_RECORD_CONSTRUCTOR "record constructor" end FR_RECORD_CONSTRUCTOR; + end FunctionRestriction; + + uniontype Mod + record MOD + Final finalPrefix; + Each eachPrefix; + list subModLst; + Option binding; + end MOD; + + record REDECL + Final finalPrefix; + Each eachPrefix; + Element element; + end REDECL; + + record NOMOD end NOMOD; + end Mod; + + uniontype SubMod + record NAMEMOD + Ident ident; + Mod mod; + end NAMEMOD; + end SubMod; + + type Program = list; + + uniontype Enum + record ENUM + Ident literal; + Comment comment; + end ENUM; + end Enum; + + uniontype ClassDef + record PARTS + list elementLst; + list normalEquationLst; + list initialEquationLst; + list normalAlgorithmLst; + list initialAlgorithmLst; + Option externalDecl; + end PARTS; + + record CLASS_EXTENDS + Ident baseClassName; + Mod modifications; + ClassDef composition; + end CLASS_EXTENDS; + + record DERIVED + Absyn.TypeSpec typeSpec; + Mod modifications; + Attributes attributes; + end DERIVED; + + record ENUMERATION + list enumLst; + end ENUMERATION; + + record OVERLOAD + list pathLst; + end OVERLOAD; + + record PDER + Absyn.Path functionPath; + list derivedVariables; + end PDER; + + end ClassDef; + + uniontype Comment + record COMMENT + Option annotation_; + Option comment; + end COMMENT; + end Comment; + + uniontype Annotation + record ANNOTATION + Mod modification; + end ANNOTATION; + end Annotation; + + uniontype ExternalDecl + record EXTERNALDECL + Option funcName; + Option lang; + Option output_; + list args; + Option annotation_ ; + end EXTERNALDECL; + + end ExternalDecl; + + uniontype Equation + record EQUATION + EEquation eEquation; + end EQUATION; + end Equation; + + uniontype EEquation + record EQ_IF + list condition; + list> thenBranch; + list elseBranch; + Comment comment; + SourceInfo info; + end EQ_IF; + + record EQ_EQUALS + Absyn.Exp expLeft; + Absyn.Exp expRight; + Comment comment; + SourceInfo info; + end EQ_EQUALS; + + record EQ_PDE + Absyn.Exp expLeft; + Absyn.Exp expRight; + ComponentRef domain; + Comment comment; + SourceInfo info; + end EQ_PDE; + + record EQ_CONNECT + Absyn.ComponentRef crefLeft; + Absyn.ComponentRef crefRight; + Comment comment; + SourceInfo info; + end EQ_CONNECT; + + record EQ_FOR + Ident index; + Option range; + list eEquationLst; + Comment comment; + SourceInfo info; + end EQ_FOR; + + record EQ_WHEN + Absyn.Exp condition; + list eEquationLst; + list>> elseBranches; + Comment comment; + SourceInfo info; + end EQ_WHEN; + + record EQ_ASSERT + Absyn.Exp condition; + Absyn.Exp message; + Absyn.Exp level; + Comment comment; + SourceInfo info; + end EQ_ASSERT; + + record EQ_TERMINATE + Absyn.Exp message; + Comment comment; + SourceInfo info; + end EQ_TERMINATE; + + record EQ_REINIT + Absyn.Exp cref; + Absyn.Exp expReinit; + Comment comment; + SourceInfo info; + end EQ_REINIT; + + record EQ_NORETCALL + Absyn.Exp exp; + Comment comment; + SourceInfo info; + end EQ_NORETCALL; + + end EEquation; + + uniontype AlgorithmSection + record ALGORITHM + list statements; + end ALGORITHM; + + end AlgorithmSection; + + uniontype Statement + record ALG_ASSIGN + Absyn.Exp assignComponent; + Absyn.Exp value; + Comment comment; + SourceInfo info; + end ALG_ASSIGN; + + record ALG_IF + Absyn.Exp boolExpr; + list trueBranch; + list>> elseIfBranch; + list elseBranch; + Comment comment; + SourceInfo info; + end ALG_IF; + + record ALG_FOR + String index; + Option range; + list forBody; + Comment comment; + SourceInfo info; + end ALG_FOR; + + record ALG_WHILE + Absyn.Exp boolExpr; + list whileBody; + Comment comment; + SourceInfo info; + end ALG_WHILE; + + record ALG_WHEN_A + list>> branches; + Comment comment; + SourceInfo info; + end ALG_WHEN_A; + + record ALG_ASSERT + Absyn.Exp condition; + Absyn.Exp message; + Absyn.Exp level; + Comment comment; + SourceInfo info; + end ALG_ASSERT; + + record ALG_TERMINATE + Absyn.Exp message; + Comment comment; + SourceInfo info; + end ALG_TERMINATE; + + record ALG_REINIT + Absyn.Exp cref; + Absyn.Exp newValue; + Comment comment; + SourceInfo info; + end ALG_REINIT; + + record ALG_NORETCALL + Absyn.Exp exp; + Comment comment; + SourceInfo info; + end ALG_NORETCALL; + + record ALG_RETURN + Comment comment; + SourceInfo info; + end ALG_RETURN; + + record ALG_BREAK + Comment comment; + SourceInfo info; + end ALG_BREAK; + + record ALG_CATCH + list catchBody; + Comment comment; + SourceInfo info; + end ALG_CATCH; + + record ALG_THROW + Comment comment; + SourceInfo info; + end ALG_THROW; + + record ALG_FAILURE + list stmts; + Comment comment; + SourceInfo info; + end ALG_FAILURE; + + record ALG_TRY + list body; + list elseBody; + Comment comment; + SourceInfo info; + end ALG_TRY; + + record ALG_CONTINUE + Comment comment; + SourceInfo info; + end ALG_CONTINUE; + + end Statement; + + uniontype Visibility + record PUBLIC end PUBLIC; + record PROTECTED end PROTECTED; + end Visibility; + + uniontype Redeclare + record REDECLARE end REDECLARE; + record NOT_REDECLARE end NOT_REDECLARE; + end Redeclare; + + uniontype ConstrainClass + record CONSTRAINCLASS + Absyn.Path constrainingClass; + Mod modifier; + Option comment; + end CONSTRAINCLASS; + end ConstrainClass; + + uniontype Replaceable + record REPLACEABLE + Option cc; + end REPLACEABLE; + record NOT_REPLACEABLE end NOT_REPLACEABLE; + end Replaceable; + + uniontype Final + record FINAL end FINAL; + record NOT_FINAL end NOT_FINAL; + end Final; + + uniontype Each + record EACH end EACH; + record NOT_EACH end NOT_EACH; + end Each; + + uniontype Encapsulated + record ENCAPSULATED end ENCAPSULATED; + record NOT_ENCAPSULATED end NOT_ENCAPSULATED; + end Encapsulated; + + uniontype Partial + record PARTIAL end PARTIAL; + record NOT_PARTIAL end NOT_PARTIAL; + end Partial; + + uniontype ConnectorType + record POTENTIAL end POTENTIAL; + record FLOW end FLOW; + record STREAM end STREAM; + end ConnectorType; + + uniontype Prefixes + record PREFIXES + Visibility visibility; + Redeclare redeclarePrefix; + Final finalPrefix; + Absyn.InnerOuter innerOuter; + Replaceable replaceablePrefix; + end PREFIXES; + end Prefixes; + + uniontype Element + record IMPORT + Absyn.Import imp; + Visibility visibility; + SourceInfo info; + end IMPORT; + + record EXTENDS + Path baseClassPath; + Visibility visibility; + Mod modifications; + Option ann; + SourceInfo info; + end EXTENDS; + + record CLASS + Ident name; + Prefixes prefixes; + Encapsulated encapsulatedPrefix; + Partial partialPrefix; + Restriction restriction; + ClassDef classDef; + Comment cmt; + SourceInfo info; + end CLASS; + + record COMPONENT + Ident name; + Prefixes prefixes; + Attributes attributes; + Absyn.TypeSpec typeSpec; + Mod modifications; + Comment comment; + Option condition; + SourceInfo info; + end COMPONENT; + + record DEFINEUNIT + Ident name; + Visibility visibility; + Option exp; + Option weight; + end DEFINEUNIT; + + end Element; + + uniontype Attributes + record ATTR + Absyn.ArrayDim arrayDims; + ConnectorType connectorType; + Parallelism parallelism; + Variability variability; + Absyn.Direction direction; + end ATTR; + end Attributes; + + uniontype Parallelism + record PARGLOBAL end PARGLOBAL; + record PARLOCAL end PARLOCAL; + record NON_PARALLEL end NON_PARALLEL; + end Parallelism; + + uniontype Variability + record VAR end VAR; + record DISCRETE end DISCRETE; + record PARAM end PARAM; + record CONST end CONST; + end Variability; + + uniontype Initial + record INITIAL end INITIAL; + record NON_INITIAL end NON_INITIAL; + end Initial; +end SCode; + +package SCodeDump + uniontype SCodeDumpOptions + record OPTIONS + Boolean stripAlgorithmSections; + Boolean stripProtectedImports; + Boolean stripStringComments; + Boolean stripExternalDecl; + Boolean stripOutputBindings; + end OPTIONS; + end SCodeDumpOptions; + constant SCodeDumpOptions defaultOptions; + + function filterElements + input list element; + input SCodeDumpOptions options; + output list outElements; + end filterElements; + +end SCodeDump; + +package Tpl + function addTemplateError + input String inErrMsg; + end addTemplateError; + function addSourceTemplateError + "Wraps call to Error.addSourceMessage() funtion with Error.TEMPLATE_ERROR and one MessageToken." + input String inErrMsg; + input builtin.SourceInfo inInfo; + end addSourceTemplateError; +end Tpl; + +package System + function escapedString + input String unescapedString; + input Boolean unescapeNewline; + output String escapedString; + end escapedString; + function trimWhitespace + input String inString; + output String outString; + end trimWhitespace; + function stringReplace + input String str; + input String source; + input String target; + output String res; + end stringReplace; +end System; + +package Util + type StatefulBoolean = array; + function getStatefulBoolean + input StatefulBoolean sb; + output Boolean b; + end getStatefulBoolean; + function setStatefulBoolean + input StatefulBoolean sb; + input Boolean b; + end setStatefulBoolean; + function makeStatefulBoolean + input Boolean b; + output StatefulBoolean sb; + end makeStatefulBoolean; +end Util; + +package Error + function infoStr + input builtin.SourceInfo info; + output String str; + end infoStr; +end Error; + +package SCodeUtil + + function translateEquations + input list inAbsynEquationItemLst; + input Boolean inIsInitial; + output list outEquationLst; + end translateEquations; + + function translateClassdefAlgorithmitems + input list inStatements; + output list outStatements; + end translateClassdefAlgorithmitems; + + function translateEitemlist + input list inAbsynElementItemLst; + // input SCode.Visibility inVisibility = SCode.PUBLIC(); + output list outElementLst; + end translateEitemlist; + +end SCodeUtil; + +package MMToJuliaUtil + uniontype Context + record FUNCTION + end FUNCTION; + record PACKAGE + end PACKAGE; + record UNIONTYPE + String name; + end UNIONTYPE; + end Context; + constant Context packageContext; + constant Context functionContext; + function makeUniontypeContext + input String name; + output Context context; + end makeUniontypeContext; +end MMToJuliaUtil; + +end MMToJuliaTV; \ No newline at end of file diff --git a/OMCompiler/toJulia/Clean.jl b/OMCompiler/toJulia/Clean.jl new file mode 100644 index 00000000000..3a9d546c900 --- /dev/null +++ b/OMCompiler/toJulia/Clean.jl @@ -0,0 +1,9 @@ +using DocumentFormat + +f=ARGS[1] + +fin=open(f) +c=read(fin) +fixed=DocumentFormat.format(String(c)) +fout=open(f, "w") +write(fout,fixed) diff --git a/OMCompiler/toJulia/Graphviz.mos b/OMCompiler/toJulia/Graphviz.mos new file mode 100644 index 00000000000..fc714a74abb --- /dev/null +++ b/OMCompiler/toJulia/Graphviz.mos @@ -0,0 +1,5 @@ +setCommandLineOptions("-g=MetaModelica");getErrorString(); +loadFile("Compiler/FrontEnd/Graphviz.mo");getErrorString(); +writeFile("toJulia/Graphviz.jl", OpenModelica.Scripting.Experimental.toJulia());getErrorString(); +system("sed -i '/^ *$/d' toJulia/Graphviz.jl"); +system("julia-1.0.0 toJulia/Clean.jl toJulia/Graphviz.jl"); diff --git a/OMCompiler/toJulia/lex.jl b/OMCompiler/toJulia/lex.jl new file mode 100644 index 00000000000..857571a182a --- /dev/null +++ b/OMCompiler/toJulia/lex.jl @@ -0,0 +1,67 @@ +using Glob +import Automa + +function bytesToPositions(data) + data_raw = Vector{UInt8}(data) + p_end = p_eof = sizeof(data) + positions = Array{Int,2}(undef, p_end, 2) + p = pos = 1 + row = 1 + col = 1 + while pos ≤ p_eof + positions[pos,1:2] = [row,col] + col = col + 1 + inc = 1 + if data_raw[pos] == Int('\n') + col = 0 + row = row + 1 + elseif data_raw[pos] & 0x80 == 0x00 + # 1 byte + elseif data_raw[pos] & 0xe0 == 0xc0 + # 2 byte sequence + inc = 2 + elseif data_raw[pos] & 0xf0 == 0xe0 + # 3 byte sequence + inc = 3 + elseif data_raw[pos] & 0xf8 == 0xf0 + # 4 byte sequence + inc = 4 + else + # Invalid + throw(LexerError("Could not parse UTF-8 String, but Julia says the String is UTF-8...")) + end + pos = pos + inc + end + positions +end + +include("tokens.jl") +include("generated_lexer.jl") + +function scanMSL() + for f in glob("../build/lib/omlibrary/Modelica 3.2.3/**/*.mo") + tokens = tokenize(f) + end +end + +# using Profile + +println("Serial MSL lexer") +scanMSL() +# Profile.clear_malloc_data() +scanMSL() +exit(0) +#@time scanMSL() + +function scanMSLParallel() + files = glob("../build/lib/omlibrary/Modelica 3.2.3/**/*.mo") + Threads.@threads for i = 1:length(files) + tokenize(files[i]) + end +end + +# Start with env.var: JULIA_NUM_THREADS=4 +println("Parallel MSL lexer") +@time scanMSLParallel() +#@time scanMSLParallel() +#@time scanMSLParallel() diff --git a/OMCompiler/toJulia/lexer.jl b/OMCompiler/toJulia/lexer.jl new file mode 100644 index 00000000000..70d5715b1e3 --- /dev/null +++ b/OMCompiler/toJulia/lexer.jl @@ -0,0 +1,94 @@ +# Generate a Lexer for (Meta)Modelica +# ===================================================================== + +import Automa +import Automa.RegExp: @re_str +import MacroTools +const re = Automa.RegExp + +include("tokens.jl") + +keywordWithAction = [ + Automa.RegExp.parse(word) => :(emit($(Symbol(uppercase(word[1]) * word[2:end]))())) for word in keywords +] +# Describe patterns in regular expression. +string = re"\"([^\"\\x5c]|(\\x5c['\"?\\x5cabfnrtv]))*\"" +ident = re"[_A-Za-z][_A-Za-z0-9]*|'([^'\\x5c]|(\\x5c.))+'" +int = re"[0-9]+" +prefloat = re"[0-9]+\.[0-9]*|[0-9]*\.[0-9]+" +float = prefloat | re.cat(prefloat | re"[-+]?[0-9]+", re"[eE][-+]?[0-9]+") +operator = re"[{}(),]|end" +number = int | float +ws = re"[ ]+" +omtoken = number | string | ident | operator +omtokens = re.opt(ws) * re.rep(omtoken * re.opt(ws)) + +# Compile a finite-state machine. +res = vcat(keywordWithAction, [ + re"=" => :(emit(Equality())), + re":=" => :(emit(Assign())), + re";" => :(emit(Semicolon())), + re"," => :(emit(Comma())), + re"\[" => :(emit(LeftBracket())), + re"\]" => :(emit(RightBracket())), + re"[(]" => :(emit(LeftPar())), + re"[)]" => :(emit(RightPar())), + re"{" => :(emit(LeftCurly())), + re"}" => :(emit(RightCurly())), + re"^" => :(emit(Exponent())), + re"[.]" => :(emit(Dot())), + re"[*]" => :(emit(Product())), + re"/" => :(emit(Division())), + re"[.][*]" => :(emit(Product_EW())), + re"[.]/" => :(emit(Division_EW())), + re"[+]" => :(emit(Plus())), + re"[-]" => :(emit(Minus())), + re"[.][+]" => :(emit(Plus_EW())), + re"[.][-]" => :(emit(Minus_EW())), + re"<" => :(emit(Less())), + re"<=" => :(emit(LessEq())), + re">" => :(emit(Greater())), + re">=" => :(emit(GreaterEq())), + re"==" => :(emit(Equals())), + re"<>" => :(emit(NotEquals())), + re":" => :(emit(Colon())), + string => :(emit(StringToken(unescape_string(String(data[ts+1:te-1]))))), + ident => :(emit(Identifier(unescape_string(String(data[ts:te]))))), # Should this be a symbol instead? + int => :(emit(IntToken(parse(Int, String(data[ts:te]))))), + float => :(emit(RealToken(String(data[ts:te]), parse(Float64, String(data[ts:te]))))), + re"[\n\t ]" => :(), + re"//[^\n]*[\n]" => :(emit(LineComment(String(data[ts+1:te-1])))), + re"/[*]([^*]|[*][^/])*[*][/]" => :(emit(BlockComment(String(data[ts+1:te-1])))), + re"." => :(for tok = tokens println(tok) end; throw(LexerError(filename,positions[ts][1],positions[ts][2],"Error lexing near: “$(data[ts:p + min(p_eof-p, 20)])”"))), + ]) +tokenizer = Automa.compile(res...) + +# Generate a tokenizing function from the machine. +ctx = Automa.CodeGenContext() +init_code = MacroTools.prettify(Automa.generate_init_code(ctx, tokenizer)) +exec_code = MacroTools.prettify(Automa.generate_exec_code(ctx, tokenizer)) + +write(open("toJulia/generated_lexer.jl","w"), """ +function tokenize(filename) + $(init_code) + data = read(open(filename), String) + data_raw = Vector{UInt8}(data) + p_end = p_eof = sizeof(data) + positions = bytesToPositions(data) + failed = false + tokens = Token[] + makeInfo(p) = FileInfo(0, p) + emit(tok::Token) = push!(tokens, tok) + emit(tok::Any) = throw(LexerError("Error while lexing. Got non-token \$(tok)")) + while p ≤ p_eof && cs > 0 + $(exec_code) + end + if cs < 0 || failed + throw(LexerError("Error while lexing")) + end + if p < p_eof + throw(LexerError("Did not scan until end of file. Remaining: \$(data[p:p_eof])")) + end + return tokens +end +""") diff --git a/OMCompiler/toJulia/toJulia.jl b/OMCompiler/toJulia/toJulia.jl new file mode 100644 index 00000000000..204c3b7b8f3 --- /dev/null +++ b/OMCompiler/toJulia/toJulia.jl @@ -0,0 +1,45 @@ +using OMJulia: OMCSession, sendExpression + +JIT_STACK_START_SIZE = 32768 +JIT_STACK_MAX_SIZE = 1048576 +Base.PCRE.JIT_STACK[] = ccall((:pcre2_jit_stack_create_8, Base.PCRE.PCRE_LIB), Ptr{Cvoid}, + (Cint, Cint, Ptr{Cvoid}), + JIT_STACK_START_SIZE, JIT_STACK_MAX_SIZE, C_NULL) +ccall((:pcre2_jit_stack_assign_8, Base.PCRE.PCRE_LIB), Cvoid, + (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}), Base.PCRE.MATCH_CONTEXT[], C_NULL, Base.PCRE.JIT_STACK[]) + + +function main() + omc=OMCSession() + sendExpression(omc, "setCommandLineOptions(\"-g=MetaModelica\")") + files = [ + "FrontEnd/Absyn.mo", + "FrontEnd/AbsynUtil.mo", + "FrontEnd/Graphviz.mo" + ] + for file in files + print(file) + base = Base.Filesystem.basename(file) + sendExpression(omc, "clear()") + @assert sendExpression(omc, "loadFile(\"Compiler/$file\")") + try + x = sendExpression(omc, "OpenModelica.Scripting.Experimental.toJulia()") + write(open("toJulia/$(base[1:end-3]).jl", "w"),x) + println(x) + catch e + bt = backtrace() + msg = sprint(showerror, e, bt) + println(msg) + println(sendExpression(omc, "getErrorString()")) + return nothing + end + println(" OK") + end + all = open("toJulia/all.jl", "w") + for file in files + base = Base.Filesystem.basename(file) + write(all, "include(\"$(base[1:end-3]).jl\")") + end +end + +main() diff --git a/OMCompiler/toJulia/tokens.jl b/OMCompiler/toJulia/tokens.jl new file mode 100644 index 00000000000..6c856ccc599 --- /dev/null +++ b/OMCompiler/toJulia/tokens.jl @@ -0,0 +1,92 @@ +abstract type Token end +struct FileInfo + line::Int + column::Int +end + +struct IntToken <: Token + value::Int +end +struct RealToken <: Token + original::String + value::Real +end +struct StringToken <: Token + value::String +end +struct Identifier <: Token + value::String +end +# Operators +struct Comma <: Token end +struct Semicolon <: Token end +struct Assign <: Token end +struct Equality <: Token end +struct LeftBracket <: Token end +struct RightBracket <: Token end +struct LeftPar <: Token end +struct RightPar <: Token end +struct LeftCurly <: Token end +struct RightCurly <: Token end +struct Exponent <: Token end +struct Product <: Token end +struct Division <: Token end +struct Product_EW <: Token end +struct Division_EW <: Token end +struct Plus <: Token end +struct Minus <: Token end +struct Plus_EW <: Token end +struct Minus_EW <: Token end +struct Less <: Token end +struct LessEq <: Token end +struct Greater <: Token end +struct GreaterEq <: Token end +struct Equals <: Token end +struct NotEquals <: Token end +struct Dot <: Token end +struct Colon <: Token end +struct LineComment <: Token + comment::String +end +struct BlockComment <: Token + comment::String +end +struct LexerError <: Exception + filename::String + row::Int + col::Int + message::String +end + +# Keywords +macro keywords(words...) + res = quote + begin + end + end + for word in words + res = quote + $(res) + struct $(Symbol(uppercase(word[1]) * word[2:end])) <: Token + end + end + end + res = quote + $(res) + $(esc(words)) + end + res +end +keywords = @keywords( + "algorithm", "and", "algorithm", "and", "annotation", + "block", "break", + "class", "connect", "connector", "constant", "constrainedby", + "der", "discrete", + "each", "else", "elseif", "elsewhen", "encapsulated", "end", "enumeration", "equation", "enumeration", "expandable", "extends", "external", + "false", "final", "flow", "for", "function", + "if", "import", "impure", "in", "initial", "inner", "input", + "loop", "model", "not", "operator", "or", "outer", "output", + "package", "parameter", "partial", "protected", "public", "pure", + "record", "redeclare", "replaceable", "return", + "stream", "then", "true", "type", "when", "while", "within" +)