[
  {
    "path": ".github/workflows/build-and-test.yml",
    "content": "name: Build and Test\non: [push, pull_request]\njobs:\n  Build-and-Test:\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v3\n      with:\n        submodules: true\n    - name: Setup .NET\n      uses: actions/setup-dotnet@v2\n      with:\n        dotnet-version: 6.0.x\n    - name: Install dependencies of Python\n      run: pip3 install -r testcases/requirements.txt\n    - name: Build\n      run: dotnet build -c Release\n    - name: Test\n      run: python3 testcases/test.py\n    - name: Fetch the score\n      # We've saved the score into `.score` file, from which we fetch the score again.\n      id: score\n      # We follow the palette of OJ (http://codeforces.com/problemset/status)\n      # The badge is green if the score is full, blue otherwise.\n      run: |\n        echo \"##[set-output name=data;]$(cat .score)\"\n        echo \"##[set-output name=color;]$(score=$(cat .score) && [[ $score == '100.0' ]] && echo '0A0' || echo '00A')\"\n    - name: Score badge\n      uses: RubbaBoy/BYOB@v1.3.0\n      with:\n        NAME: score\n        LABEL: 'score'\n        STATUS: ${{ steps.score.outputs.data }}\n        COLOR: ${{ steps.score.outputs.color }}\n        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n\n# User-specific files\n*.rsuser\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# User-specific files (MonoDevelop/Xamarin Studio)\n*.userprefs\n\n# Mono auto generated files\nmono_crash.*\n\n# Build results\n[Dd]ebug/\n[Dd]ebugPublic/\n[Rr]elease/\n[Rr]eleases/\nx64/\nx86/\n[Ww][Ii][Nn]32/\n[Aa][Rr][Mm]/\n[Aa][Rr][Mm]64/\nbld/\n[Bb]in/\n[Oo]bj/\n[Ll]og/\n[Ll]ogs/\n\n# Visual Studio 2015/2017 cache/options directory\n.vs/\n# Uncomment if you have tasks that create the project's static files in wwwroot\n#wwwroot/\n\n# Visual Studio 2017 auto generated files\nGenerated\\ Files/\n\n# MSTest test Results\n[Tt]est[Rr]esult*/\n[Bb]uild[Ll]og.*\n\n# NUnit\n*.VisualState.xml\nTestResult.xml\nnunit-*.xml\n\n# Build Results of an ATL Project\n[Dd]ebugPS/\n[Rr]eleasePS/\ndlldata.c\n\n# Benchmark Results\nBenchmarkDotNet.Artifacts/\n\n# .NET Core\nproject.lock.json\nproject.fragment.lock.json\nartifacts/\n\n# ASP.NET Scaffolding\nScaffoldingReadMe.txt\n\n# StyleCop\nStyleCopReport.xml\n\n# Files built by Visual Studio\n*_i.c\n*_p.c\n*_h.h\n*.ilk\n*.meta\n*.obj\n*.iobj\n*.pch\n*.pdb\n*.ipdb\n*.pgc\n*.pgd\n*.rsp\n*.sbr\n*.tlb\n*.tli\n*.tlh\n*.tmp\n*.tmp_proj\n*_wpftmp.csproj\n*.log\n*.vspscc\n*.vssscc\n.builds\n*.pidb\n*.svclog\n*.scc\n\n# Chutzpah Test files\n_Chutzpah*\n\n# Visual C++ cache files\nipch/\n*.aps\n*.ncb\n*.opendb\n*.opensdf\n*.sdf\n*.cachefile\n*.VC.db\n*.VC.VC.opendb\n\n# Visual Studio profiler\n*.psess\n*.vsp\n*.vspx\n*.sap\n\n# Visual Studio Trace Files\n*.e2e\n\n# TFS 2012 Local Workspace\n$tf/\n\n# Guidance Automation Toolkit\n*.gpState\n\n# ReSharper is a .NET coding add-in\n_ReSharper*/\n*.[Rr]e[Ss]harper\n*.DotSettings.user\n\n# TeamCity is a build add-in\n_TeamCity*\n\n# DotCover is a Code Coverage Tool\n*.dotCover\n\n# AxoCover is a Code Coverage Tool\n.axoCover/*\n!.axoCover/settings.json\n\n# Coverlet is a free, cross platform Code Coverage Tool\ncoverage*.json\ncoverage*.xml\ncoverage*.info\n\n# Visual Studio code coverage results\n*.coverage\n*.coveragexml\n\n# NCrunch\n_NCrunch_*\n.*crunch*.local.xml\nnCrunchTemp_*\n\n# MightyMoose\n*.mm.*\nAutoTest.Net/\n\n# Web workbench (sass)\n.sass-cache/\n\n# Installshield output folder\n[Ee]xpress/\n\n# DocProject is a documentation generator add-in\nDocProject/buildhelp/\nDocProject/Help/*.HxT\nDocProject/Help/*.HxC\nDocProject/Help/*.hhc\nDocProject/Help/*.hhk\nDocProject/Help/*.hhp\nDocProject/Help/Html2\nDocProject/Help/html\n\n# Click-Once directory\npublish/\n\n# Publish Web Output\n*.[Pp]ublish.xml\n*.azurePubxml\n# Note: Comment the next line if you want to checkin your web deploy settings,\n# but database connection strings (with potential passwords) will be unencrypted\n*.pubxml\n*.publishproj\n\n# Microsoft Azure Web App publish settings. Comment the next line if you want to\n# checkin your Azure Web App publish settings, but sensitive information contained\n# in these scripts will be unencrypted\nPublishScripts/\n\n# NuGet Packages\n*.nupkg\n# NuGet Symbol Packages\n*.snupkg\n# The packages folder can be ignored because of Package Restore\n**/[Pp]ackages/*\n# except build/, which is used as an MSBuild target.\n!**/[Pp]ackages/build/\n# Uncomment if necessary however generally it will be regenerated when needed\n#!**/[Pp]ackages/repositories.config\n# NuGet v3's project.json files produces more ignorable files\n*.nuget.props\n*.nuget.targets\n\n# Microsoft Azure Build Output\ncsx/\n*.build.csdef\n\n# Microsoft Azure Emulator\necf/\nrcf/\n\n# Windows Store app package directories and files\nAppPackages/\nBundleArtifacts/\nPackage.StoreAssociation.xml\n_pkginfo.txt\n*.appx\n*.appxbundle\n*.appxupload\n\n# Visual Studio cache files\n# files ending in .cache can be ignored\n*.[Cc]ache\n# but keep track of directories ending in .cache\n!?*.[Cc]ache/\n\n# Others\nClientBin/\n~$*\n*~\n*.dbmdl\n*.dbproj.schemaview\n*.jfm\n*.pfx\n*.publishsettings\norleans.codegen.cs\n\n# Including strong name files can present a security risk\n# (https://github.com/github/gitignore/pull/2483#issue-259490424)\n#*.snk\n\n# Since there are multiple workflows, uncomment next line to ignore bower_components\n# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)\n#bower_components/\n\n# RIA/Silverlight projects\nGenerated_Code/\n\n# Backup & report files from converting an old project file\n# to a newer Visual Studio version. Backup files are not needed,\n# because we have git ;-)\n_UpgradeReport_Files/\nBackup*/\nUpgradeLog*.XML\nUpgradeLog*.htm\nServiceFabricBackup/\n*.rptproj.bak\n\n# SQL Server files\n*.mdf\n*.ldf\n*.ndf\n\n# Business Intelligence projects\n*.rdl.data\n*.bim.layout\n*.bim_*.settings\n*.rptproj.rsuser\n*- [Bb]ackup.rdl\n*- [Bb]ackup ([0-9]).rdl\n*- [Bb]ackup ([0-9][0-9]).rdl\n\n# Microsoft Fakes\nFakesAssemblies/\n\n# GhostDoc plugin setting file\n*.GhostDoc.xml\n\n# Node.js Tools for Visual Studio\n.ntvs_analysis.dat\nnode_modules/\n\n# Visual Studio 6 build log\n*.plg\n\n# Visual Studio 6 workspace options file\n*.opt\n\n# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)\n*.vbw\n\n# Visual Studio LightSwitch build output\n**/*.HTMLClient/GeneratedArtifacts\n**/*.DesktopClient/GeneratedArtifacts\n**/*.DesktopClient/ModelManifest.xml\n**/*.Server/GeneratedArtifacts\n**/*.Server/ModelManifest.xml\n_Pvt_Extensions\n\n# Paket dependency manager\n.paket/paket.exe\npaket-files/\n\n# FAKE - F# Make\n.fake/\n\n# CodeRush personal settings\n.cr/personal\n\n# Python Tools for Visual Studio (PTVS)\n__pycache__/\n*.pyc\n\n# Cake - Uncomment if you are using it\n# tools/**\n# !tools/packages.config\n\n# Tabs Studio\n*.tss\n\n# Telerik's JustMock configuration file\n*.jmconfig\n\n# BizTalk build output\n*.btp.cs\n*.btm.cs\n*.odx.cs\n*.xsd.cs\n\n# OpenCover UI analysis results\nOpenCover/\n\n# Azure Stream Analytics local run output\nASALocalRun/\n\n# MSBuild Binary and Structured Log\n*.binlog\n\n# NVidia Nsight GPU debugger configuration file\n*.nvuser\n\n# MFractors (Xamarin productivity tool) working folder\n.mfractor/\n\n# Local History for Visual Studio\n.localhistory/\n\n# BeatPulse healthcheck temp database\nhealthchecksdb\n\n# Backup folder for Package Reference Convert tool in Visual Studio 2017\nMigrationBackup/\n\n# Ionide (cross platform F# VS Code tools) working folder\n.ionide/\n\n# Fody - auto-generated XML schema\nFodyWeavers.xsd\n\n# ANTLR VSCode extension temporary generated files\n*.antlr/\n\n# Pi programs for test\n*.pi\n\n# project settings for VS Code\n.vscode/\n\nProperties/\n\n# Binary of C++\n*.out\n\n# The score of CMinor verifier\n.score\n"
  },
  {
    "path": ".gitlab-ci.yml",
    "content": "image: autojudger22\ncache:\n  key: \"$CI_COMMIT_SHA\"\n  paths:\n    - bin/\n    - testcases/\n\nstages:\n  - build\n  - prepare_data\n  - test\n\nbuild:\n  stage: build\n  script:\n    - if [ -d 'bin' ]; then rm -r bin; fi\n    - echo \"Build starts...\"\n    - dotnet build -c Release\n    - echo \"Build finished.\"\n\n\nprepare_data:\n  stage: prepare_data\n  script:\n    - echo \"Test starts...\"\n    - echo \"Getting the latest test cases...\"\n    - if [ -d 'testcases' ]; then rm -r testcases; fi\n    - git clone https://autojudger22:x7jLHuVeyDancsF46kXQ@git.tsinghua.edu.cn/software-verification-22/cminor-testcases.git\n    - mv cminor-testcases testcases\n    - ls testcases\n    - echo \"Latest test cases got.\"\n\ntest:\n  stage: test\n  script:\n    - echo \"Running the tests...\"\n    - ls testcases\n    - python3.8 testcases/test.py\n    - echo \"Test finished.\"\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"testcases\"]\n\tpath = testcases\n\turl = git@github.com:thufv/CMinor-testcases.git\n\tbranch = master\n"
  },
  {
    "path": "CMinorLexer.g4",
    "content": "/*\n * This lexer grammar only targets C#.\n */\n\nlexer grammar CMinorLexer;\n\n@header {#pragma warning disable 3021}\n\n@preinclude {\n    using Antlr4.Runtime;\n}\n\n@members {\n  bool inAnnot = false;\n  bool inLineAnnot = false;\n}\n\n/* --- literals --- */\nVOID: 'void';\nSTRUCT: 'struct';\n\nLPAR: '(';\nRPAR: ')';\nLBRACE: '{';\nRBRACE: '}';\nCOMMA: ',';\nSEMICOLON: ';';\nLBRACKET: '[';\nRBRACKET: ']';\nPERIOD: '.';\n\nINT: 'int';\nFLOAT: 'float';\nBOOL: 'bool';\n\nIF: 'if';\nELSE: 'else';\nBREAK: 'break';\nCONTINUE: 'continue';\nRETURN: 'return';\nWHILE: 'while';\nDO: 'do';\nFOR: 'for';\n\nASSIGN: '=';\n\nEQ: '==';\nNE: '!=';\nLE: '<=';\nLT: '<';\nGE: '>=';\nGT: '>';\nADD: '+';\nMINUS: '-';\nMUL: '*';\nDIV: '/';\nNEG: '!';\nMOD: '%';\nAND: '&&';\nOR: '||';\nEXPR_TRUE: 'true';\nEXPR_FALSE: 'false';\n\nANNO_TRUE: '\\\\true';\nANNO_FALSE: '\\\\false';\nRESULT: '\\\\result';\nLENGTH: '\\\\length';\nOLD: '\\\\old';\nWITH: '\\\\with';\nIMPLY: '==>';\nEQUIV: '<==>';\nXOR: '^^';\nFORALL: '\\\\forall';\nEXISTS: '\\\\exists';\nBOOLEAN: 'boolean';\nINTEGER: 'integer';\nREAL: 'real';\nREQUIRES: 'requires';\nDECREASES: 'decreases';\nENSURES: 'ensures';\nASSERT: 'assert';\nLOOP: 'loop';\nINVARIANT: 'invariant';\nVARIANT: 'variant';\nPREDICATE: 'predicate';\nVALID: '\\\\valid';\nAPOSTROPHE: '..';\n\n/* --- constants --- */\nINT_CONSTANT: [0-9]+;\nFLOAT_CONSTANT: [0-9]+ '.' [0-9]+;\nIDENT: [a-zA-Z] [a-zA-Z0-9_]*;\n\n/* --- comments --- */\nCOMMENT: '/*' ('*/' | ~('@') .*? '*/') -> skip;\nLINE_COMMENT: '//' ([\\r\\n] | ~('@') ~[\\r\\n]*) -> skip;\n\n/* --- annotationss --- */\nANNOT_START: '/*@' { inAnnot = true; };\nANNOT_END: '*/' { inAnnot = false; };\nLINE_ANNOT_START: '//@' { inLineAnnot = true; };\n\n/* --- '@' is skipped in annotation --- */\nAT: '@' { if (inAnnot || inLineAnnot) Skip(); };\n\n/* --- LINEEND cannot be skipped for line annotation --- */\nLINEEND: [\\r\\n] {\n    if (inLineAnnot) inLineAnnot = false;\n    else Skip();\n};\n\n/* --- skip white spaces --- */\nWS: [ \\t\\u000C] -> skip;\n"
  },
  {
    "path": "CMinorParser.g4",
    "content": "/*\n * compatible with ACSL language grammar v1.17\n */\n\nparser grammar CMinorParser;\n\noptions {\n\ttokenVocab = CMinorLexer;\n}\n\n@header {#pragma warning disable 3021}\n\n/* top level */\nmain: def* EOF;\n\ndef: funcDef | structDef | predDefs;\n\nfuncDef:\n\tfuncContract retVar '(' (paraVar (',' paraVar)*)? ')' '{' (\n\t\tdecl\n\t\t| stmt\n\t)* '}';\n\nstructDef: 'struct' IDENT '{' (atomicType IDENT ';')* '}' ';';\n\n/* variable */\nlocalVar:\n\tatomicType IDENT\n\t| 'struct' IDENT IDENT\n\t| atomicType IDENT '[' INT_CONSTANT ']';\n\nparaVar:\n\tatomicType IDENT\n\t| 'struct' IDENT IDENT\n\t| atomicType IDENT '[' ']';\n\nretVar:\n\tatomicType IDENT\n\t| 'struct' IDENT IDENT\n\t| 'void' IDENT;\n\natomicType: 'int' | 'float';\n\nlogicParaVar:\n\tlogicAtomicType IDENT\n\t| 'struct' IDENT IDENT\n\t| logicAtomicType '[' ']' IDENT;\n\nlogicAtomicType: 'integer' | 'real' | 'boolean';\n\n/* about statement */\nstmt:\n\t';'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# EmptyStmt\n\t| expr ';'\t\t\t\t\t\t\t\t\t\t\t\t\t\t# ExprStmt\n\t| assign ';'\t\t\t\t\t\t\t\t\t\t\t\t\t# AssignStmt\n\t| 'if' '(' expr ')' stmt ('else' stmt)?\t\t\t\t\t\t\t# IfStmt\n\t| loopAnnot 'while' '(' expr ')' stmt\t\t\t\t\t\t\t# WhileStmt\n\t| loopAnnot 'do' stmt 'while' '(' expr ')'\t\t\t\t\t\t# DoStmt\n\t| loopAnnot 'for' '(' forInit? ';' expr? ';' forIter? ')' stmt\t# ForStmt\n\t| 'break' ';'\t\t\t\t\t\t\t\t\t\t\t\t\t# BreakStmt\n\t| 'continue' ';'\t\t\t\t\t\t\t\t\t\t\t\t# ContStmt\n\t| 'return' expr? ';'\t\t\t\t\t\t\t\t\t\t\t# ReturnStmt\n\t| assertion\t\t\t\t\t\t\t\t\t\t\t\t\t\t# AssertStmt\n\t| '{' (stmt | decl)* '}'\t\t\t\t\t\t\t\t\t\t# BlockStmt;\n\nforInit: localVar ('=' expr)? | assign;\n\nforIter: assign | expr;\n\nassign:\n\tIDENT '=' expr\t\t\t\t\t# VarAssign\n\t| IDENT '[' expr ']' '=' expr\t# SubAssign\n\t| IDENT '.' IDENT '=' expr\t\t# MemAssign;\n\ndecl: localVar ('=' expr)? ';';\n\n/* about expression */\nexpr:\n\tIDENT\t\t\t\t\t\t\t\t\t# IdentExpr\n\t| constant\t\t\t\t\t\t\t\t# ConstExpr\n\t| IDENT '(' (expr (',' expr)*)? ')'\t\t# CallExpr\n\t| '(' expr ')'\t\t\t\t\t\t\t# ParExpr\n\t| expr '[' expr ']'\t\t\t\t\t\t# ArrAccessExpr\n\t| expr '.' IDENT\t\t\t\t\t\t# MemExpr\n\t| ('!' | '-') expr\t\t\t\t\t\t# UnaryExpr\n\t| expr ('*' | '/' | '%') expr\t\t\t# MulExpr\n\t| expr ('+' | '-') expr\t\t\t\t\t# AddExpr\n\t| expr ('<' | '<=' | '>' | '>=') expr\t# OrdExpr\n\t| expr ('==' | '!=') expr\t\t\t\t# EquExpr\n\t| expr '&&' expr\t\t\t\t\t\t# AndExpr\n\t| expr '||' expr\t\t\t\t\t\t# OrExpr;\n\n/* annotation */\nlogicConstant:\n\tINT_CONSTANT\n\t| FLOAT_CONSTANT\n\t| '\\\\true'\n\t| '\\\\false';\n\narithTerm:\n\tIDENT\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# IdentTerm\n\t| '\\\\result'\t\t\t\t\t\t\t\t\t\t\t\t\t# ResTerm\n\t| logicConstant\t\t\t\t\t\t\t\t\t\t\t\t\t# ConstTerm\n\t| '{' arithTerm '\\\\with' '[' arithTerm ']' '=' arithTerm '}'\t# ArrUpdTerm\n\t| '(' arithTerm ')'\t\t\t\t\t\t\t\t\t\t\t\t# ParArithTerm\n\t| arithTerm '[' arithTerm ']'\t\t\t\t\t\t\t\t\t# ArrAccessTerm\n\t| arithTerm '.' IDENT\t\t\t\t\t\t\t\t\t\t\t# MemTerm\n\t| ('-' | '!') arithTerm\t\t\t\t\t\t\t\t\t\t\t# UnaryTerm\n\t| arithTerm ('*' | '/' | '%') arithTerm\t\t\t\t\t\t\t# MulTerm\n\t| arithTerm ('+' | '-') arithTerm\t\t\t\t\t\t\t\t# AddTerm;\n\nterm:\n\tarithTerm\t\t\t\t\t\t\t\t# AriTerm\n\t| '(' term ')'\t\t\t\t\t\t\t# ParTerm\n\t| term ('<' | '<=' | '>' | '>=') term\t# OrdTerm\n\t| term ('==' | '!=') term\t\t\t\t# EquTerm\n\t| term '&&' term\t\t\t\t\t\t# AndTerm\n\t| term '||' term\t\t\t\t\t\t# OrTerm;\n\npred:\n\t'\\\\true'\t# TruePred\n\t| '\\\\false'\t# FalsePred\n\t| arithTerm (\n\t\t('<' | '<=' | '>' | '>=' | '==' | '!=') arithTerm\n\t)+\t\t\t\t\t\t\t\t\t# CmpPred\n\t| IDENT ('(' term (',' term)* ')')?\t# CallPred\n\t| '(' pred ')'\t\t\t\t\t\t# ParPred\n\t| pred '&&' pred\t\t\t\t\t# ConPred\n\t| pred '||' pred\t\t\t\t\t# DisPred\n\t| pred '==>' pred\t\t\t\t\t# ImpPred\n\t| pred '<==>' pred\t\t\t\t\t# IffPred\n\t| '!' pred\t\t\t\t\t\t\t# NegPred\n\t| pred '^^' pred\t\t\t\t\t# XorPred\n\t// 这里化简了 ACSL 中 location 和 tset 的概念 range 是个闭区间，其首尾的类型都只能是 integer\n\t| '\\\\valid' '(' IDENT '+' '(' INT_CONSTANT '..' arithTerm ')' ')'\t# LengthPred\n\t| ('\\\\forall' | '\\\\exists') binder (',' binder)* ';' pred\t\t\t# QuantiPred;\n\nbinder: logicAtomicType IDENT (',' IDENT)*;\n\nfuncContract:\n\t'/*@' requiresClause* decreasesClause? ensuresClause* '*/'\n\t| '//@' requiresClause* decreasesClause? ensuresClause* LINEEND;\n\nrequiresClause: 'requires' pred ';';\n\ndecreasesClause:\n\t'decreases' (arithTerm | '(' arithTerm (',' arithTerm)+ ')') ';';\n\nensuresClause: 'ensures' pred ';';\n\nassertion:\n\t'/*@' 'assert' pred ';' '*/'\n\t| '//@' 'assert' pred ';' LINEEND;\n\nloopAnnot:\n\t'/*@' ('loop' 'invariant' pred ';')* (\n\t\t'loop' 'variant' (arithTerm | '(' arithTerm (',' arithTerm)+ ')') ';'\n\t)? '*/'\n\t| '//@' ('loop' 'invariant' pred ';')* (\n\t\t'loop' 'variant' (arithTerm | '(' arithTerm (',' arithTerm)+ ')') ';'\n\t)? LINEEND;\n\npredDefs:\n\t'/*@' predDef* '*/'\n\t| '//@' predDef* LINEEND;\n\npredDef:\n\t'predicate' IDENT (\n\t\t'(' logicParaVar (',' logicParaVar)* ')'\n\t)? '=' pred ';';\n\n/* miscellaneous */\nconstant: INT_CONSTANT | FLOAT_CONSTANT | 'true' | 'false';\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "Doxyfile",
    "content": "# Doxyfile 1.9.3\n\n# This file describes the settings to be used by the documentation system\n# doxygen (www.doxygen.org) for a project.\n#\n# All text after a double hash (##) is considered a comment and is placed in\n# front of the TAG it is preceding.\n#\n# All text after a single hash (#) is considered a comment and will be ignored.\n# The format is:\n# TAG = value [value, ...]\n# For lists, items can also be appended using:\n# TAG += value [value, ...]\n# Values that contain spaces should be placed between quotes (\\\" \\\").\n\n#---------------------------------------------------------------------------\n# Project related configuration options\n#---------------------------------------------------------------------------\n\n# This tag specifies the encoding used for all characters in the configuration\n# file that follow. The default is UTF-8 which is also the encoding used for all\n# text before the first occurrence of this tag. Doxygen uses libiconv (or the\n# iconv built into libc) for the transcoding. See\n# https://www.gnu.org/software/libiconv/ for the list of possible encodings.\n# The default value is: UTF-8.\n\nDOXYFILE_ENCODING      = UTF-8\n\n# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by\n# double-quotes, unless you are using Doxywizard) that should identify the\n# project for which the documentation is generated. This name is used in the\n# title of most generated pages and in a few other places.\n# The default value is: My Project.\n\nPROJECT_NAME           = \"CMinor\"\n\n# The PROJECT_NUMBER tag can be used to enter a project or revision number. This\n# could be handy for archiving the generated documentation or if some version\n# control system is used.\n\nPROJECT_NUMBER         =\n\n# Using the PROJECT_BRIEF tag one can provide an optional one line description\n# for a project that appears at the top of each page and should give viewer a\n# quick idea about the purpose of the project. Keep the description short.\n\nPROJECT_BRIEF          =\n\n# With the PROJECT_LOGO tag one can specify a logo or an icon that is included\n# in the documentation. The maximum height of the logo should not exceed 55\n# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy\n# the logo to the output directory.\n\nPROJECT_LOGO           =\n\n# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path\n# into which the generated documentation will be written. If a relative path is\n# entered, it will be relative to the location where doxygen was started. If\n# left blank the current directory will be used.\n\nOUTPUT_DIRECTORY       =\n\n# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-\n# directories (in 2 levels) under the output directory of each output format and\n# will distribute the generated files over these directories. Enabling this\n# option can be useful when feeding doxygen a huge amount of source files, where\n# putting all generated files in the same directory would otherwise causes\n# performance problems for the file system.\n# The default value is: NO.\n\nCREATE_SUBDIRS         = NO\n\n# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII\n# characters to appear in the names of generated files. If set to NO, non-ASCII\n# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode\n# U+3044.\n# The default value is: NO.\n\nALLOW_UNICODE_NAMES    = NO\n\n# The OUTPUT_LANGUAGE tag is used to specify the language in which all\n# documentation generated by doxygen is written. Doxygen will use this\n# information to generate all constant output in the proper language.\n# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,\n# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),\n# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,\n# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),\n# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,\n# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,\n# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,\n# Ukrainian and Vietnamese.\n# The default value is: English.\n\nOUTPUT_LANGUAGE        = Chinese\n\n# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member\n# descriptions after the members that are listed in the file and class\n# documentation (similar to Javadoc). Set to NO to disable this.\n# The default value is: YES.\n\nBRIEF_MEMBER_DESC      = YES\n\n# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief\n# description of a member or function before the detailed description\n#\n# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the\n# brief descriptions will be completely suppressed.\n# The default value is: YES.\n\nREPEAT_BRIEF           = YES\n\n# This tag implements a quasi-intelligent brief description abbreviator that is\n# used to form the text in various listings. Each string in this list, if found\n# as the leading text of the brief description, will be stripped from the text\n# and the result, after processing the whole list, is used as the annotated\n# text. Otherwise, the brief description is used as-is. If left blank, the\n# following values are used ($name is automatically replaced with the name of\n# the entity):The $name class, The $name widget, The $name file, is, provides,\n# specifies, contains, represents, a, an and the.\n\nABBREVIATE_BRIEF       = \"The $name class\" \\\n                         \"The $name widget\" \\\n                         \"The $name file\" \\\n                         is \\\n                         provides \\\n                         specifies \\\n                         contains \\\n                         represents \\\n                         a \\\n                         an \\\n                         the\n\n# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then\n# doxygen will generate a detailed section even if there is only a brief\n# description.\n# The default value is: NO.\n\nALWAYS_DETAILED_SEC    = NO\n\n# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all\n# inherited members of a class in the documentation of that class as if those\n# members were ordinary class members. Constructors, destructors and assignment\n# operators of the base classes will not be shown.\n# The default value is: NO.\n\nINLINE_INHERITED_MEMB  = NO\n\n# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path\n# before files name in the file list and in the header files. If set to NO the\n# shortest path that makes the file name unique will be used\n# The default value is: YES.\n\nFULL_PATH_NAMES        = YES\n\n# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.\n# Stripping is only done if one of the specified strings matches the left-hand\n# part of the path. The tag can be used to show relative paths in the file list.\n# If left blank the directory from which doxygen is run is used as the path to\n# strip.\n#\n# Note that you can specify absolute paths here, but also relative paths, which\n# will be relative from the directory where doxygen is started.\n# This tag requires that the tag FULL_PATH_NAMES is set to YES.\n\nSTRIP_FROM_PATH        =\n\n# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the\n# path mentioned in the documentation of a class, which tells the reader which\n# header file to include in order to use a class. If left blank only the name of\n# the header file containing the class definition is used. Otherwise one should\n# specify the list of include paths that are normally passed to the compiler\n# using the -I flag.\n\nSTRIP_FROM_INC_PATH    =\n\n# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but\n# less readable) file names. This can be useful is your file systems doesn't\n# support long names like on DOS, Mac, or CD-ROM.\n# The default value is: NO.\n\nSHORT_NAMES            = NO\n\n# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the\n# first line (until the first dot) of a Javadoc-style comment as the brief\n# description. If set to NO, the Javadoc-style will behave just like regular Qt-\n# style comments (thus requiring an explicit @brief command for a brief\n# description.)\n# The default value is: NO.\n\nJAVADOC_AUTOBRIEF      = NO\n\n# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line\n# such as\n# /***************\n# as being the beginning of a Javadoc-style comment \"banner\". If set to NO, the\n# Javadoc-style will behave just like regular comments and it will not be\n# interpreted by doxygen.\n# The default value is: NO.\n\nJAVADOC_BANNER         = NO\n\n# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first\n# line (until the first dot) of a Qt-style comment as the brief description. If\n# set to NO, the Qt-style will behave just like regular Qt-style comments (thus\n# requiring an explicit \\brief command for a brief description.)\n# The default value is: NO.\n\nQT_AUTOBRIEF           = NO\n\n# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a\n# multi-line C++ special comment block (i.e. a block of //! or /// comments) as\n# a brief description. This used to be the default behavior. The new default is\n# to treat a multi-line C++ comment block as a detailed description. Set this\n# tag to YES if you prefer the old behavior instead.\n#\n# Note that setting this tag to YES also means that rational rose comments are\n# not recognized any more.\n# The default value is: NO.\n\nMULTILINE_CPP_IS_BRIEF = NO\n\n# By default Python docstrings are displayed as preformatted text and doxygen's\n# special commands cannot be used. By setting PYTHON_DOCSTRING to NO the\n# doxygen's special commands can be used and the contents of the docstring\n# documentation blocks is shown as doxygen documentation.\n# The default value is: YES.\n\nPYTHON_DOCSTRING       = YES\n\n# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the\n# documentation from any documented member that it re-implements.\n# The default value is: YES.\n\nINHERIT_DOCS           = YES\n\n# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new\n# page for each member. If set to NO, the documentation of a member will be part\n# of the file/class/namespace that contains it.\n# The default value is: NO.\n\nSEPARATE_MEMBER_PAGES  = NO\n\n# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen\n# uses this value to replace tabs by spaces in code fragments.\n# Minimum value: 1, maximum value: 16, default value: 4.\n\nTAB_SIZE               = 4\n\n# This tag can be used to specify a number of aliases that act as commands in\n# the documentation. An alias has the form:\n# name=value\n# For example adding\n# \"sideeffect=@par Side Effects:^^\"\n# will allow you to put the command \\sideeffect (or @sideeffect) in the\n# documentation, which will result in a user-defined paragraph with heading\n# \"Side Effects:\". Note that you cannot put \\n's in the value part of an alias\n# to insert newlines (in the resulting output). You can put ^^ in the value part\n# of an alias to insert a newline as if a physical newline was in the original\n# file. When you need a literal { or } or , in the value part of an alias you\n# have to escape them by means of a backslash (\\), this can lead to conflicts\n# with the commands \\{ and \\} for these it is advised to use the version @{ and\n# @} or use a double escape (\\\\{ and \\\\})\n\nALIASES                =\n\n# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources\n# only. Doxygen will then generate output that is more tailored for C. For\n# instance, some of the names that are used will be different. The list of all\n# members will be omitted, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_FOR_C  = NO\n\n# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or\n# Python sources only. Doxygen will then generate output that is more tailored\n# for that language. For instance, namespaces will be presented as packages,\n# qualified scopes will look different, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_JAVA   = NO\n\n# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran\n# sources. Doxygen will then generate output that is tailored for Fortran.\n# The default value is: NO.\n\nOPTIMIZE_FOR_FORTRAN   = NO\n\n# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL\n# sources. Doxygen will then generate output that is tailored for VHDL.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_VHDL   = NO\n\n# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice\n# sources only. Doxygen will then generate output that is more tailored for that\n# language. For instance, namespaces will be presented as modules, types will be\n# separated into more groups, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_SLICE  = NO\n\n# Doxygen selects the parser to use depending on the extension of the files it\n# parses. With this tag you can assign which parser to use for a given\n# extension. Doxygen has a built-in mapping, but you can override or extend it\n# using this tag. The format is ext=language, where ext is a file extension, and\n# language is one of the parsers supported by doxygen: IDL, Java, JavaScript,\n# Csharp (C#), C, C++, Lex, D, PHP, md (Markdown), Objective-C, Python, Slice,\n# VHDL, Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:\n# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser\n# tries to guess whether the code is fixed or free formatted code, this is the\n# default for Fortran type files). For instance to make doxygen treat .inc files\n# as Fortran files (default is PHP), and .f files as C (default is Fortran),\n# use: inc=Fortran f=C.\n#\n# Note: For files without extension you can use no_extension as a placeholder.\n#\n# Note that for custom extensions you also need to set FILE_PATTERNS otherwise\n# the files are not read by doxygen. When specifying no_extension you should add\n# * to the FILE_PATTERNS.\n#\n# Note see also the list of default file extension mappings.\n\nEXTENSION_MAPPING      =\n\n# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments\n# according to the Markdown format, which allows for more readable\n# documentation. See https://daringfireball.net/projects/markdown/ for details.\n# The output of markdown processing is further processed by doxygen, so you can\n# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in\n# case of backward compatibilities issues.\n# The default value is: YES.\n\nMARKDOWN_SUPPORT       = YES\n\n# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up\n# to that level are automatically included in the table of contents, even if\n# they do not have an id attribute.\n# Note: This feature currently applies only to Markdown headings.\n# Minimum value: 0, maximum value: 99, default value: 5.\n# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.\n\nTOC_INCLUDE_HEADINGS   = 5\n\n# When enabled doxygen tries to link words that correspond to documented\n# classes, or namespaces to their corresponding documentation. Such a link can\n# be prevented in individual cases by putting a % sign in front of the word or\n# globally by setting AUTOLINK_SUPPORT to NO.\n# The default value is: YES.\n\nAUTOLINK_SUPPORT       = YES\n\n# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want\n# to include (a tag file for) the STL sources as input, then you should set this\n# tag to YES in order to let doxygen match functions declarations and\n# definitions whose arguments contain STL classes (e.g. func(std::string);\n# versus func(std::string) {}). This also make the inheritance and collaboration\n# diagrams that involve STL classes more complete and accurate.\n# The default value is: NO.\n\nBUILTIN_STL_SUPPORT    = NO\n\n# If you use Microsoft's C++/CLI language, you should set this option to YES to\n# enable parsing support.\n# The default value is: NO.\n\nCPP_CLI_SUPPORT        = NO\n\n# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:\n# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen\n# will parse them like normal C++ but will assume all classes use public instead\n# of private inheritance when no explicit protection keyword is present.\n# The default value is: NO.\n\nSIP_SUPPORT            = NO\n\n# For Microsoft's IDL there are propget and propput attributes to indicate\n# getter and setter methods for a property. Setting this option to YES will make\n# doxygen to replace the get and set methods by a property in the documentation.\n# This will only work if the methods are indeed getting or setting a simple\n# type. If this is not the case, or you want to show the methods anyway, you\n# should set this option to NO.\n# The default value is: YES.\n\nIDL_PROPERTY_SUPPORT   = YES\n\n# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC\n# tag is set to YES then doxygen will reuse the documentation of the first\n# member in the group (if any) for the other members of the group. By default\n# all members of a group must be documented explicitly.\n# The default value is: NO.\n\nDISTRIBUTE_GROUP_DOC   = NO\n\n# If one adds a struct or class to a group and this option is enabled, then also\n# any nested class or struct is added to the same group. By default this option\n# is disabled and one has to add nested compounds explicitly via \\ingroup.\n# The default value is: NO.\n\nGROUP_NESTED_COMPOUNDS = NO\n\n# Set the SUBGROUPING tag to YES to allow class member groups of the same type\n# (for instance a group of public functions) to be put as a subgroup of that\n# type (e.g. under the Public Functions section). Set it to NO to prevent\n# subgrouping. Alternatively, this can be done per class using the\n# \\nosubgrouping command.\n# The default value is: YES.\n\nSUBGROUPING            = YES\n\n# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions\n# are shown inside the group in which they are included (e.g. using \\ingroup)\n# instead of on a separate page (for HTML and Man pages) or section (for LaTeX\n# and RTF).\n#\n# Note that this feature does not work in combination with\n# SEPARATE_MEMBER_PAGES.\n# The default value is: NO.\n\nINLINE_GROUPED_CLASSES = NO\n\n# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions\n# with only public data fields or simple typedef fields will be shown inline in\n# the documentation of the scope in which they are defined (i.e. file,\n# namespace, or group documentation), provided this scope is documented. If set\n# to NO, structs, classes, and unions are shown on a separate page (for HTML and\n# Man pages) or section (for LaTeX and RTF).\n# The default value is: NO.\n\nINLINE_SIMPLE_STRUCTS  = NO\n\n# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or\n# enum is documented as struct, union, or enum with the name of the typedef. So\n# typedef struct TypeS {} TypeT, will appear in the documentation as a struct\n# with name TypeT. When disabled the typedef will appear as a member of a file,\n# namespace, or class. And the struct will be named TypeS. This can typically be\n# useful for C code in case the coding convention dictates that all compound\n# types are typedef'ed and only the typedef is referenced, never the tag name.\n# The default value is: NO.\n\nTYPEDEF_HIDES_STRUCT   = NO\n\n# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This\n# cache is used to resolve symbols given their name and scope. Since this can be\n# an expensive process and often the same symbol appears multiple times in the\n# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small\n# doxygen will become slower. If the cache is too large, memory is wasted. The\n# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range\n# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536\n# symbols. At the end of a run doxygen will report the cache usage and suggest\n# the optimal cache size from a speed point of view.\n# Minimum value: 0, maximum value: 9, default value: 0.\n\nLOOKUP_CACHE_SIZE      = 0\n\n# The NUM_PROC_THREADS specifies the number threads doxygen is allowed to use\n# during processing. When set to 0 doxygen will based this on the number of\n# cores available in the system. You can set it explicitly to a value larger\n# than 0 to get more control over the balance between CPU load and processing\n# speed. At this moment only the input processing can be done using multiple\n# threads. Since this is still an experimental feature the default is set to 1,\n# which effectively disables parallel processing. Please report any issues you\n# encounter. Generating dot graphs in parallel is controlled by the\n# DOT_NUM_THREADS setting.\n# Minimum value: 0, maximum value: 32, default value: 1.\n\nNUM_PROC_THREADS       = 1\n\n#---------------------------------------------------------------------------\n# Build related configuration options\n#---------------------------------------------------------------------------\n\n# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in\n# documentation are documented, even if no documentation was available. Private\n# class members and static file members will be hidden unless the\n# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.\n# Note: This will also disable the warnings about undocumented members that are\n# normally produced when WARNINGS is set to YES.\n# The default value is: NO.\n\nEXTRACT_ALL            = YES\n\n# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will\n# be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIVATE        = NO\n\n# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual\n# methods of a class will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIV_VIRTUAL   = NO\n\n# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal\n# scope will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PACKAGE        = NO\n\n# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be\n# included in the documentation.\n# The default value is: NO.\n\nEXTRACT_STATIC         = NO\n\n# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined\n# locally in source files will be included in the documentation. If set to NO,\n# only classes defined in header files are included. Does not have any effect\n# for Java sources.\n# The default value is: YES.\n\nEXTRACT_LOCAL_CLASSES  = YES\n\n# This flag is only useful for Objective-C code. If set to YES, local methods,\n# which are defined in the implementation section but not in the interface are\n# included in the documentation. If set to NO, only methods in the interface are\n# included.\n# The default value is: NO.\n\nEXTRACT_LOCAL_METHODS  = NO\n\n# If this flag is set to YES, the members of anonymous namespaces will be\n# extracted and appear in the documentation as a namespace called\n# 'anonymous_namespace{file}', where file will be replaced with the base name of\n# the file that contains the anonymous namespace. By default anonymous namespace\n# are hidden.\n# The default value is: NO.\n\nEXTRACT_ANON_NSPACES   = NO\n\n# If this flag is set to YES, the name of an unnamed parameter in a declaration\n# will be determined by the corresponding definition. By default unnamed\n# parameters remain unnamed in the output.\n# The default value is: YES.\n\nRESOLVE_UNNAMED_PARAMS = YES\n\n# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all\n# undocumented members inside documented classes or files. If set to NO these\n# members will be included in the various overviews, but no documentation\n# section is generated. This option has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_MEMBERS     = NO\n\n# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all\n# undocumented classes that are normally visible in the class hierarchy. If set\n# to NO, these classes will be included in the various overviews. This option\n# has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_CLASSES     = NO\n\n# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend\n# declarations. If set to NO, these declarations will be included in the\n# documentation.\n# The default value is: NO.\n\nHIDE_FRIEND_COMPOUNDS  = NO\n\n# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any\n# documentation blocks found inside the body of a function. If set to NO, these\n# blocks will be appended to the function's detailed documentation block.\n# The default value is: NO.\n\nHIDE_IN_BODY_DOCS      = NO\n\n# The INTERNAL_DOCS tag determines if documentation that is typed after a\n# \\internal command is included. If the tag is set to NO then the documentation\n# will be excluded. Set it to YES to include the internal documentation.\n# The default value is: NO.\n\nINTERNAL_DOCS          = NO\n\n# With the correct setting of option CASE_SENSE_NAMES doxygen will better be\n# able to match the capabilities of the underlying filesystem. In case the\n# filesystem is case sensitive (i.e. it supports files in the same directory\n# whose names only differ in casing), the option must be set to YES to properly\n# deal with such files in case they appear in the input. For filesystems that\n# are not case sensitive the option should be be set to NO to properly deal with\n# output files written for symbols that only differ in casing, such as for two\n# classes, one named CLASS and the other named Class, and to also support\n# references to files without having to specify the exact matching casing. On\n# Windows (including Cygwin) and MacOS, users should typically set this option\n# to NO, whereas on Linux or other Unix flavors it should typically be set to\n# YES.\n# The default value is: system dependent.\n\nCASE_SENSE_NAMES       = NO\n\n# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with\n# their full class and namespace scopes in the documentation. If set to YES, the\n# scope will be hidden.\n# The default value is: NO.\n\nHIDE_SCOPE_NAMES       = NO\n\n# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will\n# append additional text to a page's title, such as Class Reference. If set to\n# YES the compound reference will be hidden.\n# The default value is: NO.\n\nHIDE_COMPOUND_REFERENCE= NO\n\n# If the SHOW_HEADERFILE tag is set to YES then the documentation for a class\n# will show which file needs to be included to use the class.\n# The default value is: YES.\n\nSHOW_HEADERFILE        = YES\n\n# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of\n# the files that are included by a file in the documentation of that file.\n# The default value is: YES.\n\nSHOW_INCLUDE_FILES     = YES\n\n# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each\n# grouped member an include statement to the documentation, telling the reader\n# which file to include in order to use the member.\n# The default value is: NO.\n\nSHOW_GROUPED_MEMB_INC  = NO\n\n# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include\n# files with double quotes in the documentation rather than with sharp brackets.\n# The default value is: NO.\n\nFORCE_LOCAL_INCLUDES   = NO\n\n# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the\n# documentation for inline members.\n# The default value is: YES.\n\nINLINE_INFO            = YES\n\n# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the\n# (detailed) documentation of file and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order.\n# The default value is: YES.\n\nSORT_MEMBER_DOCS       = YES\n\n# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief\n# descriptions of file, namespace and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order. Note that\n# this will also influence the order of the classes in the class list.\n# The default value is: NO.\n\nSORT_BRIEF_DOCS        = NO\n\n# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the\n# (brief and detailed) documentation of class members so that constructors and\n# destructors are listed first. If set to NO the constructors will appear in the\n# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.\n# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief\n# member documentation.\n# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting\n# detailed member documentation.\n# The default value is: NO.\n\nSORT_MEMBERS_CTORS_1ST = NO\n\n# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy\n# of group names into alphabetical order. If set to NO the group names will\n# appear in their defined order.\n# The default value is: NO.\n\nSORT_GROUP_NAMES       = NO\n\n# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by\n# fully-qualified names, including namespaces. If set to NO, the class list will\n# be sorted only by class name, not including the namespace part.\n# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.\n# Note: This option applies only to the class list, not to the alphabetical\n# list.\n# The default value is: NO.\n\nSORT_BY_SCOPE_NAME     = NO\n\n# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper\n# type resolution of all parameters of a function it will reject a match between\n# the prototype and the implementation of a member function even if there is\n# only one candidate or it is obvious which candidate to choose by doing a\n# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still\n# accept a match between prototype and implementation in such cases.\n# The default value is: NO.\n\nSTRICT_PROTO_MATCHING  = NO\n\n# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo\n# list. This list is created by putting \\todo commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TODOLIST      = YES\n\n# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test\n# list. This list is created by putting \\test commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TESTLIST      = YES\n\n# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug\n# list. This list is created by putting \\bug commands in the documentation.\n# The default value is: YES.\n\nGENERATE_BUGLIST       = YES\n\n# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)\n# the deprecated list. This list is created by putting \\deprecated commands in\n# the documentation.\n# The default value is: YES.\n\nGENERATE_DEPRECATEDLIST= YES\n\n# The ENABLED_SECTIONS tag can be used to enable conditional documentation\n# sections, marked by \\if <section_label> ... \\endif and \\cond <section_label>\n# ... \\endcond blocks.\n\nENABLED_SECTIONS       =\n\n# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the\n# initial value of a variable or macro / define can have for it to appear in the\n# documentation. If the initializer consists of more lines than specified here\n# it will be hidden. Use a value of 0 to hide initializers completely. The\n# appearance of the value of individual variables and macros / defines can be\n# controlled using \\showinitializer or \\hideinitializer command in the\n# documentation regardless of this setting.\n# Minimum value: 0, maximum value: 10000, default value: 30.\n\nMAX_INITIALIZER_LINES  = 30\n\n# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at\n# the bottom of the documentation of classes and structs. If set to YES, the\n# list will mention the files that were used to generate the documentation.\n# The default value is: YES.\n\nSHOW_USED_FILES        = YES\n\n# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This\n# will remove the Files entry from the Quick Index and from the Folder Tree View\n# (if specified).\n# The default value is: YES.\n\nSHOW_FILES             = YES\n\n# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces\n# page. This will remove the Namespaces entry from the Quick Index and from the\n# Folder Tree View (if specified).\n# The default value is: YES.\n\nSHOW_NAMESPACES        = YES\n\n# The FILE_VERSION_FILTER tag can be used to specify a program or script that\n# doxygen should invoke to get the current version for each file (typically from\n# the version control system). Doxygen will invoke the program by executing (via\n# popen()) the command command input-file, where command is the value of the\n# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided\n# by doxygen. Whatever the program writes to standard output is used as the file\n# version. For an example see the documentation.\n\nFILE_VERSION_FILTER    =\n\n# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed\n# by doxygen. The layout file controls the global structure of the generated\n# output files in an output format independent way. To create the layout file\n# that represents doxygen's defaults, run doxygen with the -l option. You can\n# optionally specify a file name after the option, if omitted DoxygenLayout.xml\n# will be used as the name of the layout file. See also section \"Changing the\n# layout of pages\" for information.\n#\n# Note that if you run doxygen from a directory containing a file called\n# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE\n# tag is left empty.\n\nLAYOUT_FILE            =\n\n# The CITE_BIB_FILES tag can be used to specify one or more bib files containing\n# the reference definitions. This must be a list of .bib files. The .bib\n# extension is automatically appended if omitted. This requires the bibtex tool\n# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.\n# For LaTeX the style of the bibliography can be controlled using\n# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the\n# search path. See also \\cite for info how to create references.\n\nCITE_BIB_FILES         =\n\n#---------------------------------------------------------------------------\n# Configuration options related to warning and progress messages\n#---------------------------------------------------------------------------\n\n# The QUIET tag can be used to turn on/off the messages that are generated to\n# standard output by doxygen. If QUIET is set to YES this implies that the\n# messages are off.\n# The default value is: NO.\n\nQUIET                  = NO\n\n# The WARNINGS tag can be used to turn on/off the warning messages that are\n# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES\n# this implies that the warnings are on.\n#\n# Tip: Turn warnings on while writing the documentation.\n# The default value is: YES.\n\nWARNINGS               = YES\n\n# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate\n# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag\n# will automatically be disabled.\n# The default value is: YES.\n\nWARN_IF_UNDOCUMENTED   = YES\n\n# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for\n# potential errors in the documentation, such as documenting some parameters in\n# a documented function twice, or documenting parameters that don't exist or\n# using markup commands wrongly.\n# The default value is: YES.\n\nWARN_IF_DOC_ERROR      = YES\n\n# If WARN_IF_INCOMPLETE_DOC is set to YES, doxygen will warn about incomplete\n# function parameter documentation. If set to NO, doxygen will accept that some\n# parameters have no documentation without warning.\n# The default value is: YES.\n\nWARN_IF_INCOMPLETE_DOC = YES\n\n# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that\n# are documented, but have no documentation for their parameters or return\n# value. If set to NO, doxygen will only warn about wrong parameter\n# documentation, but not about the absence of documentation. If EXTRACT_ALL is\n# set to YES then this flag will automatically be disabled. See also\n# WARN_IF_INCOMPLETE_DOC\n# The default value is: NO.\n\nWARN_NO_PARAMDOC       = NO\n\n# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when\n# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS\n# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but\n# at the end of the doxygen process doxygen will return with a non-zero status.\n# Possible values are: NO, YES and FAIL_ON_WARNINGS.\n# The default value is: NO.\n\nWARN_AS_ERROR          = NO\n\n# The WARN_FORMAT tag determines the format of the warning messages that doxygen\n# can produce. The string should contain the $file, $line, and $text tags, which\n# will be replaced by the file and line number from which the warning originated\n# and the warning text. Optionally the format may contain $version, which will\n# be replaced by the version of the file (if it could be obtained via\n# FILE_VERSION_FILTER)\n# The default value is: $file:$line: $text.\n\nWARN_FORMAT            = \"$file:$line: $text\"\n\n# The WARN_LOGFILE tag can be used to specify a file to which warning and error\n# messages should be written. If left blank the output is written to standard\n# error (stderr). In case the file specified cannot be opened for writing the\n# warning and error messages are written to standard error. When as file - is\n# specified the warning and error messages are written to standard output\n# (stdout).\n\nWARN_LOGFILE           =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the input files\n#---------------------------------------------------------------------------\n\n# The INPUT tag is used to specify the files and/or directories that contain\n# documented source files. You may enter file names like myfile.cpp or\n# directories like /usr/src/myproject. Separate the files or directories with\n# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING\n# Note: If this tag is empty the current directory is searched.\n\nINPUT                  = Program.cs backend/ ir/ frontend/ exception/\n\n# This tag can be used to specify the character encoding of the source files\n# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses\n# libiconv (or the iconv built into libc) for the transcoding. See the libiconv\n# documentation (see:\n# https://www.gnu.org/software/libiconv/) for the list of possible encodings.\n# The default value is: UTF-8.\n\nINPUT_ENCODING         = UTF-8\n\n# If the value of the INPUT tag contains directories, you can use the\n# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and\n# *.h) to filter out the source-files in the directories.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# read by doxygen.\n#\n# Note the list of default checked file patterns might differ from the list of\n# default file extension mappings.\n#\n# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,\n# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,\n# *.hh, *.hxx, *.hpp, *.h++, *.l, *.cs, *.d, *.php, *.php4, *.php5, *.phtml,\n# *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C\n# comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd,\n# *.vhdl, *.ucf, *.qsf and *.ice.\n\nFILE_PATTERNS          = *.cs\n\n# The RECURSIVE tag can be used to specify whether or not subdirectories should\n# be searched for input files as well.\n# The default value is: NO.\n\nRECURSIVE              = YES\n\n# The EXCLUDE tag can be used to specify files and/or directories that should be\n# excluded from the INPUT source files. This way you can easily exclude a\n# subdirectory from a directory tree whose root is specified with the INPUT tag.\n#\n# Note that relative paths are relative to the directory from which doxygen is\n# run.\n\nEXCLUDE                =\n\n# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or\n# directories that are symbolic links (a Unix file system feature) are excluded\n# from the input.\n# The default value is: NO.\n\nEXCLUDE_SYMLINKS       = NO\n\n# If the value of the INPUT tag contains directories, you can use the\n# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude\n# certain files from those directories.\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories for example use the pattern */test/*\n\nEXCLUDE_PATTERNS       =\n\n# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names\n# (namespaces, classes, functions, etc.) that should be excluded from the\n# output. The symbol name can be a fully qualified name, a word, or if the\n# wildcard * is used, a substring. Examples: ANamespace, AClass,\n# ANamespace::AClass, ANamespace::*Test\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories use the pattern */test/*\n\nEXCLUDE_SYMBOLS        =\n\n# The EXAMPLE_PATH tag can be used to specify one or more files or directories\n# that contain example code fragments that are included (see the \\include\n# command).\n\nEXAMPLE_PATH           =\n\n# If the value of the EXAMPLE_PATH tag contains directories, you can use the\n# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and\n# *.h) to filter out the source-files in the directories. If left blank all\n# files are included.\n\nEXAMPLE_PATTERNS       = *\n\n# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be\n# searched for input files to be used with the \\include or \\dontinclude commands\n# irrespective of the value of the RECURSIVE tag.\n# The default value is: NO.\n\nEXAMPLE_RECURSIVE      = NO\n\n# The IMAGE_PATH tag can be used to specify one or more files or directories\n# that contain images that are to be included in the documentation (see the\n# \\image command).\n\nIMAGE_PATH             =\n\n# The INPUT_FILTER tag can be used to specify a program that doxygen should\n# invoke to filter for each input file. Doxygen will invoke the filter program\n# by executing (via popen()) the command:\n#\n# <filter> <input-file>\n#\n# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the\n# name of an input file. Doxygen will then use the output that the filter\n# program writes to standard output. If FILTER_PATTERNS is specified, this tag\n# will be ignored.\n#\n# Note that the filter must not add or remove lines; it is applied before the\n# code is scanned, but not when the output code is generated. If lines are added\n# or removed, the anchors will not be placed correctly.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by doxygen.\n\nINPUT_FILTER           =\n\n# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern\n# basis. Doxygen will compare the file name with each pattern and apply the\n# filter if there is a match. The filters are a list of the form: pattern=filter\n# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how\n# filters are used. If the FILTER_PATTERNS tag is empty or if none of the\n# patterns match the file name, INPUT_FILTER is applied.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by doxygen.\n\nFILTER_PATTERNS        =\n\n# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using\n# INPUT_FILTER) will also be used to filter the input files that are used for\n# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).\n# The default value is: NO.\n\nFILTER_SOURCE_FILES    = NO\n\n# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file\n# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and\n# it is also possible to disable source filtering for a specific pattern using\n# *.ext= (so without naming a filter).\n# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.\n\nFILTER_SOURCE_PATTERNS =\n\n# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that\n# is part of the input, its contents will be placed on the main page\n# (index.html). This can be useful if you have a project on for instance GitHub\n# and want to reuse the introduction page also for the doxygen output.\n\nUSE_MDFILE_AS_MAINPAGE =\n\n#---------------------------------------------------------------------------\n# Configuration options related to source browsing\n#---------------------------------------------------------------------------\n\n# If the SOURCE_BROWSER tag is set to YES then a list of source files will be\n# generated. Documented entities will be cross-referenced with these sources.\n#\n# Note: To get rid of all source code in the generated output, make sure that\n# also VERBATIM_HEADERS is set to NO.\n# The default value is: NO.\n\nSOURCE_BROWSER         = NO\n\n# Setting the INLINE_SOURCES tag to YES will include the body of functions,\n# classes and enums directly into the documentation.\n# The default value is: NO.\n\nINLINE_SOURCES         = NO\n\n# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any\n# special comment blocks from generated source code fragments. Normal C, C++ and\n# Fortran comments will always remain visible.\n# The default value is: YES.\n\nSTRIP_CODE_COMMENTS    = YES\n\n# If the REFERENCED_BY_RELATION tag is set to YES then for each documented\n# entity all documented functions referencing it will be listed.\n# The default value is: NO.\n\nREFERENCED_BY_RELATION = NO\n\n# If the REFERENCES_RELATION tag is set to YES then for each documented function\n# all documented entities called/used by that function will be listed.\n# The default value is: NO.\n\nREFERENCES_RELATION    = NO\n\n# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set\n# to YES then the hyperlinks from functions in REFERENCES_RELATION and\n# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will\n# link to the documentation.\n# The default value is: YES.\n\nREFERENCES_LINK_SOURCE = YES\n\n# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the\n# source code will show a tooltip with additional information such as prototype,\n# brief description and links to the definition and documentation. Since this\n# will make the HTML file larger and loading of large files a bit slower, you\n# can opt to disable this feature.\n# The default value is: YES.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nSOURCE_TOOLTIPS        = YES\n\n# If the USE_HTAGS tag is set to YES then the references to source code will\n# point to the HTML generated by the htags(1) tool instead of doxygen built-in\n# source browser. The htags tool is part of GNU's global source tagging system\n# (see https://www.gnu.org/software/global/global.html). You will need version\n# 4.8.6 or higher.\n#\n# To use it do the following:\n# - Install the latest version of global\n# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file\n# - Make sure the INPUT points to the root of the source tree\n# - Run doxygen as normal\n#\n# Doxygen will invoke htags (and that will in turn invoke gtags), so these\n# tools must be available from the command line (i.e. in the search path).\n#\n# The result: instead of the source browser generated by doxygen, the links to\n# source code will now point to the output of htags.\n# The default value is: NO.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nUSE_HTAGS              = NO\n\n# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a\n# verbatim copy of the header file for each class for which an include is\n# specified. Set to NO to disable this.\n# See also: Section \\class.\n# The default value is: YES.\n\nVERBATIM_HEADERS       = YES\n\n# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the\n# clang parser (see:\n# http://clang.llvm.org/) for more accurate parsing at the cost of reduced\n# performance. This can be particularly helpful with template rich C++ code for\n# which doxygen's built-in parser lacks the necessary type information.\n# Note: The availability of this option depends on whether or not doxygen was\n# generated with the -Duse_libclang=ON option for CMake.\n# The default value is: NO.\n\nCLANG_ASSISTED_PARSING = NO\n\n# If the CLANG_ASSISTED_PARSING tag is set to YES and the CLANG_ADD_INC_PATHS\n# tag is set to YES then doxygen will add the directory of each input to the\n# include path.\n# The default value is: YES.\n# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.\n\nCLANG_ADD_INC_PATHS    = YES\n\n# If clang assisted parsing is enabled you can provide the compiler with command\n# line options that you would normally use when invoking the compiler. Note that\n# the include paths will already be set by doxygen for the files and directories\n# specified with INPUT and INCLUDE_PATH.\n# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.\n\nCLANG_OPTIONS          =\n\n# If clang assisted parsing is enabled you can provide the clang parser with the\n# path to the directory containing a file called compile_commands.json. This\n# file is the compilation database (see:\n# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) containing the\n# options used when the source files were built. This is equivalent to\n# specifying the -p option to a clang tool, such as clang-check. These options\n# will then be passed to the parser. Any options specified with CLANG_OPTIONS\n# will be added as well.\n# Note: The availability of this option depends on whether or not doxygen was\n# generated with the -Duse_libclang=ON option for CMake.\n\nCLANG_DATABASE_PATH    =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the alphabetical class index\n#---------------------------------------------------------------------------\n\n# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all\n# compounds will be generated. Enable this if the project contains a lot of\n# classes, structs, unions or interfaces.\n# The default value is: YES.\n\nALPHABETICAL_INDEX     = YES\n\n# In case all classes in a project start with a common prefix, all classes will\n# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag\n# can be used to specify a prefix (or a list of prefixes) that should be ignored\n# while generating the index headers.\n# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.\n\nIGNORE_PREFIX          =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the HTML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output\n# The default value is: YES.\n\nGENERATE_HTML          = YES\n\n# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_OUTPUT            = api-doc\n\n# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each\n# generated HTML page (for example: .htm, .php, .asp).\n# The default value is: .html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FILE_EXTENSION    = .html\n\n# The HTML_HEADER tag can be used to specify a user-defined HTML header file for\n# each generated HTML page. If the tag is left blank doxygen will generate a\n# standard header.\n#\n# To get valid HTML the header file that includes any scripts and style sheets\n# that doxygen needs, which is dependent on the configuration options used (e.g.\n# the setting GENERATE_TREEVIEW). It is highly recommended to start with a\n# default header using\n# doxygen -w html new_header.html new_footer.html new_stylesheet.css\n# YourConfigFile\n# and then modify the file new_header.html. See also section \"Doxygen usage\"\n# for information on how to generate the default header that doxygen normally\n# uses.\n# Note: The header is subject to change so you typically have to regenerate the\n# default header when upgrading to a newer version of doxygen. For a description\n# of the possible markers and block names see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_HEADER            =\n\n# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each\n# generated HTML page. If the tag is left blank doxygen will generate a standard\n# footer. See HTML_HEADER for more information on how to generate a default\n# footer and what special commands can be used inside the footer. See also\n# section \"Doxygen usage\" for information on how to generate the default footer\n# that doxygen normally uses.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FOOTER            =\n\n# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style\n# sheet that is used by each HTML page. It can be used to fine-tune the look of\n# the HTML output. If left blank doxygen will generate a default style sheet.\n# See also section \"Doxygen usage\" for information on how to generate the style\n# sheet that doxygen normally uses.\n# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as\n# it is more robust and this tag (HTML_STYLESHEET) will in the future become\n# obsolete.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_STYLESHEET        =\n\n# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# cascading style sheets that are included after the standard style sheets\n# created by doxygen. Using this option one can overrule certain style aspects.\n# This is preferred over using HTML_STYLESHEET since it does not replace the\n# standard style sheet and is therefore more robust against future updates.\n# Doxygen will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list). For an example see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_STYLESHEET  =\n\n# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the HTML output directory. Note\n# that these files will be copied to the base HTML output directory. Use the\n# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these\n# files. In the HTML_STYLESHEET file, use the file name only. Also note that the\n# files will be copied as-is; there are no commands or markers available.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_FILES       =\n\n# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen\n# will adjust the colors in the style sheet and background images according to\n# this color. Hue is specified as an angle on a color-wheel, see\n# https://en.wikipedia.org/wiki/Hue for more information. For instance the value\n# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300\n# purple, and 360 is red again.\n# Minimum value: 0, maximum value: 359, default value: 220.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_HUE    = 220\n\n# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors\n# in the HTML output. For a value of 0 the output will use gray-scales only. A\n# value of 255 will produce the most vivid colors.\n# Minimum value: 0, maximum value: 255, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_SAT    = 100\n\n# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the\n# luminance component of the colors in the HTML output. Values below 100\n# gradually make the output lighter, whereas values above 100 make the output\n# darker. The value divided by 100 is the actual gamma applied, so 80 represents\n# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not\n# change the gamma.\n# Minimum value: 40, maximum value: 240, default value: 80.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_GAMMA  = 80\n\n# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML\n# page will contain the date and time when the page was generated. Setting this\n# to YES can help to show when doxygen was last run and thus if the\n# documentation is up to date.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_TIMESTAMP         = NO\n\n# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML\n# documentation will contain a main index with vertical navigation menus that\n# are dynamically created via JavaScript. If disabled, the navigation index will\n# consists of multiple levels of tabs that are statically embedded in every HTML\n# page. Disable this option to support browsers that do not have JavaScript,\n# like the Qt help browser.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_MENUS     = YES\n\n# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML\n# documentation will contain sections that can be hidden and shown after the\n# page has loaded.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_SECTIONS  = NO\n\n# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries\n# shown in the various tree structured indices initially; the user can expand\n# and collapse entries dynamically later on. Doxygen will expand the tree to\n# such a level that at most the specified number of entries are visible (unless\n# a fully collapsed tree already exceeds this amount). So setting the number of\n# entries 1 will produce a full collapsed tree by default. 0 is a special value\n# representing an infinite number of entries and will result in a full expanded\n# tree by default.\n# Minimum value: 0, maximum value: 9999, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_INDEX_NUM_ENTRIES = 100\n\n# If the GENERATE_DOCSET tag is set to YES, additional index files will be\n# generated that can be used as input for Apple's Xcode 3 integrated development\n# environment (see:\n# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To\n# create a documentation set, doxygen will generate a Makefile in the HTML\n# output directory. Running make will produce the docset in that directory and\n# running make install will install the docset in\n# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at\n# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy\n# genXcode/_index.html for more information.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_DOCSET        = NO\n\n# This tag determines the name of the docset feed. A documentation feed provides\n# an umbrella under which multiple documentation sets from a single provider\n# (such as a company or product suite) can be grouped.\n# The default value is: Doxygen generated docs.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_FEEDNAME        = \"Doxygen generated docs\"\n\n# This tag determines the URL of the docset feed. A documentation feed provides\n# an umbrella under which multiple documentation sets from a single provider\n# (such as a company or product suite) can be grouped.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_FEEDURL         =\n\n# This tag specifies a string that should uniquely identify the documentation\n# set bundle. This should be a reverse domain-name style string, e.g.\n# com.mycompany.MyDocSet. Doxygen will append .docset to the name.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_BUNDLE_ID       = org.doxygen.Project\n\n# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify\n# the documentation publisher. This should be a reverse domain-name style\n# string, e.g. com.mycompany.MyDocSet.documentation.\n# The default value is: org.doxygen.Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_ID    = org.doxygen.Publisher\n\n# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.\n# The default value is: Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_NAME  = Publisher\n\n# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three\n# additional HTML index files: index.hhp, index.hhc, and index.hhk. The\n# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop\n# on Windows. In the beginning of 2021 Microsoft took the original page, with\n# a.o. the download links, offline the HTML help workshop was already many years\n# in maintenance mode). You can download the HTML help workshop from the web\n# archives at Installation executable (see:\n# http://web.archive.org/web/20160201063255/http://download.microsoft.com/downlo\n# ad/0/A/9/0A939EF6-E31C-430F-A3DF-DFAE7960D564/htmlhelp.exe).\n#\n# The HTML Help Workshop contains a compiler that can convert all HTML output\n# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML\n# files are now used as the Windows 98 help format, and will replace the old\n# Windows help format (.hlp) on all Windows platforms in the future. Compressed\n# HTML files also contain an index, a table of contents, and you can search for\n# words in the documentation. The HTML workshop also contains a viewer for\n# compressed HTML files.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_HTMLHELP      = NO\n\n# The CHM_FILE tag can be used to specify the file name of the resulting .chm\n# file. You can add a path in front of the file if the result should not be\n# written to the html output directory.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_FILE               =\n\n# The HHC_LOCATION tag can be used to specify the location (absolute path\n# including file name) of the HTML help compiler (hhc.exe). If non-empty,\n# doxygen will try to run the HTML help compiler on the generated index.hhp.\n# The file has to be specified with full path.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nHHC_LOCATION           =\n\n# The GENERATE_CHI flag controls if a separate .chi index file is generated\n# (YES) or that it should be included in the main .chm file (NO).\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nGENERATE_CHI           = NO\n\n# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)\n# and project file content.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_INDEX_ENCODING     =\n\n# The BINARY_TOC flag controls whether a binary table of contents is generated\n# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it\n# enables the Previous and Next buttons.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nBINARY_TOC             = NO\n\n# The TOC_EXPAND flag can be set to YES to add extra items for group members to\n# the table of contents of the HTML help documentation and to the tree view.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nTOC_EXPAND             = NO\n\n# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and\n# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that\n# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help\n# (.qch) of the generated HTML documentation.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_QHP           = NO\n\n# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify\n# the file name of the resulting .qch file. The path specified is relative to\n# the HTML output folder.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQCH_FILE               =\n\n# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help\n# Project output. For more information please see Qt Help Project / Namespace\n# (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_NAMESPACE          = org.doxygen.Project\n\n# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt\n# Help Project output. For more information please see Qt Help Project / Virtual\n# Folders (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).\n# The default value is: doc.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_VIRTUAL_FOLDER     = doc\n\n# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom\n# filter to add. For more information please see Qt Help Project / Custom\n# Filters (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_NAME   =\n\n# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the\n# custom filter to add. For more information please see Qt Help Project / Custom\n# Filters (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_ATTRS  =\n\n# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this\n# project's filter section matches. Qt Help Project / Filter Attributes (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_SECT_FILTER_ATTRS  =\n\n# The QHG_LOCATION tag can be used to specify the location (absolute path\n# including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to\n# run qhelpgenerator on the generated .qhp file.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHG_LOCATION           =\n\n# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be\n# generated, together with the HTML files, they form an Eclipse help plugin. To\n# install this plugin and make it available under the help contents menu in\n# Eclipse, the contents of the directory containing the HTML and XML files needs\n# to be copied into the plugins directory of eclipse. The name of the directory\n# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.\n# After copying Eclipse needs to be restarted before the help appears.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_ECLIPSEHELP   = NO\n\n# A unique identifier for the Eclipse help plugin. When installing the plugin\n# the directory name containing the HTML and XML files should also have this\n# name. Each documentation set should have its own identifier.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.\n\nECLIPSE_DOC_ID         = org.doxygen.Project\n\n# If you want full control over the layout of the generated HTML pages it might\n# be necessary to disable the index and replace it with your own. The\n# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top\n# of each HTML page. A value of NO enables the index and the value YES disables\n# it. Since the tabs in the index contain the same information as the navigation\n# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nDISABLE_INDEX          = NO\n\n# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index\n# structure should be generated to display hierarchical information. If the tag\n# value is set to YES, a side panel will be generated containing a tree-like\n# index structure (just like the one that is generated for HTML Help). For this\n# to work a browser that supports JavaScript, DHTML, CSS and frames is required\n# (i.e. any modern browser). Windows users are probably better off using the\n# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can\n# further fine tune the look of the index (see \"Fine-tuning the output\"). As an\n# example, the default style sheet generated by doxygen has an example that\n# shows how to put an image at the root of the tree instead of the PROJECT_NAME.\n# Since the tree basically has the same information as the tab index, you could\n# consider setting DISABLE_INDEX to YES when enabling this option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_TREEVIEW      = NO\n\n# When both GENERATE_TREEVIEW and DISABLE_INDEX are set to YES, then the\n# FULL_SIDEBAR option determines if the side bar is limited to only the treeview\n# area (value NO) or if it should extend to the full height of the window (value\n# YES). Setting this to YES gives a layout similar to\n# https://docs.readthedocs.io with more room for contents, but less room for the\n# project logo, title, and description. If either GENERATE_TREEVIEW or\n# DISABLE_INDEX is set to NO, this option has no effect.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFULL_SIDEBAR           = NO\n\n# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that\n# doxygen will group on one line in the generated HTML documentation.\n#\n# Note that a value of 0 will completely suppress the enum values from appearing\n# in the overview section.\n# Minimum value: 0, maximum value: 20, default value: 4.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nENUM_VALUES_PER_LINE   = 4\n\n# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used\n# to set the initial width (in pixels) of the frame in which the tree is shown.\n# Minimum value: 0, maximum value: 1500, default value: 250.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nTREEVIEW_WIDTH         = 250\n\n# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to\n# external symbols imported via tag files in a separate window.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nEXT_LINKS_IN_WINDOW    = NO\n\n# If the OBFUSCATE_EMAILS tag is set to YES, doxygen will obfuscate email\n# addresses.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nOBFUSCATE_EMAILS       = YES\n\n# If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg\n# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see\n# https://inkscape.org) to generate formulas as SVG images instead of PNGs for\n# the HTML output. These images will generally look nicer at scaled resolutions.\n# Possible values are: png (the default) and svg (looks nicer but requires the\n# pdf2svg or inkscape tool).\n# The default value is: png.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FORMULA_FORMAT    = png\n\n# Use this tag to change the font size of LaTeX formulas included as images in\n# the HTML documentation. When you change the font size after a successful\n# doxygen run you need to manually remove any form_*.png images from the HTML\n# output directory to force them to be regenerated.\n# Minimum value: 8, maximum value: 50, default value: 10.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_FONTSIZE       = 10\n\n# Use the FORMULA_TRANSPARENT tag to determine whether or not the images\n# generated for formulas are transparent PNGs. Transparent PNGs are not\n# supported properly for IE 6.0, but are supported on all modern browsers.\n#\n# Note that when changing this option you need to delete any form_*.png files in\n# the HTML output directory before the changes have effect.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_TRANSPARENT    = YES\n\n# The FORMULA_MACROFILE can contain LaTeX \\newcommand and \\renewcommand commands\n# to create new LaTeX commands to be used in formulas as building blocks. See\n# the section \"Including formulas\" for details.\n\nFORMULA_MACROFILE      =\n\n# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see\n# https://www.mathjax.org) which uses client side JavaScript for the rendering\n# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX\n# installed or if you want to formulas look prettier in the HTML output. When\n# enabled you may also need to install MathJax separately and configure the path\n# to it using the MATHJAX_RELPATH option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nUSE_MATHJAX            = NO\n\n# With MATHJAX_VERSION it is possible to specify the MathJax version to be used.\n# Note that the different versions of MathJax have different requirements with\n# regards to the different settings, so it is possible that also other MathJax\n# settings have to be changed when switching between the different MathJax\n# versions.\n# Possible values are: MathJax_2 and MathJax_3.\n# The default value is: MathJax_2.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_VERSION        = MathJax_2\n\n# When MathJax is enabled you can set the default output format to be used for\n# the MathJax output. For more details about the output format see MathJax\n# version 2 (see:\n# http://docs.mathjax.org/en/v2.7-latest/output.html) and MathJax version 3\n# (see:\n# http://docs.mathjax.org/en/latest/web/components/output.html).\n# Possible values are: HTML-CSS (which is slower, but has the best\n# compatibility. This is the name for Mathjax version 2, for MathJax version 3\n# this will be translated into chtml), NativeMML (i.e. MathML. Only supported\n# for NathJax 2. For MathJax version 3 chtml will be used instead.), chtml (This\n# is the name for Mathjax version 3, for MathJax version 2 this will be\n# translated into HTML-CSS) and SVG.\n# The default value is: HTML-CSS.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_FORMAT         = HTML-CSS\n\n# When MathJax is enabled you need to specify the location relative to the HTML\n# output directory using the MATHJAX_RELPATH option. The destination directory\n# should contain the MathJax.js script. For instance, if the mathjax directory\n# is located at the same level as the HTML output directory, then\n# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax\n# Content Delivery Network so you can quickly see the result without installing\n# MathJax. However, it is strongly recommended to install a local copy of\n# MathJax from https://www.mathjax.org before deployment. The default value is:\n# - in case of MathJax version 2: https://cdn.jsdelivr.net/npm/mathjax@2\n# - in case of MathJax version 3: https://cdn.jsdelivr.net/npm/mathjax@3\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_RELPATH        =\n\n# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax\n# extension names that should be enabled during MathJax rendering. For example\n# for MathJax version 2 (see\n# https://docs.mathjax.org/en/v2.7-latest/tex.html#tex-and-latex-extensions):\n# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols\n# For example for MathJax version 3 (see\n# http://docs.mathjax.org/en/latest/input/tex/extensions/index.html):\n# MATHJAX_EXTENSIONS = ams\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_EXTENSIONS     =\n\n# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces\n# of code that will be used on startup of the MathJax code. See the MathJax site\n# (see:\n# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an\n# example see the documentation.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_CODEFILE       =\n\n# When the SEARCHENGINE tag is enabled doxygen will generate a search box for\n# the HTML output. The underlying search engine uses javascript and DHTML and\n# should work on any modern browser. Note that when using HTML help\n# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)\n# there is already a search function so this one should typically be disabled.\n# For large projects the javascript based search engine can be slow, then\n# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to\n# search using the keyboard; to jump to the search box use <access key> + S\n# (what the <access key> is depends on the OS and browser, but it is typically\n# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down\n# key> to jump into the search results window, the results can be navigated\n# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel\n# the search. The filter options can be selected when the cursor is inside the\n# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>\n# to select a filter and <Enter> or <escape> to activate or cancel the filter\n# option.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nSEARCHENGINE           = YES\n\n# When the SERVER_BASED_SEARCH tag is enabled the search engine will be\n# implemented using a web server instead of a web client using JavaScript. There\n# are two flavors of web server based searching depending on the EXTERNAL_SEARCH\n# setting. When disabled, doxygen will generate a PHP script for searching and\n# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing\n# and searching needs to be provided by external tools. See the section\n# \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSERVER_BASED_SEARCH    = NO\n\n# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP\n# script for searching. Instead the search results are written to an XML file\n# which needs to be processed by an external indexer. Doxygen will invoke an\n# external search engine pointed to by the SEARCHENGINE_URL option to obtain the\n# search results.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see:\n# https://xapian.org/).\n#\n# See the section \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH        = NO\n\n# The SEARCHENGINE_URL should point to a search engine hosted by a web server\n# which will return the search results when EXTERNAL_SEARCH is enabled.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see:\n# https://xapian.org/). See the section \"External Indexing and Searching\" for\n# details.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHENGINE_URL       =\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed\n# search data is written to a file for indexing by an external tool. With the\n# SEARCHDATA_FILE tag the name of this file can be specified.\n# The default file is: searchdata.xml.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHDATA_FILE        = searchdata.xml\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the\n# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is\n# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple\n# projects and redirect the results back to the right project.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH_ID     =\n\n# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen\n# projects other than the one defined by this configuration file, but that are\n# all added to the same external search index. Each project needs to have a\n# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of\n# to a relative location where the documentation can be found. The format is:\n# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTRA_SEARCH_MAPPINGS  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the LaTeX output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.\n# The default value is: YES.\n\nGENERATE_LATEX         = NO\n\n# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: latex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_OUTPUT           = latex\n\n# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be\n# invoked.\n#\n# Note that when not enabling USE_PDFLATEX the default is latex when enabling\n# USE_PDFLATEX the default is pdflatex and when in the later case latex is\n# chosen this is overwritten by pdflatex. For specific output languages the\n# default can have been set differently, this depends on the implementation of\n# the output language.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_CMD_NAME         =\n\n# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate\n# index for LaTeX.\n# Note: This tag is used in the Makefile / make.bat.\n# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file\n# (.tex).\n# The default file is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nMAKEINDEX_CMD_NAME     = makeindex\n\n# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to\n# generate index for LaTeX. In case there is no backslash (\\) as first character\n# it will be automatically added in the LaTeX code.\n# Note: This tag is used in the generated output file (.tex).\n# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat.\n# The default value is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_MAKEINDEX_CMD    = makeindex\n\n# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nCOMPACT_LATEX          = NO\n\n# The PAPER_TYPE tag can be used to set the paper type that is used by the\n# printer.\n# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x\n# 14 inches) and executive (7.25 x 10.5 inches).\n# The default value is: a4.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPAPER_TYPE             = a4\n\n# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names\n# that should be included in the LaTeX output. The package can be specified just\n# by its name or with the correct syntax as to be used with the LaTeX\n# \\usepackage command. To get the times font for instance you can specify :\n# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}\n# To use the option intlimits with the amsmath package you can specify:\n# EXTRA_PACKAGES=[intlimits]{amsmath}\n# If left blank no extra packages will be included.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nEXTRA_PACKAGES         =\n\n# The LATEX_HEADER tag can be used to specify a user-defined LaTeX header for\n# the generated LaTeX document. The header should contain everything until the\n# first chapter. If it is left blank doxygen will generate a standard header. It\n# is highly recommended to start with a default header using\n# doxygen -w latex new_header.tex new_footer.tex new_stylesheet.sty\n# and then modify the file new_header.tex. See also section \"Doxygen usage\" for\n# information on how to generate the default header that doxygen normally uses.\n#\n# Note: Only use a user-defined header if you know what you are doing!\n# Note: The header is subject to change so you typically have to regenerate the\n# default header when upgrading to a newer version of doxygen. The following\n# commands have a special meaning inside the header (and footer): For a\n# description of the possible markers and block names see the documentation.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HEADER           =\n\n# The LATEX_FOOTER tag can be used to specify a user-defined LaTeX footer for\n# the generated LaTeX document. The footer should contain everything after the\n# last chapter. If it is left blank doxygen will generate a standard footer. See\n# LATEX_HEADER for more information on how to generate a default footer and what\n# special commands can be used inside the footer. See also section \"Doxygen\n# usage\" for information on how to generate the default footer that doxygen\n# normally uses. Note: Only use a user-defined footer if you know what you are\n# doing!\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_FOOTER           =\n\n# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# LaTeX style sheets that are included after the standard style sheets created\n# by doxygen. Using this option one can overrule certain style aspects. Doxygen\n# will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list).\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_STYLESHEET =\n\n# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the LATEX_OUTPUT output\n# directory. Note that the files will be copied as-is; there are no commands or\n# markers available.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_FILES      =\n\n# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is\n# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will\n# contain links (just like the HTML output) instead of page references. This\n# makes the output suitable for online browsing using a PDF viewer.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPDF_HYPERLINKS         = YES\n\n# If the USE_PDFLATEX tag is set to YES, doxygen will use the engine as\n# specified with LATEX_CMD_NAME to generate the PDF file directly from the LaTeX\n# files. Set this option to YES, to get a higher quality PDF documentation.\n#\n# See also section LATEX_CMD_NAME for selecting the engine.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nUSE_PDFLATEX           = YES\n\n# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode\n# command to the generated LaTeX files. This will instruct LaTeX to keep running\n# if errors occur, instead of asking the user for help.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BATCHMODE        = NO\n\n# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the\n# index chapters (such as File Index, Compound Index, etc.) in the output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HIDE_INDICES     = NO\n\n# The LATEX_BIB_STYLE tag can be used to specify the style to use for the\n# bibliography, e.g. plainnat, or ieeetr. See\n# https://en.wikipedia.org/wiki/BibTeX and \\cite for more info.\n# The default value is: plain.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BIB_STYLE        = plain\n\n# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated\n# page will contain the date and time when the page was generated. Setting this\n# to NO can help when comparing the output of multiple runs.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_TIMESTAMP        = NO\n\n# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)\n# path from which the emoji images will be read. If a relative path is entered,\n# it will be relative to the LATEX_OUTPUT directory. If left blank the\n# LATEX_OUTPUT directory will be used.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EMOJI_DIRECTORY  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the RTF output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The\n# RTF output is optimized for Word 97 and may not look too pretty with other RTF\n# readers/editors.\n# The default value is: NO.\n\nGENERATE_RTF           = NO\n\n# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: rtf.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_OUTPUT             = rtf\n\n# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nCOMPACT_RTF            = NO\n\n# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will\n# contain hyperlink fields. The RTF file will contain links (just like the HTML\n# output) instead of page references. This makes the output suitable for online\n# browsing using Word or some other Word compatible readers that support those\n# fields.\n#\n# Note: WordPad (write) and others do not support links.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_HYPERLINKS         = NO\n\n# Load stylesheet definitions from file. Syntax is similar to doxygen's\n# configuration file, i.e. a series of assignments. You only have to provide\n# replacements, missing definitions are set to their default value.\n#\n# See also section \"Doxygen usage\" for information on how to generate the\n# default style sheet that doxygen normally uses.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_STYLESHEET_FILE    =\n\n# Set optional variables used in the generation of an RTF document. Syntax is\n# similar to doxygen's configuration file. A template extensions file can be\n# generated using doxygen -e rtf extensionFile.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_EXTENSIONS_FILE    =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the man page output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for\n# classes and files.\n# The default value is: NO.\n\nGENERATE_MAN           = NO\n\n# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it. A directory man3 will be created inside the directory specified by\n# MAN_OUTPUT.\n# The default directory is: man.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_OUTPUT             = man\n\n# The MAN_EXTENSION tag determines the extension that is added to the generated\n# man pages. In case the manual section does not start with a number, the number\n# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is\n# optional.\n# The default value is: .3.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_EXTENSION          = .3\n\n# The MAN_SUBDIR tag determines the name of the directory created within\n# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by\n# MAN_EXTENSION with the initial . removed.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_SUBDIR             =\n\n# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it\n# will generate one additional man file for each entity documented in the real\n# man page(s). These additional files only source the real man page, but without\n# them the man command would be unable to find the correct page.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_LINKS              = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the XML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that\n# captures the structure of the code including all documentation.\n# The default value is: NO.\n\nGENERATE_XML           = NO\n\n# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: xml.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_OUTPUT             = xml\n\n# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program\n# listings (including syntax highlighting and cross-referencing information) to\n# the XML output. Note that enabling this will significantly increase the size\n# of the XML output.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_PROGRAMLISTING     = YES\n\n# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include\n# namespace members in file scope as well, matching the HTML output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_NS_MEMB_FILE_SCOPE = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the DOCBOOK output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files\n# that can be used to generate PDF.\n# The default value is: NO.\n\nGENERATE_DOCBOOK       = NO\n\n# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in\n# front of it.\n# The default directory is: docbook.\n# This tag requires that the tag GENERATE_DOCBOOK is set to YES.\n\nDOCBOOK_OUTPUT         = docbook\n\n#---------------------------------------------------------------------------\n# Configuration options for the AutoGen Definitions output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an\n# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures\n# the structure of the code including all documentation. Note that this feature\n# is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_AUTOGEN_DEF   = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the Perl module output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module\n# file that captures the structure of the code including all documentation.\n#\n# Note that this feature is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_PERLMOD       = NO\n\n# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary\n# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI\n# output from the Perl module output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_LATEX          = NO\n\n# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely\n# formatted so it can be parsed by a human reader. This is useful if you want to\n# understand what is going on. On the other hand, if this tag is set to NO, the\n# size of the Perl module output will be much smaller and Perl will parse it\n# just the same.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_PRETTY         = YES\n\n# The names of the make variables in the generated doxyrules.make file are\n# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful\n# so different doxyrules.make files included by the same Makefile don't\n# overwrite each other's variables.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_MAKEVAR_PREFIX =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the preprocessor\n#---------------------------------------------------------------------------\n\n# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all\n# C-preprocessor directives found in the sources and include files.\n# The default value is: YES.\n\nENABLE_PREPROCESSING   = YES\n\n# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names\n# in the source code. If set to NO, only conditional compilation will be\n# performed. Macro expansion can be done in a controlled way by setting\n# EXPAND_ONLY_PREDEF to YES.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nMACRO_EXPANSION        = NO\n\n# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then\n# the macro expansion is limited to the macros specified with the PREDEFINED and\n# EXPAND_AS_DEFINED tags.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_ONLY_PREDEF     = NO\n\n# If the SEARCH_INCLUDES tag is set to YES, the include files in the\n# INCLUDE_PATH will be searched if a #include is found.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSEARCH_INCLUDES        = YES\n\n# The INCLUDE_PATH tag can be used to specify one or more directories that\n# contain include files that are not input files but should be processed by the\n# preprocessor.\n# This tag requires that the tag SEARCH_INCLUDES is set to YES.\n\nINCLUDE_PATH           =\n\n# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard\n# patterns (like *.h and *.hpp) to filter out the header-files in the\n# directories. If left blank, the patterns specified with FILE_PATTERNS will be\n# used.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nINCLUDE_FILE_PATTERNS  =\n\n# The PREDEFINED tag can be used to specify one or more macro names that are\n# defined before the preprocessor is started (similar to the -D option of e.g.\n# gcc). The argument of the tag is a list of macros of the form: name or\n# name=definition (no spaces). If the definition and the \"=\" are omitted, \"=1\"\n# is assumed. To prevent a macro definition from being undefined via #undef or\n# recursively expanded use the := operator instead of the = operator.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nPREDEFINED             =\n\n# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this\n# tag can be used to specify a list of macro names that should be expanded. The\n# macro definition that is found in the sources will be used. Use the PREDEFINED\n# tag if you want to use a different macro definition that overrules the\n# definition found in the source code.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_AS_DEFINED      =\n\n# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will\n# remove all references to function-like macros that are alone on a line, have\n# an all uppercase name, and do not end with a semicolon. Such function macros\n# are typically used for boiler-plate code, and will confuse the parser if not\n# removed.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSKIP_FUNCTION_MACROS   = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to external references\n#---------------------------------------------------------------------------\n\n# The TAGFILES tag can be used to specify one or more tag files. For each tag\n# file the location of the external documentation should be added. The format of\n# a tag file without this location is as follows:\n# TAGFILES = file1 file2 ...\n# Adding location for the tag files is done as follows:\n# TAGFILES = file1=loc1 \"file2 = loc2\" ...\n# where loc1 and loc2 can be relative or absolute paths or URLs. See the\n# section \"Linking to external documentation\" for more information about the use\n# of tag files.\n# Note: Each tag file must have a unique name (where the name does NOT include\n# the path). If a tag file is not located in the directory in which doxygen is\n# run, you must also specify the path to the tagfile here.\n\nTAGFILES               =\n\n# When a file name is specified after GENERATE_TAGFILE, doxygen will create a\n# tag file that is based on the input files it reads. See section \"Linking to\n# external documentation\" for more information about the usage of tag files.\n\nGENERATE_TAGFILE       =\n\n# If the ALLEXTERNALS tag is set to YES, all external class will be listed in\n# the class index. If set to NO, only the inherited external classes will be\n# listed.\n# The default value is: NO.\n\nALLEXTERNALS           = NO\n\n# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed\n# in the modules index. If set to NO, only the current project's groups will be\n# listed.\n# The default value is: YES.\n\nEXTERNAL_GROUPS        = YES\n\n# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in\n# the related pages index. If set to NO, only the current project's pages will\n# be listed.\n# The default value is: YES.\n\nEXTERNAL_PAGES         = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to the dot tool\n#---------------------------------------------------------------------------\n\n# You can include diagrams made with dia in doxygen documentation. Doxygen will\n# then run dia to produce the diagram and insert it in the documentation. The\n# DIA_PATH tag allows you to specify the directory where the dia binary resides.\n# If left empty dia is assumed to be found in the default search path.\n\nDIA_PATH               =\n\n# If set to YES the inheritance and collaboration graphs will hide inheritance\n# and usage relations if the target is undocumented or is not a class.\n# The default value is: YES.\n\nHIDE_UNDOC_RELATIONS   = YES\n\n# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is\n# available from the path. This tool is part of Graphviz (see:\n# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent\n# Bell Labs. The other options in this section have no effect if this option is\n# set to NO\n# The default value is: NO.\n\nHAVE_DOT               = NO\n\n# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed\n# to run in parallel. When set to 0 doxygen will base this on the number of\n# processors available in the system. You can set it explicitly to a value\n# larger than 0 to get control over the balance between CPU load and processing\n# speed.\n# Minimum value: 0, maximum value: 32, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_NUM_THREADS        = 0\n\n# When you want a differently looking font in the dot files that doxygen\n# generates you can specify the font name using DOT_FONTNAME. You need to make\n# sure dot is able to find the font, which can be done by putting it in a\n# standard location or by setting the DOTFONTPATH environment variable or by\n# setting DOT_FONTPATH to the directory containing the font.\n# The default value is: Helvetica.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTNAME           = Helvetica\n\n# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of\n# dot graphs.\n# Minimum value: 4, maximum value: 24, default value: 10.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTSIZE           = 10\n\n# By default doxygen will tell dot to use the default font as specified with\n# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set\n# the path where dot can find it using this tag.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTPATH           =\n\n# If the CLASS_GRAPH tag is set to YES (or GRAPH) then doxygen will generate a\n# graph for each documented class showing the direct and indirect inheritance\n# relations. In case HAVE_DOT is set as well dot will be used to draw the graph,\n# otherwise the built-in generator will be used. If the CLASS_GRAPH tag is set\n# to TEXT the direct and indirect inheritance relations will be shown as texts /\n# links.\n# Possible values are: NO, YES, TEXT and GRAPH.\n# The default value is: YES.\n\nCLASS_GRAPH            = YES\n\n# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a\n# graph for each documented class showing the direct and indirect implementation\n# dependencies (inheritance, containment, and class references variables) of the\n# class with other documented classes.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCOLLABORATION_GRAPH    = YES\n\n# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for\n# groups, showing the direct groups dependencies.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGROUP_GRAPHS           = YES\n\n# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and\n# collaboration diagrams in a style similar to the OMG's Unified Modeling\n# Language.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nUML_LOOK               = NO\n\n# If the UML_LOOK tag is enabled, the fields and methods are shown inside the\n# class node. If there are many fields or methods and many nodes the graph may\n# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the\n# number of items for each type to make the size more manageable. Set this to 0\n# for no limit. Note that the threshold may be exceeded by 50% before the limit\n# is enforced. So when you set the threshold to 10, up to 15 fields may appear,\n# but if the number exceeds 15, the total amount of fields shown is limited to\n# 10.\n# Minimum value: 0, maximum value: 100, default value: 10.\n# This tag requires that the tag UML_LOOK is set to YES.\n\nUML_LIMIT_NUM_FIELDS   = 10\n\n# If the DOT_UML_DETAILS tag is set to NO, doxygen will show attributes and\n# methods without types and arguments in the UML graphs. If the DOT_UML_DETAILS\n# tag is set to YES, doxygen will add type and arguments for attributes and\n# methods in the UML graphs. If the DOT_UML_DETAILS tag is set to NONE, doxygen\n# will not generate fields with class member information in the UML graphs. The\n# class diagrams will look similar to the default class diagrams but using UML\n# notation for the relationships.\n# Possible values are: NO, YES and NONE.\n# The default value is: NO.\n# This tag requires that the tag UML_LOOK is set to YES.\n\nDOT_UML_DETAILS        = NO\n\n# The DOT_WRAP_THRESHOLD tag can be used to set the maximum number of characters\n# to display on a single line. If the actual line length exceeds this threshold\n# significantly it will wrapped across multiple lines. Some heuristics are apply\n# to avoid ugly line breaks.\n# Minimum value: 0, maximum value: 1000, default value: 17.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_WRAP_THRESHOLD     = 17\n\n# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and\n# collaboration graphs will show the relations between templates and their\n# instances.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nTEMPLATE_RELATIONS     = NO\n\n# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to\n# YES then doxygen will generate a graph for each documented file showing the\n# direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDE_GRAPH          = YES\n\n# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are\n# set to YES then doxygen will generate a graph for each documented file showing\n# the direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDED_BY_GRAPH      = YES\n\n# If the CALL_GRAPH tag is set to YES then doxygen will generate a call\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable call graphs for selected\n# functions only using the \\callgraph command. Disabling a call graph can be\n# accomplished by means of the command \\hidecallgraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALL_GRAPH             = NO\n\n# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable caller graphs for selected\n# functions only using the \\callergraph command. Disabling a caller graph can be\n# accomplished by means of the command \\hidecallergraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALLER_GRAPH           = NO\n\n# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical\n# hierarchy of all classes instead of a textual one.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGRAPHICAL_HIERARCHY    = YES\n\n# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the\n# dependencies a directory has on other directories in a graphical way. The\n# dependency relations are determined by the #include relations between the\n# files in the directories.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDIRECTORY_GRAPH        = YES\n\n# The DIR_GRAPH_MAX_DEPTH tag can be used to limit the maximum number of levels\n# of child directories generated in directory dependency graphs by dot.\n# Minimum value: 1, maximum value: 25, default value: 1.\n# This tag requires that the tag DIRECTORY_GRAPH is set to YES.\n\nDIR_GRAPH_MAX_DEPTH    = 1\n\n# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images\n# generated by dot. For an explanation of the image formats see the section\n# output formats in the documentation of the dot tool (Graphviz (see:\n# http://www.graphviz.org/)).\n# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order\n# to make the SVG files visible in IE 9+ (other browsers do not have this\n# requirement).\n# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,\n# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and\n# png:gdiplus:gdiplus.\n# The default value is: png.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_IMAGE_FORMAT       = png\n\n# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to\n# enable generation of interactive SVG images that allow zooming and panning.\n#\n# Note that this requires a modern browser other than Internet Explorer. Tested\n# and working are Firefox, Chrome, Safari, and Opera.\n# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make\n# the SVG files visible. Older versions of IE do not have SVG support.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINTERACTIVE_SVG        = NO\n\n# The DOT_PATH tag can be used to specify the path where the dot tool can be\n# found. If left blank, it is assumed the dot tool can be found in the path.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_PATH               =\n\n# The DOTFILE_DIRS tag can be used to specify one or more directories that\n# contain dot files that are included in the documentation (see the \\dotfile\n# command).\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOTFILE_DIRS           =\n\n# The MSCFILE_DIRS tag can be used to specify one or more directories that\n# contain msc files that are included in the documentation (see the \\mscfile\n# command).\n\nMSCFILE_DIRS           =\n\n# The DIAFILE_DIRS tag can be used to specify one or more directories that\n# contain dia files that are included in the documentation (see the \\diafile\n# command).\n\nDIAFILE_DIRS           =\n\n# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the\n# path where java can find the plantuml.jar file or to the filename of jar file\n# to be used. If left blank, it is assumed PlantUML is not used or called during\n# a preprocessing step. Doxygen will generate a warning when it encounters a\n# \\startuml command in this case and will not generate output for the diagram.\n\nPLANTUML_JAR_PATH      =\n\n# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a\n# configuration file for plantuml.\n\nPLANTUML_CFG_FILE      =\n\n# When using plantuml, the specified paths are searched for files specified by\n# the !include statement in a plantuml block.\n\nPLANTUML_INCLUDE_PATH  =\n\n# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes\n# that will be shown in the graph. If the number of nodes in a graph becomes\n# larger than this value, doxygen will truncate the graph, which is visualized\n# by representing a node as a red box. Note that doxygen if the number of direct\n# children of the root node in a graph is already larger than\n# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that\n# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.\n# Minimum value: 0, maximum value: 10000, default value: 50.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_GRAPH_MAX_NODES    = 50\n\n# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs\n# generated by dot. A depth value of 3 means that only nodes reachable from the\n# root by following a path via at most 3 edges will be shown. Nodes that lay\n# further from the root node will be omitted. Note that setting this option to 1\n# or 2 may greatly reduce the computation time needed for large code bases. Also\n# note that the size of a graph can be further restricted by\n# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.\n# Minimum value: 0, maximum value: 1000, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nMAX_DOT_GRAPH_DEPTH    = 0\n\n# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent\n# background. This is disabled by default, because dot on Windows does not seem\n# to support this out of the box.\n#\n# Warning: Depending on the platform used, enabling this option may lead to\n# badly anti-aliased labels on the edges of a graph (i.e. they become hard to\n# read).\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_TRANSPARENT        = NO\n\n# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output\n# files in one run (i.e. multiple -o and -T options on the command line). This\n# makes dot run faster, but since only newer versions of dot (>1.8.10) support\n# this, this feature is disabled by default.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_MULTI_TARGETS      = NO\n\n# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page\n# explaining the meaning of the various boxes and arrows in the dot generated\n# graphs.\n# Note: This tag requires that UML_LOOK isn't set, i.e. the doxygen internal\n# graphical representation for inheritance and collaboration diagrams is used.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGENERATE_LEGEND        = YES\n\n# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate\n# files that are used to generate the various graphs.\n#\n# Note: This setting is not only used for dot files but also for msc temporary\n# files.\n# The default value is: YES.\n\nDOT_CLEANUP            = YES\n"
  },
  {
    "path": "Program.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\n\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\n\nusing CommandLine;\nusing CommandLine.Text;\n\nnamespace cminor\n{\n    /// <summary> 整个验证工具的入口类 </summary>\n    class Program\n    {\n        class Options\n        {\n            [Option(\"source\",\n                Required = true,\n                HelpText = \"The source file of CMinor language (recommended with filename extension '.c').\")]\n            public string sourcePath { get; set; } = default!;\n\n            [Option(\"printCFG\",\n                Required = false,\n                HelpText = \"The file (or 'console') to which the control flow graph is printed.\")]\n            public string? CFGFile { get; set; } = null;\n\n            [Usage(ApplicationAlias = \"cminor\")]\n            public static IEnumerable<Example> Examples\n            {\n                get\n                {\n                    return new List<Example>()\n                    {\n                        new Example(\"The simplest usage to compile and verify a pi source file\", new Options\n                        {\n                            sourcePath = \"<path>\"\n                        })\n                    };\n                }\n            }\n        }\n\n        /// <summary> 整个验证工具的入口函数 </summary>\n        static void Main(string[] args)\n        {\n            CommandLine.Parser.Default.ParseArguments<Options>(args)\n                .WithParsed(RunOptions);\n        }\n\n        /// <summary> 整个验证工具的主驱动函数 </summary>\n        /// <remarks>\n        /// 返回码的设计是这样的：\n        /// <list type=\"bullet\">\n        ///     <item> 0 表示验证成功 </item>\n        ///     <item> 1 表示验证失败 </item>\n        ///     <item> 2 表示语义错误 </item>\n        ///     <item> 3 表示语法错误 </item>\n        /// </list>\n        /// </remarks>\n        static void RunOptions(Options opts)\n        {\n            try\n            {\n                // 首先，我们要生成 cfg！\n\n                StreamReader reader = File.OpenText(opts.sourcePath);\n\n                AntlrInputStream stream = new AntlrInputStream(reader);\n\n                ITokenSource lexer = new CMinorLexer(stream);\n\n                ITokenStream tokens = new CommonTokenStream(lexer);\n\n                CMinorParser parser = new CMinorParser(tokens);\n\n                // 由于现有的 error listener 或者 handler，\n                // 要么不会终止 parse，要么连行号都不会打印出来……\n                // 所以我们需要写一个新的 listener！\n                parser.RemoveErrorListeners();\n                parser.AddErrorListener(new ThrowingErrorListener());\n\n                CMinorParser.MainContext tree = parser.main();\n                CFGGenerator generator = new CFGGenerator();\n                IRMain cfg = generator.Apply(tree);\n\n                if (opts.CFGFile != null)\n                {\n                    // 输出 cfg\n                    using (TextWriter writer = opts.CFGFile == \"console\"\n                        ? Console.Out\n                        : new StreamWriter(opts.CFGFile))\n                    {\n                        cfg.Print(writer);\n                    }\n                }\n\n                Verifier verifier = new Verifier(Console.Out);\n\n                int result = verifier.Apply(cfg);\n                if (result > 0) Console.WriteLine(\"VERIFIED\");\n                else if (result == 0) Console.WriteLine(\"UNKNOWN\");\n                else if (result < 0) Console.WriteLine(\"UNVERIFIED\");\n\n                Environment.Exit(0);\n            }\n            catch (ParsingException e)\n            {\n                Console.Error.WriteLine($\"semantic error: {e.Message}\");\n                Environment.Exit(1);\n            }\n            catch (ParseCanceledException e)\n            {\n                Console.Error.WriteLine($\"syntax error: {e.Message}\");\n                Environment.Exit(1);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "backend/BasicPath.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.Diagnostics.Contracts;\nusing System.Collections.Generic;\n\nnamespace cminor\n{\n    class BasicPath\n    {\n        public List<Expression> headConditions = new List<Expression>();\n        public List<Expression> headRankingFunctions = new List<Expression>();\n\n        // only assumement, assignment are allowed\n        public List<Statement> statements = new List<Statement>();\n\n        public List<Expression> tailConditions = new List<Expression>();\n\n        public List<Expression> tailRankingFunctions = new List<Expression>();\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            foreach (Expression headCondition in headConditions)\n                Contract.Invariant(headCondition.type is BoolType);\n        }\n    }\n}"
  },
  {
    "path": "backend/CounterModel.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.IO;\nusing System.Collections.Generic;\n\nnamespace cminor\n{\n    class CounterModel\n    {\n        // 一个比较悲哀的事实是，由于 SMT solver 对 array 的处理方式是将其看做是一个特殊的\n        // uninterpreted function，所以在其 model 中可能会是一个比较复杂的表达式。\n        // 因此，这里我们没有办法比较好地处理 assign，只能将其都转为字符串。作为一个只是能打印\n        // 出来（或许对同学们来说还是非常难以理解的……）的字符串。\n        Dictionary<string, string> assignments = default!;\n\n        public CounterModel(Dictionary<string, string> assignments)\n        {\n            this.assignments = assignments;\n        }\n\n        /// <summary> 将这个反例模型打印出来。 </summary>\n        /// <remarks> 打印的头尾信息是尽量和 Boogie 保持一致的。 </remarks>\n        public void Print(TextWriter writer)\n        {\n            writer.WriteLine(\"*** COUNTER MODEL\");\n            foreach ((string name, string assignment) in assignments)\n            {\n                writer.WriteLine($\"{name} = {assignment}\");\n            }\n            writer.WriteLine(\"*** END COUNTER MODEL\");\n        }\n    }\n}"
  },
  {
    "path": "backend/SMTSolver.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.Collections.Generic;\n\nnamespace cminor\n{\n    /// <summary> 对真正的 SMT Solver 的一层封装 </summary>\n    /// <remarks> \n    /// 不过我们目前还只支持 z3。。。\n    /// 之后会考虑支持 cvc5，以及把这一层封装也换成更成熟的封装。\n    /// </remarks>\n    class SMTSolver\n    {\n        Dictionary<string, Expression> predicates = new Dictionary<string, Expression>();\n\n        Z3Solver z3Solver = new Z3Solver();\n\n\n        /// <summary> 检查逻辑表达式的有效性 </summary>\n        /// <param name=\"expression\"> 待检查的逻辑表达式 </param>\n        /// <returns> 为 null 的话就表示 valid，否则返回一个反例模型。 </returns>\n        public CounterModel? CheckValid(Expression expression)\n        {\n            return z3Solver.CheckValid(expression);\n        }\n\n        /// <summary> 在 SMT solver 中定义谓词 </summary>\n        /// <param name=\"predicate\"> 待定义的谓词 </param>\n        /// <remarks> 目前我们只允许一个表达式作为谓词，而且谓词不允许递归调用。 </remarks>\n        public void definePredicate(Predicate predicate)\n        {\n            z3Solver.definePredicate(predicate);\n        }\n    }\n}"
  },
  {
    "path": "backend/Verifier.cs",
    "content": "\n/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\n/*\n    TODO: 这是你唯一允许编辑的文件，你可以对此文件作任意的修改，只要整个项目可以正常地跑起来。\n*/\n\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Collections.Generic;\n\nusing System.IO;\n\nnamespace cminor\n{\n    /// <summary> 一个验证器，接受一个中间表示，判断其是否有效。 </summary>\n    class Verifier\n    {\n        SMTSolver solver = new SMTSolver();\n        TextWriter writer;\n\n        public Verifier(TextWriter writer)\n        {\n            this.writer = writer;\n        }\n\n        /// <summary> 应用此验证器 </summary>\n        /// <param name=\"cfg\"> 待验证的控制流图 </param>\n        /// <returns> 验证结果 </returns>\n        /// <list type=\"bullet\">\n        ///     <item> “&gt; 0” 表示所有的 specification 都成立 </item>\n        ///     <item> “&lt; 0” 表示有一个 specification 不成立 </item>\n        ///     <item> “= 0” 表示 unknown </item>\n        /// </list>\n        public int Apply(IRMain cfg)\n        {\n            return 0;\n        }\n    }\n}\n\n"
  },
  {
    "path": "backend/Z3Solver.cs",
    "content": "/* Copyright 2022 Xingyu Xie, Jiangyi Liu\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System;\nusing System.Linq;\nusing System.Diagnostics;\nusing System.Collections.Generic;\n\nusing Microsoft.Z3;\n\nnamespace cminor\n{\n    /// <summary> 对 Z3 求解器的一层封装 </summary>\n    class Z3Solver\n    {\n        Context ctx = new Context(new Dictionary<string, string>() {\n            { \"model\", \"true\" }\n        });\n\n        public Z3Solver()\n        {\n            Microsoft.Z3.Global.SetParameter(\"parallel.enable\", \"false\");\n        }\n\n        /// <summary> 对逻辑表达式的有效性的检查。 </summary>\n        /// <param name=\"expression\"> 待检查有效性的逻辑表达式 </param>\n        /// <returns> 如果表达式有效，那么就返回 null；否则的话，返回一个反例模型。</returns>\n        public CounterModel? CheckValid(Expression expression)\n        {\n            Solver solver = ctx.MkSolver();\n\n            Expr expr = ExpressionToZ3Expr(expression).Simplify();\n            Debug.Assert(expr is BoolExpr);\n\n            // Z3 默认求解的是 satisfiable\n            // 为了判断 valid，我们需要先取反\n            solver.Assert(ctx.MkNot((BoolExpr)expr));\n            Status status = solver.Check();\n            if (status == Status.UNSATISFIABLE)\n            {\n                return null;\n            }\n            else\n            {\n                Dictionary<string, string> assignments = new Dictionary<string, string>();\n                foreach ((FuncDecl decl, Expr valueExpr) in solver.Model.Consts)\n                {\n                    assignments.Add(decl.Name.ToString(), valueExpr.ToString());\n                }\n                return new CounterModel(assignments);\n            }\n        }\n\n        /// <summary> 把我们的 IR 里的表达式转成 Z3 里的表达式 </summary>\n        /// <remarks> 注意我们的 constant 其实需要对应到 z3 里的 numeral，我们的 variable 需要对应到 z3 里的 const。</remarks>\n        Expr ExpressionToZ3Expr(Expression e)\n        {\n            switch (e)\n            {\n                case VariableExpression ve:\n                    {\n                        string name = ve.variable.name;\n                        switch (ve.variable.type)\n                        {\n                            case IntType:\n                                return ctx.MkIntConst(name);\n                            case FloatType:\n                                return ctx.MkRealConst(name);\n                            case BoolType:\n                                return ctx.MkBoolConst(name);\n                            case ArrayType at:\n                                switch (at.atomicType)\n                                {\n                                    case IntType:\n                                        return ctx.MkArrayConst(name, ctx.IntSort, ctx.IntSort);\n                                    case FloatType:\n                                        return ctx.MkArrayConst(name, ctx.IntSort, ctx.RealSort);\n                                    case BoolType:\n                                        return ctx.MkArrayConst(name, ctx.IntSort, ctx.BoolSort);\n                                    default:\n                                        throw new ArgumentException(\"there's an atomic type that is neither 'int', 'float' or 'bool'. Probably a bug occurs.\");\n                                }\n                        }\n                        break;\n                    }\n                case IntConstantExpression ice:\n                    return ctx.MkNumeral(ice.constant, ctx.IntSort);\n                case FloatConstantExpression fce:\n                    return ctx.MkReal(fce.constant.ToString());\n                case BoolConstantExpression bce:\n                    return ctx.MkBool(bce.constant);\n                case PredicateCallExpression pce:\n                    // 里面的 predicate 应该是已经被预先声明好了\n                    Debug.Assert(predicates.ContainsKey(pce.predicate));\n\n                    return predicates[pce.predicate].Item1.Substitute(\n                        from: predicates[pce.predicate].Item2,\n                        to: pce.argumentExpressions.Select(\n                            expression => ExpressionToZ3Expr(expression)).ToArray());\n                case ArrayAccessExpression aae:\n                    {\n                        Expr array = ExpressionToZ3Expr(aae.array);\n                        Expr subscript = ExpressionToZ3Expr(aae.subscript);\n\n                        Debug.Assert(array is ArrayExpr);\n\n                        return ctx.MkSelect((ArrayExpr)array, subscript);\n                    }\n                case ArrayUpdateExpression aue:\n                    {\n                        Expr array = ExpressionToZ3Expr(aue.array);\n                        Expr subscript = ExpressionToZ3Expr(aue.subscript);\n                        Expr rhs = ExpressionToZ3Expr(aue.rhs);\n\n                        Debug.Assert(array is ArrayExpr);\n\n                        return ctx.MkStore((ArrayExpr)array, subscript, rhs);\n                    }\n                case ITEExpression itee:\n                    {\n                        Expr cond = ExpressionToZ3Expr(itee.cond);\n                        Expr thenExpr = ExpressionToZ3Expr(itee.thenExpr);\n                        Expr elseExpr = ExpressionToZ3Expr(itee.elseExpr);\n\n                        Debug.Assert(cond is BoolExpr);\n\n                        return ctx.MkITE((BoolExpr)cond, thenExpr, elseExpr);\n                    }\n                case NotExpression ne:\n                    {\n                        Expr expr = ExpressionToZ3Expr(ne.expression);\n                        Debug.Assert(expr is BoolExpr);\n                        return ctx.MkNot((BoolExpr)expr);\n                    }\n                case NegExpression ne:\n                    {\n                        Expr expr = ExpressionToZ3Expr(ne.expression);\n                        Debug.Assert(expr is ArithExpr);\n                        return ctx.MkUnaryMinus((ArithExpr)expr);\n                    }\n                case BinaryExpression be:\n                    {\n                        Expr le = ExpressionToZ3Expr(be.le);\n                        Expr re = ExpressionToZ3Expr(be.re);\n\n                        switch (be)\n                        {\n                            case MultiExpression:\n                                Debug.Assert(le is ArithExpr);\n                                Debug.Assert(re is ArithExpr);\n\n                                return ctx.MkMul(new ArithExpr[] {\n                                    (ArithExpr)le,\n                                    (ArithExpr)re\n                                });\n                            case DivExpression:\n                                if (le is IntExpr li)\n                                {\n                                    if (re is IntExpr ri)\n                                    {\n                                        //             5 / 3   5 / -3   -5 / -3   -5 / 3\n                                        // C        :    1       -1        1        -1\n                                        // Euclidean:    1       -1        2        -2\n\n                                        //  (le div re) + (le >= 0 || le % re == 0 ? 0: (re > 0 ? - 1: 1))\n                                        return ctx.MkAdd(\n                                            ctx.MkDiv(li, ri),\n                                            (IntExpr)ctx.MkITE(\n                                                ctx.MkOr(\n                                                    ctx.MkGe(li, ctx.MkInt(0)),\n                                                    ctx.MkEq(ctx.MkMod(li, ri), ctx.MkInt(0))\n                                                ),\n                                                ctx.MkInt(0),\n                                                ctx.MkITE(\n                                                    ctx.MkGt(ri, ctx.MkInt(0)),\n                                                    ctx.MkInt(-1),\n                                                    ctx.MkInt(1)\n                                                )\n                                            )\n                                        );\n                                    }\n                                }\n                                else\n                                {\n                                    if (le is RealExpr lr)\n                                        if (re is RealExpr rr)\n                                            return ctx.MkDiv(lr, rr);\n                                }\n                                throw new ArgumentException(\"The type between '/' must be both 'int' or both 'real'.\");\n                            case ModExpression:\n                                Debug.Assert(le is IntExpr);\n                                Debug.Assert(re is IntExpr);\n\n                                //             5 % 3    5 % -3   -5 % -3   -5 % 3\n                                // C        :    2        2        -2        -2\n                                // Euclidean:    2        2         1         1\n\n                                // le > 0 ? (re > 0 ? (le mod re): (le mod -re) : (re > 0 ? -(le mod re): -(le mod -re))\n                                return ctx.MkITE(\n                                    ctx.MkGt((IntExpr)le, ctx.MkInt(0)),\n                                    (IntExpr)ctx.MkITE(\n                                        ctx.MkGt((IntExpr)re, ctx.MkInt(0)),\n                                        ctx.MkMod((IntExpr)le, (IntExpr)re),\n                                        ctx.MkMod((IntExpr)le, (IntExpr)ctx.MkUnaryMinus((IntExpr)re))\n                                    ),\n                                    (IntExpr)ctx.MkITE(\n                                        ctx.MkGt((IntExpr)re, ctx.MkInt(0)),\n                                        ctx.MkUnaryMinus(ctx.MkMod((IntExpr)le, (IntExpr)re)),\n                                        ctx.MkUnaryMinus(ctx.MkMod((IntExpr)le, (IntExpr)ctx.MkUnaryMinus((IntExpr)re)))\n                                    )\n                                );\n                            case AddExpression:\n                                Debug.Assert(le is ArithExpr);\n                                Debug.Assert(re is ArithExpr);\n\n                                return ctx.MkAdd(new ArithExpr[] {\n                                    (ArithExpr)le,\n                                    (ArithExpr)re\n                                });\n                            case SubExpression:\n                                Debug.Assert(le is ArithExpr);\n                                Debug.Assert(re is ArithExpr);\n\n                                return ctx.MkSub(new ArithExpr[] {\n                                    (ArithExpr)le,\n                                    (ArithExpr)re\n                                });\n                            case LTExpression:\n                                Debug.Assert(le is ArithExpr);\n                                Debug.Assert(re is ArithExpr);\n\n                                return ctx.MkLt((ArithExpr)le, (ArithExpr)re);\n                            case LEExpression:\n                                Debug.Assert(le is ArithExpr);\n                                Debug.Assert(re is ArithExpr);\n\n                                return ctx.MkLe((ArithExpr)le, (ArithExpr)re);\n                            case GTExpression:\n                                Debug.Assert(le is ArithExpr);\n                                Debug.Assert(re is ArithExpr);\n\n                                return ctx.MkGt((ArithExpr)le, (ArithExpr)re);\n                            case GEExpression:\n                                Debug.Assert(le is ArithExpr);\n                                Debug.Assert(re is ArithExpr);\n\n                                return ctx.MkGe((ArithExpr)le, (ArithExpr)re);\n                            case EQExpression:\n                                Debug.Assert(le is ArithExpr);\n                                Debug.Assert(re is ArithExpr);\n\n                                return ctx.MkEq((ArithExpr)le, (ArithExpr)re);\n                            case NEExpression:\n                                Debug.Assert(le is ArithExpr);\n                                Debug.Assert(re is ArithExpr);\n\n                                return ctx.MkNot(ctx.MkEq((ArithExpr)le, (ArithExpr)re));\n                            case AndExpression:\n                                Debug.Assert(le is BoolExpr);\n                                Debug.Assert(re is BoolExpr);\n\n                                return ctx.MkAnd(new BoolExpr[] {\n                                    (BoolExpr)le,\n                                    (BoolExpr)re\n                                });\n                            case OrExpression:\n                                Debug.Assert(le is BoolExpr);\n                                Debug.Assert(re is BoolExpr);\n\n                                return ctx.MkOr(new BoolExpr[] {\n                                    (BoolExpr)le,\n                                    (BoolExpr)re\n                                });\n                            case ImplicationExpression:\n                                Debug.Assert(le is BoolExpr);\n                                Debug.Assert(re is BoolExpr);\n\n                                return ctx.MkImplies((BoolExpr)le, (BoolExpr)re);\n                            case IffExpression:\n                                Debug.Assert(le is BoolExpr);\n                                Debug.Assert(re is BoolExpr);\n\n                                return ctx.MkIff((BoolExpr)le, (BoolExpr)re);\n                            case XorExpression:\n                                Debug.Assert(le is BoolExpr);\n                                Debug.Assert(re is BoolExpr);\n\n                                return ctx.MkXor((BoolExpr)le, (BoolExpr)re);\n                        }\n\n                        Debug.Assert(false);\n                        break;\n                    }\n                case QuantifiedExpression qe:\n                    Expr[] boundConstants = qe.vars.Values.Select<QuantifiedVariable, Expr>(\n                        variable =>\n                        {\n                            switch (variable.type)\n                            {\n                                case IntType:\n                                    return ctx.MkIntConst(variable.name);\n                                case FloatType:\n                                    return ctx.MkRealConst(variable.name);\n                                case BoolType:\n                                    return ctx.MkBoolConst(variable.name);\n                                default:\n                                    throw new ArgumentException($\"there is a type of quantified variable that is not atomic type: {variable.type}\");\n                            }\n                        }\n                    ).ToArray();\n                    Expr body = ExpressionToZ3Expr(qe.expression);\n                    if (qe is ForallQuantifiedExpression)\n                    {\n                        return ctx.MkForall(boundConstants, body);\n                    }\n                    else\n                    {\n                        Debug.Assert(qe is ExistsQuantifiedExpression);\n                        return ctx.MkExists(boundConstants, body);\n                    }\n                case LengthExpression le:\n                    {\n                        if (le.expression is VariableExpression ve)\n                        {\n                            Debug.Assert(ve.variable is ArrayVariable);\n                            ArrayVariable av = (ArrayVariable)(ve.variable);\n                            return ctx.MkIntConst(av.length.name);\n                        }\n                        else\n                        {\n                            Debug.Assert(le.expression is ArrayUpdateExpression);\n                            LocalVariable variable = ((ArrayUpdateExpression)(le.expression)).length.variable;\n                            Debug.Assert(variable.type is IntType);\n                            return ctx.MkIntConst(variable.name);\n                        }\n                    }\n            }\n            Debug.Assert(false);\n            return null;\n        }\n\n        Dictionary<Predicate, Tuple<Expr, Expr[]>> predicates = new Dictionary<Predicate, Tuple<Expr, Expr[]>>();\n\n        public void definePredicate(Predicate predicate)\n        {\n            Expr expr = ExpressionToZ3Expr(predicate.expression);\n            Expr[] paraExprs = predicate.parameters.Select<LocalVariable, Expr>(\n                (parameter) =>\n                {\n                    switch (parameter.type)\n                    {\n                        case IntType:\n                            return ctx.MkIntConst(parameter.name);\n                        case FloatType:\n                            return ctx.MkRealConst(parameter.name);\n                        case BoolType:\n                            return ctx.MkBoolConst(parameter.name);\n                        case ArrayType at:\n                            switch (at.atomicType)\n                            {\n                                case IntType:\n                                    return ctx.MkArrayConst(parameter.name, ctx.IntSort, ctx.IntSort);\n                                case FloatType:\n                                    return ctx.MkArrayConst(parameter.name, ctx.IntSort, ctx.RealSort);\n                                case BoolType:\n                                    return ctx.MkArrayConst(parameter.name, ctx.IntSort, ctx.BoolSort);\n                                default:\n                                    throw new ArgumentException(\"there's an atomic type that is neither 'int', 'float' or 'bool'. Probably a bug occurs.\");\n                            }\n                        default:\n                            throw new ArgumentException($\"the type of parameter of {predicate.name} is neither int, float nor bool.\");\n                    }\n                }\n            ).ToArray();\n\n            predicates.Add(predicate, Tuple.Create(expr, paraExprs));\n        }\n    }\n}"
  },
  {
    "path": "cminor.csproj",
    "content": "<Project Sdk=\"Microsoft.NET.Sdk\">\r\n\r\n  <PropertyGroup>\r\n    <OutputType>Exe</OutputType>\r\n    <TargetFramework>net6.0</TargetFramework>\r\n    <RootNamespace>cminor</RootNamespace>\r\n    <Antlr4UseCSharpGenerator>True</Antlr4UseCSharpGenerator>\r\n    <LangVersion>10.0</LangVersion>\r\n    <Nullable>enable</Nullable>\r\n  </PropertyGroup>\r\n\r\n  <ItemGroup>\r\n    <PackageReference Include=\"Antlr4.CodeGenerator\" Version=\"4.6.6\">\r\n      <PrivateAssets>all</PrivateAssets>\r\n      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>\r\n    </PackageReference>\r\n    <PackageReference Include=\"Antlr4.Runtime\" Version=\"4.6.6\" />\r\n    <PackageReference Include=\"CommandLineParser\" Version=\"2.8.0\" />\r\n    <PackageReference Include=\"Microsoft.Z3\" Version=\"4.8.11\" />\r\n  </ItemGroup>\r\n\r\n</Project>\r\n"
  },
  {
    "path": "cminor.sln",
    "content": "﻿\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio Version 16\r\nVisualStudioVersion = 16.0.30114.105\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"cminor\", \"cminor.csproj\", \"{D19B789C-157A-467D-A250-8BB1A6748430}\"\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tDebug|Any CPU = Debug|Any CPU\r\n\t\tRelease|Any CPU = Release|Any CPU\r\n\tEndGlobalSection\r\n\tGlobalSection(SolutionProperties) = preSolution\r\n\t\tHideSolutionNode = FALSE\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{D19B789C-157A-467D-A250-8BB1A6748430}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{D19B789C-157A-467D-A250-8BB1A6748430}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{D19B789C-157A-467D-A250-8BB1A6748430}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{D19B789C-157A-467D-A250-8BB1A6748430}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  },
  {
    "path": "exception/ParsingException.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System;\nusing Antlr4.Runtime;\n\nusing Antlr4.Runtime.Misc;\n\nnamespace cminor\n{\n    public class ParsingException : Exception\n    {\n        public ParsingException() { }\n        public ParsingException(string message) : base(message) { }\n        public ParsingException(string message, Exception inner) : base(message, inner) { }\n\n        public ParsingException([NotNull] ParserRuleContext context, string message) : base($\"({context.Start.Line}, {context.Start.Column}): {message}\")\n        { }\n    }\n}"
  },
  {
    "path": "exception/ThrowingErrorListener.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\n\nnamespace cminor\n{\n    public class ThrowingErrorListener : BaseErrorListener\n    {\n        public override void SyntaxError([NotNull] IRecognizer recognizer, [Nullable] IToken offendingSymbol, int line, int charPositionInLine, [NotNull] string msg, [Nullable] RecognitionException e)\n        {\n            throw new ParseCanceledException($\"({line}, {charPositionInLine}): {msg}\");\n        }\n    }\n}"
  },
  {
    "path": "frontend/AnnoGenerator.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\n/*\n    这里是生成 annotation 的逻辑，需要生成的 annotation 包括：\n    - precondition\n    - postcondition\n    - ranking function\n    - assertion\n*/\n\nusing System.Linq;\nusing System.Diagnostics;\nusing System.Collections.Generic;\n\nusing Antlr4.Runtime.Misc;\n\nnamespace cminor\n{\n    partial class CFGGenerator : CMinorParserBaseVisitor<Expression?>\n    {\n        public override Expression? VisitAssertion([NotNull] CMinorParser.AssertionContext context)\n        {\n            Debug.Assert(currentBlock != null);\n\n            // 尽管这里的类型应该是已经被 confirm 过一遍了，但多 confirm 一次是更加保险的选择\n            Expression pred = TypeConfirm(context.pred(), false, BoolType.Get());\n\n            currentBlock.AddStatement(new AssertStatement\n            {\n                pred = pred\n            });\n\n            return null;\n        }\n\n        PreconditionBlock\n        CalcPreconditionBlock([NotNull] CMinorParser.RequiresClauseContext[] requiresClauseContexts, CMinorParser.DecreasesClauseContext? decreasesClauseContext)\n        {\n            List<Expression> conditions = requiresClauseContexts.Select(\n                        ctx => TypeConfirm(ctx.pred(), false, BoolType.Get())).ToList();\n            List<Expression> rankingFunctions = decreasesClauseContext is null\n                ? new List<Expression>()\n                : decreasesClauseContext.arithTerm().Select(\n                        arithTerm => TypeConfirm(arithTerm, false, IntType.Get())).ToList();\n            return new PreconditionBlock\n            {\n                conditions = conditions,\n                rankingFunctions = rankingFunctions\n            };\n        }\n\n        LoopHeadBlock CalcLoopHeadBlock([NotNull] CMinorParser.LoopAnnotContext context)\n        {\n            Debug.Assert(currentFunction != null);\n            Debug.Assert(currentBlock != null);\n\n            List<Expression> invariants = new List<Expression>(\n                context.pred().Select(\n                    invariant => TypeConfirm(invariant, false, BoolType.Get())));\n            List<Expression> rankingFunctions = new List<Expression>(\n                context.arithTerm().Select(\n                    arithTerm => TypeConfirm(arithTerm, false, IntType.Get())));\n            return new LoopHeadBlock(currentFunction, currentBlock)\n            {\n                invariants = invariants,\n                rankingFunctions = rankingFunctions\n            };\n        }\n\n        PostconditionBlock CalcPostconditionBlock([NotNull] CMinorParser.EnsuresClauseContext[] contexts, List<LocalVariable> rvs)\n        {\n            // 这里我们开一个只有 \\result 的假作用域\n            var scope = rvs.ToDictionary(rv => rv.name, rv => rv);\n            symbolTables.Push(scope);\n\n            List<Expression> conditions = new List<Expression>(contexts.Select(\n                ctx => TypeConfirm(ctx.pred(), false, BoolType.Get())));\n\n            symbolTables.Pop();\n\n            return new PostconditionBlock\n            {\n                conditions = conditions\n            };\n        }\n    }\n}"
  },
  {
    "path": "frontend/CFGGenerator.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.Linq;\nusing System.Diagnostics;\nusing System.Collections.Generic;\n\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Tree;\n\nnamespace cminor\n{\n    /**\n        <summary> 最顶层的 CFG 的生成器 </summary>\n        <remarks>\n        这里是生成最顶层的 CFG 的代码。\n\n        CFG 的生成过程是在 ANTLR 生成的 CST 上做单遍的遍历，这是一个 vistor pattern。\n        但为了让代码结构更清晰，这里我们通过 C# 的 partial class 特性，\n        把 CFGGenerator 的实现拆分进了七个文件中：\n        <list type=\"bullet\">\n            <item> AnnoGenerator.cs：标注的生成 </item>\n            <item> CFGGenerator.cs：最顶层的函数定义、结构体定义、谓词定义等的生成 </item>\n            <item> DeclGenerator.cs：变量声明的生成 </item>\n            <item> ExprGenerator.cs：C 中表达式的生成 </item>\n            <item> PredGenerator.cs：标注中的谓词（逻辑表达式）的生成 </item>\n            <item> StmtGenerator.cs：语句的生成 </item>\n            <item> TermGenerator.cs：标注中的项（非逻辑表达式）的生成 </item>\n            <item> Utils.cs：一些工具函数和工具类 </item>\n        </list>\n        \n        注意：\n        <list type=\"bullet\">\n            <item> 在生成的过程中，我们是有 struct 相关的东西的，但在最终的 IR 中我们会隐藏 struct； </item>\n            <item> 目前我们考虑的语言是没有 side effect 的，这样的话，\n            不少 C 里的 unspecified behavior/undefined behavior 在我们这里是不存在的，比如 <c>a[++i] = ++i;</c>。</item>\n        </list>\n        </remarks>\n    */\n    partial class CFGGenerator : CMinorParserBaseVisitor<Expression?>\n    {\n        // 最终计算出来的 IR 主体\n        IRMain main = default!;\n\n        // 当前正在计算的 function\n        Function? currentFunction;\n        // block\n        Block? currentBlock = null;\n        // block that break statement points to\n        BasicBlock? breakBlock = null;\n        // block that continue statement points to\n        Block? contBlock = null;\n\n        // 符号表\n        Dictionary<string, Function> functionTable = new Dictionary<string, Function>();\n        Dictionary<string, Struct> structTable = new Dictionary<string, Struct>();\n        Dictionary<string, Predicate> predicateTable = new Dictionary<string, Predicate>();\n        Stack<Dictionary<string, LocalVariable>> symbolTables = new Stack<Dictionary<string, LocalVariable>>();\n\n        // 用来作 alpha renaming，以及用来生成临时变量\n        Counter counter = new Counter();\n\n        // 真正的主函数\n        public IRMain Apply([NotNull] CMinorParser.MainContext context)\n        {\n            main = new IRMain();\n            Visit(context);\n\n            // 这里我们做一个检查（约定）：ranking function 的数量在每个函数头和循环头都是相等的。\n            int rankingFunctionNum = -1; // -1 means unknown, 0 means non-existence, 1 means existence\n            foreach (Function function in functionTable.Values)\n            {\n                if (rankingFunctionNum == -1)\n                    rankingFunctionNum = function.preconditionBlock.rankingFunctions.Count;\n                if (rankingFunctionNum != function.preconditionBlock.rankingFunctions.Count)\n                    throw new ParsingException(context, \"Ranking functions should exist in all function contracts and loopheads, or not exist in all function contracts and loopheads.\");\n                foreach (Block block in function.blocks)\n                    if (block is LoopHeadBlock lhb)\n                        if (rankingFunctionNum != function.preconditionBlock.rankingFunctions.Count)\n                            throw new ParsingException(context, \"Ranking functions should exist in all function contracts and loopheads, or not exist in all function contracts and loopheads.\");\n            }\n\n            // 把函数和谓词的参数、返回值和类型“拍扁”\n            // 也就是说把 struct 消解成几个普通的变量\n            foreach (Function function in functionTable.Values)\n            {\n                // 拍扁参数及其类型\n                List<LocalVariable> flattenedParameters = new List<LocalVariable>();\n                List<VarType> flattenedParaTypes = new List<VarType>();\n                for (int i = 0; i < function.parameters.Count; ++i)\n                {\n                    if (function.parameters[i] is StructVariable structParameter)\n                    {\n                        foreach (LocalVariable member in structParameter.members.Values)\n                        {\n                            flattenedParameters.Add(member);\n                            flattenedParaTypes.Add(member.type);\n                        }\n                    }\n                    else\n                    {\n                        flattenedParameters.Add(function.parameters[i]);\n                        flattenedParaTypes.Add(function.parameters[i].type);\n                    }\n                }\n                function.parameters = flattenedParameters;\n\n                if (function.rvs.Count > 0 && function.rvs[0] is StructVariable structRV)\n                {\n                    // 拍扁返回值\n                    Debug.Assert(function.rvs.Count == 1);\n\n                    List<LocalVariable> flattenedRV = new List<LocalVariable>();\n                    foreach (LocalVariable member in structRV.members.Values)\n                    {\n                        flattenedRV.Add(member);\n                    }\n                    function.rvs = flattenedRV;\n                }\n\n                List<VarType> flattenedReturnTypes = new List<VarType>();\n                foreach (LocalVariable rv in function.rvs)\n                {\n                    flattenedReturnTypes.Add(rv.type);\n                }\n                function.type = FunType.Get(flattenedReturnTypes, flattenedParaTypes);\n            }\n            foreach (Predicate predicate in predicateTable.Values)\n            {\n                // 拍扁参数及其类型\n                List<LocalVariable> flattenedParameters = new List<LocalVariable>();\n                List<VarType> flattenedParaTypes = new List<VarType>();\n                for (int i = 0; i < predicate.parameters.Count; ++i)\n                {\n                    if (predicate.parameters[i] is StructVariable structParameter)\n                    {\n                        foreach (LocalVariable member in structParameter.members.Values)\n                        {\n                            flattenedParameters.Add(member);\n                            flattenedParaTypes.Add(member.type);\n                        }\n                    }\n                    else\n                    {\n                        flattenedParameters.Add(predicate.parameters[i]);\n                        flattenedParaTypes.Add(predicate.parameters[i].type);\n                    }\n                }\n                predicate.type = PredType.Get(flattenedParaTypes);\n                predicate.parameters = flattenedParameters;\n            }\n\n            return main;\n        }\n\n        public override Expression? VisitMain([NotNull] CMinorParser.MainContext context)\n        {\n            foreach (var def in context.def())\n                Visit(def);\n            return null;\n        }\n\n        public override Expression? VisitFuncDef([NotNull] CMinorParser.FuncDefContext context)\n        {\n            string name = CalcDefName(context, context.retVar().IDENT().Last());\n\n            // 把所有的形参加到符号表里\n            symbolTables.Push(new Dictionary<string, LocalVariable>());\n            var paraVars = new List<LocalVariable>(context.paraVar().Select(ctx => CalcParaVar(ctx)));\n            var paraTypes = new List<VarType>(paraVars.Select(var => var.type));\n\n            // 算出 returnType，如果其不是 void，那么就搞出一个 \\result 变量来\n            List<VarType> returnTypes = new List<VarType>();\n            List<LocalVariable> rvs = new List<LocalVariable>();\n            if (context.retVar().GetChild(0).GetText() != \"void\")\n            {\n                LocalVariable rv = CalcRetVar(context.retVar());\n                returnTypes.Add(rv.type);\n                rvs.Add(rv);\n            }\n\n            PreconditionBlock preconditionBlock = CalcPreconditionBlock(context.funcContract().requiresClause(), context.funcContract().decreasesClause());\n            PostconditionBlock postconditionBlock = CalcPostconditionBlock(context.funcContract().ensuresClause(), rvs);\n\n            currentFunction = new Function\n            {\n                type = FunType.Get(returnTypes, paraTypes),\n                name = name,\n                parameters = paraVars,\n                preconditionBlock = preconditionBlock,\n                postconditionBlock = postconditionBlock,\n                rvs = rvs\n            };\n            main.functions.AddLast(currentFunction);\n            functionTable.Add(name, currentFunction);\n\n            // visit function body\n            currentBlock = new BasicBlock(currentFunction, preconditionBlock);\n\n            // 逐次访问函数中的每一条语句\n            foreach (var child in context.children)\n                if (child is CMinorParser.DeclContext decl)\n                    Visit(decl);\n                else if (child is CMinorParser.StmtContext stmt)\n                    Visit(stmt);\n\n            // 理想情况下，currentBasicBlock 应该是空，这表示所有的 path 都已经被 return 了\n            if (currentBlock != null)\n            {\n                if (returnTypes.Count == 0)\n                { // 如果函数的返回值类型是 void 的话，我们是允许隐式的 return 的\n                    Block.AddEdge(currentBlock, postconditionBlock);\n                }\n                else\n                    throw new ParsingException(context, $\"function '{name}' does not return in all paths.\");\n            }\n\n            // 搞定这个函数啦~\n            symbolTables.Pop();\n\n            currentFunction = null;\n\n            return null;\n        }\n\n        public override Expression? VisitStructDef([NotNull] CMinorParser.StructDefContext context)\n        {\n            string name = CalcDefName(context, context.IDENT().First());\n\n            // parse member variables\n            var members = new SortedDictionary<string, MemberVariable>();\n            for (int i = 0; i < context.atomicType().Length; ++i)\n            {\n                string memberName = context.IDENT()[i + 1].GetText();\n                MemberVariable memberVariable = new MemberVariable\n                {\n                    type = AtomicType.FromString(context.atomicType()[i].GetText()),\n                    name = memberName\n                };\n                if (!members.ContainsKey(memberName))\n                    members.Add(memberName, memberVariable);\n                else\n                    throw new ParsingException(context, $\"duplicate struct member '{memberName}'\");\n            }\n            Struct s = new Struct(name, members);\n            structTable.Add(name, s);\n            return null;\n        }\n\n        public override Expression? VisitPredDef([NotNull] CMinorParser.PredDefContext context)\n        {\n            string name = CalcDefName(context, context.IDENT());\n\n            // calculate parameters\n            symbolTables.Push(new Dictionary<string, LocalVariable>());\n            var paraVars = new List<LocalVariable>(context.logicParaVar().Select(ctx => CalcLogicParaVar(ctx)));\n            var paraTypes = new List<VarType>(paraVars.Select(var => var.type));\n\n            Expression expression = NotNullConfirm(context.pred());\n\n            // 最后再把这个加到谓词表里，避免其表达式中有对自身的引用。\n\n            Predicate predicate = new Predicate\n            {\n                type = PredType.Get(paraTypes),\n                name = name,\n                parameters = paraVars,\n                expression = expression\n            };\n            // 这里我们需要在表达式算完之后再将谓词名放到表里，\n            // 因为函数可以递归调用自身，但是谓词是不行的\n            predicateTable.Add(name, predicate);\n            main.predicates.AddLast(predicate);\n\n            symbolTables.Pop();\n\n            return null;\n        }\n\n        // ==== utils just for top level definitions ====\n\n        string CalcDefName(ParserRuleContext context, ITerminalNode node)\n        {\n            string name = node.GetText();\n            // check if the name is used by a previous function, struct or predicate\n            if (functionTable.ContainsKey(name))\n                throw new ParsingException(context, $\"a function named '{name}' has already been defined\");\n            if (structTable.ContainsKey(name))\n                throw new ParsingException(context, $\"a struct named '{name}' has already been defined\");\n            if (predicateTable.ContainsKey(name))\n                throw new ParsingException(context, $\"a predicate named '{name}' has already been defined\");\n            return name;\n        }\n    }\n}\n"
  },
  {
    "path": "frontend/DeclGenerator.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.Diagnostics;\n\nusing Antlr4.Runtime.Misc;\n\nnamespace cminor\n{\n    partial class CFGGenerator: CMinorParserBaseVisitor<Expression?>\n    {\n        public override Expression? VisitDecl([NotNull] CMinorParser.DeclContext context)\n        {\n            Debug.Assert(currentBlock != null);\n\n            LocalVariable lv = CalcLocalVar(context.localVar());\n\n            // 遵循 C 标准，初始化表达式中可以出现正在定义的变量，\n            // 但这个变量在这个初始化表达式中的值是未定义的。\n            // 如果说有初始化表达式存在，那么其实就相当于一个赋值语句，所以也需要放到现在的 block 里。\n            if (context.expr() != null)\n                Assign(lv, context.expr());\n            \n            return null;\n        }\n    }\n}"
  },
  {
    "path": "frontend/ExprGenerator.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System;\nusing System.Diagnostics;\nusing System.Collections.Generic;\n\nusing Antlr4.Runtime.Misc;\n\nnamespace cminor\n{\n    partial class CFGGenerator : CMinorParserBaseVisitor<Expression?>\n    {\n        public override Expression VisitIdentExpr([NotNull] CMinorParser.IdentExprContext context)\n        {\n            LocalVariable variable = FindVariable(context, context.IDENT().GetText());\n            return new VariableExpression(variable);\n        }\n\n        public override Expression VisitConstExpr([NotNull] CMinorParser.ConstExprContext context)\n        {\n            return NotNullConfirm(context.constant());\n        }\n\n        public override Expression? VisitCallExpr([NotNull] CMinorParser.CallExprContext context)\n        {\n            string calledName = context.IDENT().GetText();\n            if (LocalVariableExists(calledName))\n                throw new ParsingException(context, \"call a variable that is neither function nor predicate.\");\n\n            if (!functionTable.ContainsKey(calledName))\n                throw new ParsingException(context, $\"no function named '{calledName}'\");\n\n            Debug.Assert(!predicateTable.ContainsKey(calledName));\n            Debug.Assert(currentBlock != null);\n\n            Function function = functionTable[calledName];\n\n            // 先算出参数来\n            int paraNum = function.type.paraTypes.Count;\n            if (paraNum != context.expr().Length)\n                throw new ParsingException(context, $\"the number of arguments passed to function '{calledName}' is not the same as defined.\");\n            List<LocalVariable> argumentVariables = new List<LocalVariable>();\n            for (int i = 0; i < paraNum; ++i)\n            {\n                Expression argumentExpression = TypeConfirm(context.expr()[i], true, function.type.paraTypes[i]);\n                if (argumentExpression is VariableExpression variableExpression)\n                {\n                    // 如果参数是一个 struct 的话，就把它拍扁，每个成员作为一个参数\n                    if (variableExpression.variable is StructVariable sv)\n                    {\n                        foreach (LocalVariable memberVariable in sv.members.Values)\n                        {\n                            argumentVariables.Add(memberVariable);\n                        }\n                    }\n                    else\n                    {\n                        argumentVariables.Add(variableExpression.variable);\n                    }\n                }\n                else\n                { // 如果说表达式不只是由单个变量构成的话，我们就需要为它搞一个新的临时变量。\n                    argumentVariables.Add(CompressedExpression(argumentExpression, counter.GetArg).variable);\n                }\n                Debug.Assert(argumentVariables[i] is not QuantifiedVariable);\n            }\n\n            // 把一条 function call 的 statement 加到当前的基本块里\n            FunctionCallExpression expression = new FunctionCallExpression\n            {\n                function = function,\n                argumentVariables = argumentVariables\n            };\n            if (function.type.returnTypes.Count == 0)\n            {\n                currentBlock.AddStatement(new FunctionCallStatement\n                {\n                    rhs = expression\n                });\n                // 如果返回值是 void 的话，那么就没有返回表达式。\n                // 这里其实是所有的 expression visit method 中唯一一个会返回 null 的地方。\n                return null;\n            }\n            else\n            {\n                Debug.Assert(function.type.returnTypes.Count == 1);\n\n                // 如果返回值不是 void，那么这里其实是需要添加一个 assign statement，\n                // 然后把装有函数的返回值的临时变量回传。\n                string callName = counter.GetCall(function.name);\n                List<LocalVariable> lhs = new List<LocalVariable>();\n                LocalVariable variable;\n                switch (function.type.returnTypes[0])\n                {\n                    case StructType st:\n                        // 如果返回值类型是一个 struct type，那么需要把它“拍扁”\n                        variable = new StructVariable(st, callName);\n\n                        foreach (LocalVariable member in ((StructVariable)variable).members.Values)\n                        {\n                            lhs.Add(member);\n                        }\n                        break;\n                    case ArrayType at:\n                        // 如果返回值类型是一个 array type，那么需要把长度 havoc\n                        variable = new ArrayVariable\n                        {\n                            type = at,\n                            name = callName,\n                            length = new LocalVariable\n                            {\n                                type = IntType.Get(),\n                                name = Counter.GetLength(callName)\n                            }\n                        };\n\n                        lhs.Add(variable);\n                        break;\n                    default:\n                        Debug.Assert(function.type.returnTypes[0] is VarType);\n                        variable = new LocalVariable\n                        {\n                            type = (VarType)(function.type.returnTypes[0]),\n                            name = callName\n                        };\n                        lhs.Add(variable);\n                        break;\n                }\n                currentBlock.AddStatement(new FunctionCallStatement\n                {\n                    lhs = lhs,\n                    rhs = expression\n                });\n\n                return new VariableExpression(variable);\n            }\n\n            throw new ParsingException(context, \"an undefined symbol is called.\");\n        }\n\n        public override Expression? VisitParExpr([NotNull] CMinorParser.ParExprContext context)\n        {\n            return Visit(context.expr());\n        }\n\n        public override Expression VisitArrAccessExpr([NotNull] CMinorParser.ArrAccessExprContext context)\n        {\n            Expression array = NotNullConfirm(context.expr()[0]);\n\n            Debug.Assert(currentBlock != null);\n\n            VariableExpression subscript = CompressedExpression(TypeConfirm(context.expr()[1], true, IntType.Get()), counter.GetSub);\n\n            // runtime assertion: subscript >= 0\n            currentBlock.AddStatement(new AssertStatement()\n            {\n                pred = new LEExpression(new IntConstantExpression(0), subscript)\n            });\n\n            // runtime assertion: subscript < length\n            Debug.Assert(currentBlock != null);\n            currentBlock.AddStatement(new AssertStatement()\n            {\n                pred = new LTExpression(subscript, new LengthExpression(array))\n            });\n\n            return new ArrayAccessExpression(array, subscript);\n\n            throw new ParsingException(context, $\"request for an element in a non-array expression.\");\n        }\n\n        public override Expression VisitMemExpr([NotNull] CMinorParser.MemExprContext context)\n        {\n            Expression structExpression = NotNullConfirm(context.expr());\n            string memberName = context.IDENT().GetText();\n\n            // struct 只能是变量或者函数的返回值，\n            // 函数的返回值会被用临时变量处理，\n            // 所以这里肯定会是一个局部变量。\n            if (structExpression is not VariableExpression)\n                throw new ParsingException(context, $\"request for member '{memberName}' in a non-variable expression. Probably a bug occurs.\");\n\n            // 从表达式得到变量\n            Variable structVariable = ((VariableExpression)structExpression).variable;\n            if (structVariable is not StructVariable)\n                throw new ParsingException(context, $\"request for member '{memberName}' in an expression of non-struct type '{structExpression.type}'\");\n\n            // 从变量得到定义\n            Struct structDefinition = ((StructType)(structExpression.type)).structDefinition;\n            if (!structDefinition.members.ContainsKey(memberName))\n                throw new ParsingException(context, $\"'struct {structDefinition.name}' has no member named '{memberName}'.\");\n\n            // 将成员变量转化成一个局部变量\n            MemberVariable memberVariable = structDefinition.members[memberName];\n            var members = ((StructVariable)structVariable).members;\n            if (!members.ContainsKey(memberName))\n            { // 如果之前已经转化过一次了，那么就得直接用之前转化出来的\n                members[memberName] = new LocalVariable\n                {\n                    name = structVariable.name + \"$\" + memberName,\n                    type = memberVariable.type\n                };\n            }\n\n            return new VariableExpression(members[memberName]);\n        }\n\n        public override Expression VisitUnaryExpr([NotNull] CMinorParser.UnaryExprContext context)\n        {\n            string op = context.GetChild(0).GetText();\n            switch (op)\n            {\n                case \"!\":\n                    {\n                        Expression expression = TypeConfirm(context.expr(), true, BoolType.Get());\n                        return new NotExpression(expression);\n                    }\n                case \"-\":\n                    {\n                        Expression expression = TypeConfirm(context.expr(), true, IntType.Get(), FloatType.Get());\n                        return new NegExpression(expression);\n                    }\n                default:\n                    throw new ArgumentException(\n                        message: $\"operator '{op}' is neither '!' nor '-'. Probably a bug occurs.\",\n                        paramName: nameof(op));\n            }\n        }\n\n        public override Expression VisitMulExpr([NotNull] CMinorParser.MulExprContext context)\n        {\n            string op = context.GetChild(1).GetText();\n\n            switch (op)\n            {\n                case \"*\":\n                    {\n                        Expression le = TypeConfirm(context.expr()[0], true, IntType.Get(), FloatType.Get());\n                        Expression re = TypeConfirm(context.expr()[1], true, IntType.Get(), FloatType.Get());\n                        if (!(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType))\n                            throw new ParsingException(context, \"the type of expression between '*' must be both 'int' or 'float'.\");\n                        return new MultiExpression(le, re);\n                    }\n                case \"/\":\n                    {\n                        Expression le = TypeConfirm(context.expr()[0], true, IntType.Get(), FloatType.Get());\n                        Expression re = TypeConfirm(context.expr()[1], true, IntType.Get(), FloatType.Get());\n                        if (!(le.type is FloatType && re.type is FloatType || le.type is IntType && re.type is IntType))\n                            throw new ParsingException(context, \"the type of expression between '/' must be both 'float'.\");\n\n                        Debug.Assert(currentBlock != null);\n                        re = CompressedExpression(re, counter.GetDivisor);\n                        currentBlock.AddStatement(new AssertStatement()\n                        {\n                            pred = new NEExpression(re,\n                                le.type is IntType ? new IntConstantExpression(0) : new FloatConstantExpression(0))\n                        });\n                        return new DivExpression(le, re);\n                    }\n                case \"%\":\n                    {\n                        Expression le = TypeConfirm(context.expr()[0], true, IntType.Get());\n                        Expression re = TypeConfirm(context.expr()[1], true, IntType.Get());\n\n                        Debug.Assert(currentBlock != null);\n                        re = CompressedExpression(re, counter.GetDivisor);\n                        currentBlock.AddStatement(new AssertStatement()\n                        {\n                            pred = new NEExpression(re, new IntConstantExpression(0))\n                        });\n                        return new ModExpression(le, re);\n                    }\n                default:\n                    throw new ArgumentException(\n                        message: $\"operator '{op}' is neither '*', '/', 'div' nor '%'. Probably a bug occurs.\",\n                        paramName: nameof(op));\n            }\n        }\n\n        public override Expression VisitAddExpr([NotNull] CMinorParser.AddExprContext context)\n        {\n            Expression le = TypeConfirm(context.expr()[0], true, IntType.Get(), FloatType.Get());\n            Expression re = TypeConfirm(context.expr()[1], true, IntType.Get(), FloatType.Get());\n            string op = context.GetChild(1).GetText();\n\n            if (!(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType))\n                throw new ParsingException(context, \"the type of expression between '+' or '-' must be both int or float.\");\n\n            switch (op)\n            {\n                case \"+\":\n                    return new AddExpression(le, re);\n                case \"-\":\n                    return new SubExpression(le, re);\n                default:\n                    throw new ArgumentException(\n                        message: $\"operator '{op}' is neither '+' nor '-'. Probably a bug occurs.\",\n                        paramName: nameof(op));\n            }\n        }\n\n        public override Expression VisitOrdExpr([NotNull] CMinorParser.OrdExprContext context)\n        {\n            Expression le = TypeConfirm(context.expr()[0], true, IntType.Get(), FloatType.Get());\n            Expression re = TypeConfirm(context.expr()[1], true, IntType.Get(), FloatType.Get());\n\n            if (!(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType))\n                throw new ParsingException(context, $\"the type of expression between inequality must be both int or float, while now they are '{le.type}' and '{re.type}'.\");\n\n            string op = context.GetChild(1).GetText();\n            Expression e = BinaryExpression.FromOp(op, le, re);\n            return e;\n        }\n\n        public override Expression VisitEquExpr([NotNull] CMinorParser.EquExprContext context)\n        {\n            Expression le = NotNullConfirm(context.expr()[0]);\n            Expression re = NotNullConfirm(context.expr()[1]);\n\n            if (le.type is BoolType && re.type is IntType)\n                le = new ITEExpression(le, new IntConstantExpression(1), new IntConstantExpression(0));\n            else if (le.type is IntType && re.type is BoolType)\n                re = new ITEExpression(re, new IntConstantExpression(1), new IntConstantExpression(0));\n\n            if (!(le.type is AtomicType && re.type is AtomicType && le.type == re.type))\n                throw new ParsingException(context, $\"the type of expression between '=' or '!=' must be of same atomic type, while now they are '{le.type}' and '{re.type}'.\");\n\n            string op = context.GetChild(1).GetText();\n            Expression e = BinaryExpression.FromOp(op, le, re);\n            return e;\n        }\n\n        public override Expression VisitAndExpr([NotNull] CMinorParser.AndExprContext context)\n        {\n            Expression le = TypeConfirm(context.expr()[0], true, BoolType.Get());\n            Expression re = TypeConfirm(context.expr()[1], true, BoolType.Get());\n            Expression e = new AndExpression(le, re);\n            return e;\n        }\n\n        public override Expression VisitOrExpr([NotNull] CMinorParser.OrExprContext context)\n        {\n            Expression le = TypeConfirm(context.expr()[0], true, BoolType.Get());\n            Expression re = TypeConfirm(context.expr()[1], true, BoolType.Get());\n            Expression e = new OrExpression(le, re);\n            return e;\n        }\n\n        public override Expression VisitConstant([NotNull] CMinorParser.ConstantContext context)\n        {\n            if (context.INT_CONSTANT() != null)\n                return new IntConstantExpression(int.Parse(context.INT_CONSTANT().GetText()));\n            else if (context.FLOAT_CONSTANT() != null)\n                return new FloatConstantExpression(float.Parse(context.FLOAT_CONSTANT().GetText()));\n            else if (context.GetText() == \"true\")\n                return new BoolConstantExpression(true);\n            else\n            {\n                Debug.Assert(context.GetText() == \"false\");\n                return new BoolConstantExpression(false);\n            }\n        }\n    }\n}"
  },
  {
    "path": "frontend/PredGenerator.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nusing Antlr4.Runtime.Misc;\n\nnamespace cminor\n{\n    partial class CFGGenerator : CMinorParserBaseVisitor<Expression?>\n    {\n        public override Expression VisitTruePred([NotNull] CMinorParser.TruePredContext context)\n        {\n            return new BoolConstantExpression(true);\n        }\n\n        public override Expression VisitFalsePred([NotNull] CMinorParser.FalsePredContext context)\n        {\n            return new BoolConstantExpression(false);\n        }\n\n        public override Expression VisitCmpPred([NotNull] CMinorParser.CmpPredContext context)\n        {\n            // 所有的 term 的 type 必须相同\n            var exprs = new List<Expression>();\n            for (int i = 0; i < context.ChildCount; i += 2)\n            {\n                exprs.Add(NotNullConfirm(context.arithTerm()[i >> 1]));\n                if (exprs.Last().type != exprs.First().type)\n                    throw new ParsingException(context, $\"The types of terms in CmpPred must be same, but there are {exprs.Last().type} and {exprs.First().type}.\");\n            }\n\n            var ops = new List<String>();\n            for (int i = 1; i < context.ChildCount; i += 2)\n                ops.Add(context.GetChild(i).GetText());\n            if (ops.Count > 1\n                && !(new HashSet<String>(ops)).IsSubsetOf(new HashSet<String> { \"<\", \"<=\", \"==\" })\n                && !(new HashSet<String>(ops)).IsSubsetOf(new HashSet<String> { \">\", \">=\", \"==\" }))\n                throw new ParsingException(context, $\"The directions of operators are different: {ops}\");\n\n            Expression e = BinaryExpression.FromOp(ops[0], exprs[0], exprs[1]);\n            for (int i = 1; i < ops.Count; ++i)\n                e = new AndExpression(e, BinaryExpression.FromOp(ops[i], exprs[i], exprs[i + 1]));\n            return e;\n        }\n\n        public override Expression VisitCallPred([NotNull] CMinorParser.CallPredContext context)\n        {\n            string calledName = context.IDENT().GetText();\n            if (LocalVariableExists(calledName))\n                throw new ParsingException(context, \"call a variable that is neither function nor predicate.\");\n\n            if (!predicateTable.ContainsKey(calledName))\n                throw new ParsingException(context, $\"no predicate named '{calledName}'\");\n\n            // 这种其实很简单，正常来就行啦QAQ\n            Predicate predicate = predicateTable[calledName];\n\n            // 把所有参数算出来！\n            int paraNum = predicate.type.paraTypes.Count;\n            if (paraNum != context.term().Length)\n                throw new ParsingException(context, $\"the number of arguments passed to function '{calledName}' is not the same as defined.\");\n            List<Expression> argumentExpressions = new List<Expression>();\n            for (int i = 0; i < paraNum; ++i)\n            {\n                Expression argumentExpression = TypeConfirm(context.term()[i], false, predicate.type.paraTypes[i]);\n                if (argumentExpression.type is StructType)\n                {\n                    Debug.Assert(argumentExpression is VariableExpression);\n                    Debug.Assert(((VariableExpression)argumentExpression).variable is StructVariable);\n                    foreach (LocalVariable member in ((StructVariable)(((VariableExpression)argumentExpression).variable)).members.Values)\n                    {\n                        argumentExpressions.Add(argumentExpression);\n                    }\n                }\n                else\n                {\n                    argumentExpressions.Add(argumentExpression);\n                }\n            }\n\n            return new PredicateCallExpression(predicate, argumentExpressions);\n        }\n\n        public override Expression? VisitParPred([NotNull] CMinorParser.ParPredContext context)\n        {\n            return Visit(context.pred());\n        }\n\n        public override Expression VisitConPred([NotNull] CMinorParser.ConPredContext context)\n        {\n            Expression le = TypeConfirm(context.pred()[0], false, BoolType.Get());\n            Expression re = TypeConfirm(context.pred()[1], false, BoolType.Get());\n            Expression e = new AndExpression(le, re);\n            return e;\n        }\n\n        public override Expression VisitDisPred([NotNull] CMinorParser.DisPredContext context)\n        {\n            Expression le = TypeConfirm(context.pred()[0], false, BoolType.Get());\n            Expression re = TypeConfirm(context.pred()[1], false, BoolType.Get());\n            Expression e = new OrExpression(le, re);\n            return e;\n        }\n\n        public override Expression VisitImpPred([NotNull] CMinorParser.ImpPredContext context)\n        {\n            Expression le = TypeConfirm(context.pred()[0], false, BoolType.Get());\n            Expression re = TypeConfirm(context.pred()[1], false, BoolType.Get());\n            Expression e = new ImplicationExpression(le, re);\n            return e;\n        }\n\n        public override Expression VisitIffPred([NotNull] CMinorParser.IffPredContext context)\n        {\n            Expression le = TypeConfirm(context.pred()[0], false, BoolType.Get());\n            Expression re = TypeConfirm(context.pred()[1], false, BoolType.Get());\n            Expression e = new IffExpression(le, re);\n            return e;\n        }\n\n        public override Expression VisitNegPred([NotNull] CMinorParser.NegPredContext context)\n        {\n            Expression expression = TypeConfirm(context.pred(), false, BoolType.Get());\n            Expression e = new NotExpression(expression);\n            return e;\n        }\n\n        public override Expression VisitXorPred([NotNull] CMinorParser.XorPredContext context)\n        {\n            Expression le = TypeConfirm(context.pred()[0], false, BoolType.Get());\n            Expression re = TypeConfirm(context.pred()[1], false, BoolType.Get());\n            Expression e = new XorExpression(le, re);\n            return e;\n        }\n\n        public override Expression VisitLengthPred([NotNull] CMinorParser.LengthPredContext context)\n        {\n            Debug.Assert(context.INT_CONSTANT().GetText() == \"0\");\n            LocalVariable variable = FindVariable(context, context.IDENT().GetText());\n            Expression length = TypeConfirm(context.arithTerm(), false, IntType.Get());\n            if (variable is ArrayVariable av)\n                // av.length > length\n                return new GTExpression(new LengthExpression(new VariableExpression(av)), length);\n            else\n                throw new ParsingException(context, \"try calculating the length of a non-array expression.\");\n        }\n\n        public override Expression VisitQuantiPred([NotNull] CMinorParser.QuantiPredContext context)\n        {\n            // 这里我们开一个新的作用域\n            // 当然 alpha-renaming 也是要做的\n            symbolTables.Push(new Dictionary<string, LocalVariable>());\n            Dictionary<string, QuantifiedVariable> vars = new Dictionary<string, QuantifiedVariable>();\n            foreach ((AtomicType type, List<String> names) in context.binder().Select(\n                ctx =>\n                    (\n                        AtomicType.FromString(ctx.GetChild(0).GetText()),\n                        ctx.IDENT().ToArray().Select(identContext => identContext.GetText()).ToList()\n                    )))\n            {\n                foreach (String name in names)\n                {\n                    if (vars.ContainsKey(name))\n                        throw new ParsingException(context, $\"duplicate quantified variable {name}\");\n                    QuantifiedVariable variable = new QuantifiedVariable\n                    {\n                        name = counter.GetVariable(name),\n                        type = type\n                    };\n                    symbolTables.Peek().Add(name, variable);\n                    vars.Add(name, variable);\n                }\n            }\n\n            Expression expression = TypeConfirm(context.pred(), false, BoolType.Get());\n\n            symbolTables.Pop();\n\n            if (context.GetChild(0).GetText() == \"\\\\forall\")\n                return new ForallQuantifiedExpression(vars, expression);\n            else\n            {\n                Debug.Assert(context.GetChild(0).GetText() == \"\\\\exists\");\n                return new ExistsQuantifiedExpression(vars, expression);\n            }\n        }\n    }\n}"
  },
  {
    "path": "frontend/StmtGenerator.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.Diagnostics;\nusing System.Collections.Generic;\n\nusing Antlr4.Runtime.Misc;\n\nnamespace cminor\n{\n    partial class CFGGenerator : CMinorParserBaseVisitor<Expression?>\n    {\n        public override Expression? VisitExprStmt([NotNull] CMinorParser.ExprStmtContext context)\n        {\n            Debug.Assert(currentBlock != null);\n            Debug.Assert(currentFunction != null);\n\n            // 这里的表达式的返回值在对象语言中是可以为 void 的，\n            // 也就是在元语言中可以为 null。\n            Visit(context.expr());\n\n            return null;\n        }\n\n        public override Expression? VisitIfStmt([NotNull] CMinorParser.IfStmtContext context)\n        {\n            Debug.Assert(currentBlock != null);\n            Debug.Assert(currentFunction != null);\n\n            // 先把 condition variable 算出来，如果是一个比较复杂的表达式的话，就加一个辅助变量作为 variable\n            Expression conditionExpression = CompressedExpression(TypeConfirm(context.expr(), true, BoolType.Get()), counter.GetCondition);\n\n            Block prevBlock = currentBlock;\n\n            // then-block\n            BasicBlock thenBlock = new BasicBlock(currentFunction, prevBlock);\n            currentBlock = thenBlock;\n            thenBlock.AddStatement(new AssumeStatement\n            {\n                condition = conditionExpression\n            });\n            symbolTables.Push(new Dictionary<string, LocalVariable>());\n            Visit(context.stmt()[0]);\n            symbolTables.Pop();\n            Block? visitedThenBlock = currentBlock;\n\n            // else-block\n            BasicBlock elseBlock = new BasicBlock(currentFunction, prevBlock);\n            currentBlock = elseBlock;\n            elseBlock.AddStatement(new AssumeStatement\n            {\n                condition = new NotExpression(conditionExpression)\n            });\n            if (context.stmt().Length == 2)\n            {\n                symbolTables.Push(new Dictionary<string, LocalVariable>());\n                Visit(context.stmt()[1]);\n                symbolTables.Pop();\n            }\n            Block? visitedElseBlock = currentBlock;\n\n            // 在访问过之后，相应的 block 可能为空\n            // 因为被 break 或者 return 了\n            if (visitedThenBlock != null || visitedElseBlock != null)\n            {\n                currentBlock = new BasicBlock(currentFunction);\n                if (visitedThenBlock != null)\n                    Block.AddEdge(visitedThenBlock, currentBlock);\n                if (visitedElseBlock != null)\n                    Block.AddEdge(visitedElseBlock, currentBlock);\n            }\n\n            return null;\n        }\n\n        public override Expression? VisitWhileStmt([NotNull] CMinorParser.WhileStmtContext context)\n        {\n            Debug.Assert(currentBlock != null);\n            Debug.Assert(currentFunction != null);\n\n            // calculate condition\n            LoopHeadBlock loopheadBlock = CalcLoopHeadBlock(context.loopAnnot());\n            currentBlock = loopheadBlock;\n            Block? outerContBlock = contBlock;\n            contBlock = loopheadBlock;\n\n            Expression condition = CompressedExpression(TypeConfirm(context.expr(), true, BoolType.Get()), counter.GetCondition);\n\n            // 开一个新的作用域\n            symbolTables.Push(new Dictionary<string, LocalVariable>());\n\n            // 开一个 body block\n            BasicBlock bodyBlock = new BasicBlock(currentFunction, loopheadBlock);\n            bodyBlock.AddStatement(new AssumeStatement\n            {\n                condition = condition\n            });\n\n            // 开一个 exit loop block，里面其实只有一条语句，就是 assume notCondition\n            BasicBlock exitBlock = new BasicBlock(currentFunction, loopheadBlock);\n            exitBlock.AddStatement(new AssumeStatement\n            {\n                condition = new NotExpression(condition)\n            });\n\n            // 开一个 post loop block，接在 exit loop block 后面\n            BasicBlock? outerBreakBlock = breakBlock;\n            breakBlock = new BasicBlock(currentFunction, exitBlock);\n\n            // 访问 body\n            currentBlock = bodyBlock;\n            Visit(context.stmt());\n            if (currentBlock != null)\n            {\n                Block.AddEdge(currentBlock, loopheadBlock);\n            }\n\n            // 结束循环\n            symbolTables.Pop();\n            currentBlock = breakBlock;\n            breakBlock = outerBreakBlock;\n            contBlock = outerContBlock;\n\n            return null;\n        }\n\n        /* for ( var := init ; cond ; iter)\n        \n              [init]\n                |\n     ------[loop head]------\n     |          |          |\n   [exit]  [loop body]   [cont]\n     |          |          |\n     |          -----------|\n     |\n     -----------|\n                |\n               ...\n        */\n        public override Expression? VisitForStmt([NotNull] CMinorParser.ForStmtContext context)\n        {\n            Debug.Assert(currentBlock != null);\n            Debug.Assert(currentFunction != null);\n\n            // 开作用域，但不开新的 block\n            symbolTables.Push(new Dictionary<string, LocalVariable>());\n\n            if (context.forInit() != null)\n            { // declaration and possible initialization\n                if (context.forInit().localVar() != null)\n                {\n                    LocalVariable localVariable = CalcLocalVar(context.forInit().localVar());\n                    if (context.forInit().expr() != null)\n                        Assign(localVariable, context.forInit().expr());\n                }\n                else\n                {\n                    Debug.Assert(context.forInit().assign() != null);\n                    Visit(context.forInit().assign());\n                }\n            }\n\n            // loop head block\n            LoopHeadBlock loopheadBlock = CalcLoopHeadBlock(context.loopAnnot());\n            currentBlock = loopheadBlock;\n\n            // condition\n            Expression condition = context.expr() == null\n                ? new BoolConstantExpression(true)\n                : CompressedExpression(TypeConfirm(context.expr(), true, BoolType.Get()), counter.GetCondition);\n\n            // 开一个 body block\n            BasicBlock bodyBlock = new BasicBlock(currentFunction, loopheadBlock);\n\n            // 将 condition 作为 assume 放到 body block 的首端\n            bodyBlock.AddStatement(new AssumeStatement\n            {\n                condition = condition\n            });\n\n            // 开一个 exit loop block，其中其实只有一条 assume 语句\n            BasicBlock exitBlock = new BasicBlock(currentFunction, loopheadBlock);\n            exitBlock.AddStatement(new AssumeStatement\n            {\n                condition = new NotExpression(condition)\n            });\n\n            // 开一个新的 break block，接在 exit loop block 后面\n            BasicBlock? outerBreakBlock = breakBlock;\n            breakBlock = new BasicBlock(currentFunction, exitBlock);\n\n            // 访问 body\n            currentBlock = bodyBlock;\n            Visit(context.stmt());\n\n            // cont (iter) block\n            Block? outerContBlock = contBlock;\n            contBlock = new BasicBlock(currentFunction, currentBlock);\n            Block.AddEdge(contBlock, loopheadBlock);\n            currentBlock = contBlock;\n            if (context.forIter() != null)\n            {\n                if (context.forIter().expr() != null)\n                { // 如果有 iterExpr 的话，需要放到 body block 的最末端\n                  // 我们可以无需理会它的返回表达式，因为事实上唯一有副作用的是 function call\n                  // 而我们会为 function call 自动生成语句\n                    Visit(context.forIter());\n                }\n                else\n                { // 也可能放到 iteration 位置上的不是 expr，而是一个 assign\n                    Debug.Assert(context.forIter().assign() != null);\n                    Visit(context.forIter().assign());\n                }\n            }\n\n            // 结束循环\n            symbolTables.Pop();\n            currentBlock = breakBlock;\n            breakBlock = outerBreakBlock;\n            contBlock = outerContBlock;\n\n            return null;\n        }\n\n        /* do { body } while (cond)\n           \n            [loop head] -|\n                 |       |\n                 |  [normal cont]\n                 |       |\n            [loop body] -|\n                 |\n            [loop exit]\n                 |\n         */\n        public override Expression? VisitDoStmt([NotNull] CMinorParser.DoStmtContext context)\n        {\n            Debug.Assert(currentBlock != null);\n            Debug.Assert(currentFunction != null);\n\n            // calculate condition\n            LoopHeadBlock loopheadBlock = CalcLoopHeadBlock(context.loopAnnot());\n            Block? outerContBlock = contBlock;\n            contBlock = loopheadBlock;\n\n            // 开一个新的作用域\n            symbolTables.Push(new Dictionary<string, LocalVariable>());\n\n            // 开一个 body block\n            BasicBlock bodyBlock = new BasicBlock(currentFunction, loopheadBlock);\n\n            // 开一个 exit loop block\n            BasicBlock exitBlock = new BasicBlock(currentFunction, bodyBlock);\n\n            // 开一个 post loop block，接在 exit loop block 后面\n            BasicBlock? outerBreakBlock = breakBlock;\n            breakBlock = new BasicBlock(currentFunction, exitBlock);\n\n            // 访问 body\n            currentBlock = bodyBlock;\n            Visit(context.stmt());\n            Expression condition = CompressedExpression(TypeConfirm(context.expr(), true, BoolType.Get()), counter.GetCondition);\n\n            // 就是不调 continue，正常执行地话，因为循环条件不满足，所以会走的 block\n            BasicBlock normalContBlock = new BasicBlock(currentFunction, bodyBlock);\n            normalContBlock.AddStatement(new AssumeStatement\n            {\n                condition = condition\n            });\n            Block.AddEdge(normalContBlock, loopheadBlock);\n\n            // exit loop block 里面其实只有一条语句，就是 assume not condition\n            exitBlock.AddStatement(new AssumeStatement\n            {\n                condition = new NotExpression(condition)\n            });\n\n            // 结束循环\n            symbolTables.Pop();\n            currentBlock = breakBlock;\n            breakBlock = outerBreakBlock;\n            contBlock = outerContBlock;\n\n            return null;\n        }\n\n        public override Expression? VisitBreakStmt([NotNull] CMinorParser.BreakStmtContext context)\n        {\n            Debug.Assert(currentBlock != null);\n\n            if (breakBlock == null)\n                throw new ParsingException(context, \"a break statement is not within loop.\");\n\n            Block.AddEdge(currentBlock, breakBlock);\n            currentBlock = null;\n\n            return null;\n        }\n\n        public override Expression? VisitContStmt([NotNull] CMinorParser.ContStmtContext context)\n        {\n            Debug.Assert(currentBlock != null);\n\n            if (contBlock == null)\n                throw new ParsingException(context, \"a break statement is not within loop.\");\n\n            Block.AddEdge(currentBlock, contBlock);\n            currentBlock = null;\n\n            return null;\n        }\n\n        public override Expression? VisitReturnStmt([NotNull] CMinorParser.ReturnStmtContext context)\n        {\n            Debug.Assert(currentBlock != null);\n            Debug.Assert(currentFunction != null);\n\n            if (context.expr() == null)\n            {\n                // 如果没有返回值的话，函数的返回类型也必须是 void\n                if (currentFunction.type.returnTypes.Count > 0)\n                    throw new ParsingException(context, $\"return-statement with no value, in function returning '{currentFunction.type.returnTypes}'\");\n            }\n            else\n            {\n                if (currentFunction.rvs.Count == 0)\n                    throw new ParsingException(context, $\"return-statement with a value, in function returning 'void'\");\n                Debug.Assert(currentFunction.rvs.Count == 1);\n                Assign(currentFunction.rvs[0], context.expr());\n            }\n\n            Block.AddEdge(currentBlock, currentFunction.postconditionBlock);\n            currentBlock = null;\n\n            return null;\n        }\n\n        public override Expression? VisitBlockStmt([NotNull] CMinorParser.BlockStmtContext context)\n        {\n            symbolTables.Push(new Dictionary<string, LocalVariable>());\n            foreach (var child in context.children)\n                if (child is CMinorParser.StmtContext stmt)\n                    Visit(stmt);\n                else if (child is CMinorParser.DeclContext decl)\n                    Visit(decl);\n            symbolTables.Pop();\n            return null;\n        }\n\n        public override Expression? VisitVarAssign([NotNull] CMinorParser.VarAssignContext context)\n        {\n            Debug.Assert(currentBlock != null);\n\n            string name = context.IDENT().GetText();\n            LocalVariable variable = FindVariable(context, name);\n            Assign(variable, context.expr());\n\n            return null;\n        }\n\n        public override Expression? VisitSubAssign([NotNull] CMinorParser.SubAssignContext context)\n        {\n            Debug.Assert(currentBlock != null);\n\n            LocalVariable lv = FindVariable(context, context.IDENT().GetText());\n            if (lv is ArrayVariable av)\n            {\n                VariableExpression subscript = CompressedExpression(TypeConfirm(context.expr()[0], true, IntType.Get()), counter.GetSub);\n\n                // runtime assertion: subscript >= 0\n                currentBlock.AddStatement(new AssertStatement()\n                {\n                    pred = new LEExpression(new IntConstantExpression(0), subscript)\n                });\n                // runtime assertion: subscript < length\n                if (av.length != null)\n                {\n                    currentBlock.AddStatement(new AssertStatement()\n                    {\n                        pred = new LTExpression(subscript, new LengthExpression(new VariableExpression(av)))\n                    });\n                }\n\n                Expression rhs = TypeConfirm(context.expr()[1], true, ((ArrayType)(av.type)).atomicType);\n\n                currentBlock.AddStatement(new SubscriptAssignStatement\n                {\n                    array = av,\n                    subscript = subscript,\n                    rhs = rhs\n                });\n            }\n            else\n                throw new ParsingException(context, \"request for an element in a non-array variable.\");\n            return null;\n        }\n\n        public override Expression? VisitMemAssign([NotNull] CMinorParser.MemAssignContext context)\n        {\n            Debug.Assert(currentBlock != null);\n\n            string structName = context.IDENT()[0].GetText();\n            string memberName = context.IDENT()[1].GetText();\n            Variable structVariable = FindVariable(context, structName);\n            if (structVariable is StructVariable sv)\n            {\n                if (!((StructType)(sv.type)).structDefinition.members.ContainsKey(memberName))\n                    throw new ParsingException(context, $\"'struct {structName}' has no member named '{memberName}'.\");\n                Debug.Assert(sv.members.ContainsKey(memberName));\n\n                LocalVariable variable = sv.members[memberName];\n\n                // 求出右边的表达式\n                Expression rhs = TypeConfirm(context.expr(), true, variable.type);\n\n                // 把赋值语句加到基本块里\n                currentBlock.AddStatement(new VariableAssignStatement\n                {\n                    variable = variable,\n                    rhs = rhs\n                });\n            }\n            else\n                throw new ParsingException(context, $\"request for member '{memberName}' in '{structName}', which is of non-struct type '{structVariable.type}'.\");\n            return null;\n        }\n\n        // utils only for statement generator\n\n        void Assign(LocalVariable lhsVariable, [NotNull] CMinorParser.ExprContext rhsContext)\n        {\n            Debug.Assert(currentBlock != null);\n\n            Expression rhs = TypeConfirm(rhsContext, true, lhsVariable.type);\n\n            switch (rhs.type)\n            {\n                case StructType st:\n                    Debug.Assert(lhsVariable is StructVariable);\n                    StructVariable ls = (StructVariable)lhsVariable;\n\n                    // 如果右边的表达式的类型是一个 struct 的话，\n                    // 那么它一定是 VariableExpression\n                    Debug.Assert(rhs is VariableExpression);\n                    Debug.Assert(((VariableExpression)rhs).variable is StructVariable);\n                    StructVariable rs = (StructVariable)(((VariableExpression)rhs).variable);\n\n                    // 为每一个成员单独赋值\n                    foreach (MemberVariable mv in st.structDefinition.members.Values)\n                    {\n                        Debug.Assert(ls.members.ContainsKey(mv.name));\n                        Debug.Assert(rs.members.ContainsKey(mv.name));\n                        Debug.Assert(ls.members[mv.name].type == mv.type);\n                        Debug.Assert(ls.members[mv.name].type == mv.type);\n\n                        currentBlock.AddStatement(new VariableAssignStatement\n                        {\n                            variable = ls.members[mv.name],\n                            rhs = new VariableExpression(rs.members[mv.name])\n                        });\n                    }\n                    break;\n                default:\n                    currentBlock.AddStatement(new VariableAssignStatement\n                    {\n                        variable = lhsVariable,\n                        rhs = rhs\n                    });\n                    break;\n            }\n        }\n    }\n}"
  },
  {
    "path": "frontend/Struct.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.IO;\nusing System.Collections.Generic;\n\nusing System.Diagnostics.Contracts;\n\nnamespace cminor\n{\n    /// <summary> 对 C 语言中的结构体的刻画 </summary>\n    /// <remarks> 我们把 struct 相关的放在前端这边，因为它们不会出现在最后的 IR 里。 </remarks>\n    class Struct\n    {\n        public StructType type;\n        public string name;\n\n        public SortedDictionary<string, MemberVariable> members;\n\n        public Struct(string name, SortedDictionary<string, MemberVariable> members)\n        {\n            this.name = name;\n            this.members = members;\n            this.type = StructType.Get(this);\n        }\n\n        public void Print(TextWriter writer)\n        {\n            writer.WriteLine($\"[struct] {name}\\n{{\");\n            foreach (MemberVariable member in members.Values)\n                writer.WriteLine($\"\\t{member.name}: {member.type};\");\n            writer.WriteLine(\"}}\");\n        }\n    }\n\n    /// <summary> 结构体类型 </summary>\n    sealed class StructType : VarType\n    {\n        public Struct structDefinition;\n\n        private static Dictionary<Struct, StructType> singletons = new Dictionary<Struct, StructType>();\n\n        private StructType(Struct structDefinition)\n        {\n            this.structDefinition = structDefinition;\n        }\n\n        public static StructType Get(Struct structDefinition)\n        {\n            if (!singletons.ContainsKey(structDefinition))\n            {\n                singletons.Add(structDefinition, new StructType(structDefinition));\n            }\n            return singletons[structDefinition];\n        }\n\n        public override string ToString()\n        {\n            return $\"struct {structDefinition.name}\";\n        }\n    }\n\n    /// <summary> 结构体变量 </summary>\n    class StructVariable : LocalVariable\n    {\n        public SortedDictionary<string, LocalVariable> members = new SortedDictionary<string, LocalVariable>();\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            Contract.Invariant(this.type is StructType);\n        }\n\n        public StructVariable(StructType type, string name)\n        {\n            this.type = type;\n            this.name = name;\n            foreach (MemberVariable mv in type.structDefinition.members.Values)\n            {\n                if (mv.type is ArrayType)\n                {\n                    members.Add(mv.name, new ArrayVariable\n                    {\n                        type = mv.type,\n                        name = $\"{name}${mv.name}\",\n                        length = new LocalVariable\n                        {\n                            type = IntType.Get(),\n                            name = CFGGenerator.Counter.GetLength(mv.name)\n                        }\n                    });\n                }\n                else\n                {\n                    members.Add(mv.name, new LocalVariable\n                    {\n                        type = mv.type,\n                        name = $\"{name}${mv.name}\"\n                    });\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "frontend/TermGenerator.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System;\nusing System.Diagnostics;\n\nusing Antlr4.Runtime.Misc;\n\nnamespace cminor\n{\n    partial class CFGGenerator : CMinorParserBaseVisitor<Expression?>\n    {\n        public override Expression VisitIdentTerm([NotNull] CMinorParser.IdentTermContext context)\n        {\n            LocalVariable variable = FindVariable(context, context.IDENT().GetText());\n            return new VariableExpression(variable);\n        }\n\n        public override Expression VisitResTerm([NotNull] CMinorParser.ResTermContext context)\n        {\n            LocalVariable variable = FindVariable(context, \"\\\\result\");\n            return new VariableExpression(variable);\n        }\n\n        public override Expression VisitConstTerm([NotNull] CMinorParser.ConstTermContext context)\n        {\n            return NotNullConfirm(context.logicConstant());\n        }\n\n        public override Expression? VisitParArithTerm([NotNull] CMinorParser.ParArithTermContext context)\n        {\n            return Visit(context.arithTerm());\n        }\n\n        public override Expression? VisitParTerm([NotNull] CMinorParser.ParTermContext context)\n        {\n            return Visit(context.term());\n        }\n\n        public override Expression VisitArrAccessTerm([NotNull] CMinorParser.ArrAccessTermContext context)\n        {\n            Expression array = NotNullConfirm(context.arithTerm()[0]);\n\n            Expression subscript = TypeConfirm(context.arithTerm()[1], false, IntType.Get());\n            return new ArrayAccessExpression(array, subscript);\n\n            throw new ParsingException(context, $\"request for an element in a non-array expression.\");\n        }\n\n        public override Expression VisitMemTerm([NotNull] CMinorParser.MemTermContext context)\n        {\n            Expression structExpression = NotNullConfirm(context.arithTerm());\n            string memberName = context.IDENT().GetText();\n\n            // struct 只能是变量或者函数的返回值，\n            // 函数的返回值会被用临时变量处理，\n            // 所以这里肯定会是一个局部变量。\n            if (structExpression is not VariableExpression)\n                throw new ParsingException(context, $\"request for member '{memberName}' in a non-variable expression. Probably a bug occurs.\");\n\n            // 从表达式得到变量\n            Variable structVariable = ((VariableExpression)structExpression).variable;\n            if (structVariable is not StructVariable)\n                throw new ParsingException(context, $\"request for member '{memberName}' in an expression of non-struct type '{structExpression.type}'\");\n\n            // 从变量得到定义\n            Struct structDefinition = ((StructType)(structExpression.type)).structDefinition;\n            if (!structDefinition.members.ContainsKey(memberName))\n                throw new ParsingException(context, $\"'struct {structDefinition.name}' has no member named '{memberName}'.\");\n\n            // 将成员变量转化成一个局部变量\n            MemberVariable memberVariable = structDefinition.members[memberName];\n            var members = ((StructVariable)structVariable).members;\n            if (!members.ContainsKey(memberName))\n            { // 如果之前已经转化过一次了，那么就得直接用之前转化出来的\n                members[memberName] = new LocalVariable\n                {\n                    name = structVariable.name + \"$\" + memberName,\n                    type = memberVariable.type\n                };\n            }\n\n            return new VariableExpression(members[memberName]);\n        }\n\n        public override Expression VisitUnaryTerm([NotNull] CMinorParser.UnaryTermContext context)\n        {\n            string op = context.GetChild(0).GetText();\n            switch (op)\n            {\n                case \"!\":\n                    {\n                        Expression expression = TypeConfirm(context.arithTerm(), false, BoolType.Get());\n                        return new NotExpression(expression);\n                    }\n                case \"-\":\n                    {\n                        Expression expression = TypeConfirm(context.arithTerm(), false, IntType.Get(), FloatType.Get());\n                        return new NegExpression(expression);\n                    }\n                default:\n                    throw new ArgumentException(\n                        message: $\"operator '{op}' is neither '!' nor '-'. Probably a bug occurs.\",\n                        paramName: nameof(op));\n            }\n        }\n\n        public override Expression VisitMulTerm([NotNull] CMinorParser.MulTermContext context)\n        {\n            string op = context.GetChild(1).GetText();\n\n            switch (op)\n            {\n                case \"*\":\n                    {\n                        Expression le = TypeConfirm(context.arithTerm()[0], false, IntType.Get(), FloatType.Get());\n                        Expression re = TypeConfirm(context.arithTerm()[1], false, IntType.Get(), FloatType.Get());\n                        if (!(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType))\n                            throw new ParsingException(context, \"the type of expression between '*' must be both 'int' or 'float'.\");\n                        return new MultiExpression(le, re);\n                    }\n                case \"/\":\n                    {\n                        Expression le = TypeConfirm(context.arithTerm()[0], false, IntType.Get(), FloatType.Get());\n                        Expression re = TypeConfirm(context.arithTerm()[1], false, IntType.Get(), FloatType.Get());\n                        if (!(le.type is FloatType && re.type is FloatType || le.type is IntType && re.type is IntType))\n                            throw new ParsingException(context, \"the type of expression between '/' must be both 'float'.\");\n                        return new DivExpression(le, re);\n                    }\n                case \"%\":\n                    {\n                        Expression le = TypeConfirm(context.arithTerm()[0], false, IntType.Get());\n                        Expression re = TypeConfirm(context.arithTerm()[1], false, IntType.Get());\n                        if (!(le.type is IntType && re.type is IntType))\n                            throw new ParsingException(context, \"the type of expression '%' must be both 'int'.\");\n                        return new ModExpression(le, re);\n                    }\n                default:\n                    throw new ArgumentException(\n                        message: $\"operator '{op}' is neither '*', '/', 'div' nor '%'. Probably a bug occurs.\",\n                        paramName: nameof(op));\n            }\n        }\n\n        public override Expression VisitAddTerm([NotNull] CMinorParser.AddTermContext context)\n        {\n            Expression le = TypeConfirm(context.arithTerm()[0], false, IntType.Get(), FloatType.Get());\n            Expression re = TypeConfirm(context.arithTerm()[1], false, IntType.Get(), FloatType.Get());\n\n            if (!(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType))\n                throw new ParsingException(context, \"the type of expression between '+' or '-' must be both int or float.\");\n\n            string op = context.GetChild(1).GetText();\n            Expression e = BinaryExpression.FromOp(op, le, re);\n            return e;\n        }\n\n        public override Expression VisitOrdTerm([NotNull] CMinorParser.OrdTermContext context)\n        {\n            Expression le = TypeConfirm(context.term()[0], false, IntType.Get(), FloatType.Get());\n            Expression re = TypeConfirm(context.term()[1], false, IntType.Get(), FloatType.Get());\n\n            if (!(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType))\n                throw new ParsingException(context, $\"the type of expression between inequality must be both int or float, while now they are '{le.type}' and '{re.type}'.\");\n\n            string op = context.GetChild(1).GetText();\n            Expression e = BinaryExpression.FromOp(op, le, re);\n            return e;\n        }\n\n        public override Expression VisitEquTerm([NotNull] CMinorParser.EquTermContext context)\n        {\n            Expression le = NotNullConfirm(context.term()[0]);\n            Expression re = NotNullConfirm(context.term()[1]);\n\n            if (!(le.type is AtomicType && re.type is AtomicType && le.type == re.type))\n                throw new ParsingException(context, $\"the type of expression between '=' or '!=' must be of same atomic type, while now they are '{le.type}' and '{re.type}'.\");\n\n            string op = context.GetChild(1).GetText();\n            Expression e = BinaryExpression.FromOp(op, le, re);\n            return e;\n        }\n\n        public override Expression VisitAndTerm([NotNull] CMinorParser.AndTermContext context)\n        {\n            Expression le = TypeConfirm(context.term()[0], false, BoolType.Get());\n            Expression re = TypeConfirm(context.term()[1], false, BoolType.Get());\n            Expression e = new AndExpression(le, re);\n            return e;\n        }\n\n        public override Expression VisitOrTerm([NotNull] CMinorParser.OrTermContext context)\n        {\n            Expression le = TypeConfirm(context.term()[0], false, BoolType.Get());\n            Expression re = TypeConfirm(context.term()[1], false, BoolType.Get());\n            Expression e = new OrExpression(le, re);\n            return e;\n        }\n\n        public override Expression VisitArrUpdTerm([NotNull] CMinorParser.ArrUpdTermContext context)\n        {\n            Expression array = NotNullConfirm(context.arithTerm()[0]);\n            if (array.type is ArrayType at)\n            {\n                Debug.Assert(currentBlock != null);\n\n                VariableExpression subscript = CompressedExpression(TypeConfirm(context.arithTerm()[1], false, IntType.Get()), counter.GetSub);\n\n                // runtime assertion: subscript >= 0\n                currentBlock.AddStatement(new AssertStatement()\n                {\n                    pred = new LEExpression(new IntConstantExpression(0), subscript)\n                });\n\n                Expression rhs = TypeConfirm(context.arithTerm()[2], false, ((ArrayType)(array.type)).atomicType);\n\n                // runtime assertion: subscript < length\n                currentBlock.AddStatement(new AssertStatement()\n                {\n                    pred = new LTExpression(subscript, new LengthExpression(array))\n                });\n\n                if (array is ArrayUpdateExpression aue)\n                {\n                    return new ArrayUpdateExpression(array, subscript, rhs, aue.length);\n                }\n                else if (array is VariableExpression ve && ve.variable is ArrayVariable av)\n                {\n                    return new ArrayUpdateExpression(array, subscript, rhs, new VariableExpression(av.length));\n                }\n                else\n                    throw new ArgumentException(\n                        message: \"the expression to update as array is neither single variable expression nor array update expression. Probably a bug occurs.\",\n                        paramName: nameof(array));\n            }\n            else\n                throw new ParsingException(context, $\"updating a non-array expression as it is an array.\");\n        }\n\n        public override Expression VisitLogicConstant([NotNull] CMinorParser.LogicConstantContext context)\n        {\n            if (context.INT_CONSTANT() != null)\n                return new IntConstantExpression(\n                    int.Parse(context.INT_CONSTANT().GetText()));\n            else if (context.FLOAT_CONSTANT() != null)\n                return new FloatConstantExpression(\n                    float.Parse(context.FLOAT_CONSTANT().GetText()));\n            else if (context.GetText() == \"\\\\true\")\n                return new BoolConstantExpression(true);\n            else\n            {\n                Debug.Assert(context.GetText() == \"\\\\false\");\n                return new BoolConstantExpression(false);\n            }\n        }\n    }\n}"
  },
  {
    "path": "frontend/Utils.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\n\nusing System.Diagnostics;\n\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\n\nnamespace cminor\n{\n    // 如果是专属于某一部分的 util method，就放到直接放到它的那个文件里吧QAQ\n\n    partial class CFGGenerator : CMinorParserBaseVisitor<Expression?>\n    {\n        VarType CalcType(string type, bool isArray)\n        {\n            if (AtomicType.availableNames.Contains(type))\n            { // atomic type or array type\n                AtomicType atomicType = AtomicType.FromString(type);\n                if (isArray)\n                { // array type\n                    return ArrayType.Get(atomicType);\n                }\n                else\n                { // atomic type\n                    return atomicType;\n                }\n            }\n            else\n            { // struct type\n                Debug.Assert(!isArray);\n                if (structTable.ContainsKey(type))\n                    return structTable[type].type;\n                else\n                    throw new ArgumentException($\"unknown type '{type}'.\");\n            }\n        }\n\n        LocalVariable CalcVar([NotNull] ParserRuleContext context, string name, VarType type)\n        {\n            if (symbolTables.Peek().ContainsKey(name))\n                throw new ParsingException(context, $\"duplicate declared variable {name}\");\n            string varname = counter.GetVariable(name);\n\n            LocalVariable variable;\n            if (type is StructType st)\n            {\n                variable = new StructVariable(st, varname);\n            }\n            else if (type is ArrayType at)\n            {\n                variable = new ArrayVariable\n                {\n                    type = at,\n                    name = varname,\n                    length = new LocalVariable\n                    {\n                        type = IntType.Get(),\n                        name = Counter.GetLength(name)\n                    }\n                };\n            }\n            else\n            {\n                Debug.Assert(type is AtomicType);\n                variable = new LocalVariable\n                {\n                    type = type,\n                    name = varname\n                };\n            }\n\n            // 把新建出来的变量放到符号表里并返回\n            symbolTables.Peek().Add(name, variable);\n            return variable;\n        }\n\n        LocalVariable CalcLocalVar([NotNull] CMinorParser.LocalVarContext context)\n        {\n            Debug.Assert(currentBlock != null);\n\n            string name = context.IDENT().Last().GetText();\n            VarType type = CalcType(context.IDENT().Length > 1\n                ? context.IDENT()[0].GetText()  // struct type\n                : context.GetChild(0).GetText() // other types\n            , context.ChildCount > 3);\n            LocalVariable lv = CalcVar(context, name, type);\n\n            // 对于数组来说，在声明时我们会要求指定一个 literal 作为长度。\n            if (context.INT_CONSTANT() != null)\n            {\n                Debug.Assert(lv is ArrayVariable);\n                Debug.Assert(type is ArrayType);\n\n                currentBlock.AddStatement(new VariableAssignStatement\n                {\n                    variable = ((ArrayVariable)lv).length,\n                    rhs = new IntConstantExpression(int.Parse(context.INT_CONSTANT().GetText()))\n                });\n            }\n\n            return lv;\n        }\n\n        LocalVariable CalcParaVar([NotNull] CMinorParser.ParaVarContext context)\n        {\n            string name = context.IDENT().Last().GetText();\n            VarType type = CalcType(context.IDENT().Length > 1\n                ? context.IDENT()[0].GetText()  // struct type\n                : context.GetChild(0).GetText() // other types\n            , context.ChildCount > 3);\n            return CalcVar(context, name, type);\n        }\n\n        LocalVariable CalcLogicParaVar([NotNull] CMinorParser.LogicParaVarContext context)\n        {\n            string name = context.IDENT().Last().GetText();\n            VarType type = CalcType(context.IDENT().Length > 1\n                ? context.IDENT()[0].GetText()  // struct type\n                : context.GetChild(0).GetText() // other types\n            , context.ChildCount > 3);\n            return CalcVar(context, name, type);\n        }\n\n        LocalVariable CalcRetVar([NotNull] CMinorParser.RetVarContext context)\n        {\n            VarType type = CalcType(context.IDENT().Length > 1\n                ? context.IDENT()[0].GetText()  // struct type\n                : context.GetChild(0).GetText() // other types\n            , false);\n            return CalcVar(context, \"\\\\result\", type);\n        }\n\n        Expression TypeConfirm([NotNull] ParserRuleContext context, bool boolAsInt, params Type[] intendedTypes)\n        {\n            Expression? expression = Visit(context);\n            if (expression == null)\n                throw new ParsingException(context, $\"try to use an expression of type 'void'.\");\n            foreach (Type intendedType in intendedTypes)\n                if (expression.type == intendedType)\n                    return expression;\n            if (boolAsInt)\n            {\n                if (expression.type is BoolType && intendedTypes.Contains(IntType.Get()))\n                    return new ITEExpression(expression, new IntConstantExpression(1), new IntConstantExpression(0));\n                if (expression.type is IntType && intendedTypes.Contains(BoolType.Get()))\n                    return new NEExpression(expression, new IntConstantExpression(0));\n            }\n            throw new ParsingException(context, $\"the expected types of the expression are {intendedTypes}, while the actual type is '{expression.type}'.\");\n        }\n\n        LocalVariable FindVariable([NotNull] ParserRuleContext context, string name)\n        {\n            // consider each symbol table reversely\n            foreach (var symbolTable in symbolTables)\n                if (symbolTable.ContainsKey(name))\n                {\n                    // Console.WriteLine($\"Found variable ({symbolTable[name].name}: {symbolTable[name].type}) of name {name}.\");\n\n                    return symbolTable[name];\n                }\n            throw new ParsingException(context, $\"cannot find local variable '{name}'.\");\n        }\n        bool LocalVariableExists(string name)\n        {\n            // consider each symbol table reversely\n            foreach (var symbolTable in symbolTables)\n                if (symbolTable.ContainsKey(name))\n                    return true;\n            return false;\n        }\n\n        Expression NotNullConfirm([NotNull] ParserRuleContext context)\n        {\n            Expression? expression = Visit(context);\n            if (expression != null)\n                return expression;\n            else\n                throw new ParsingException(context, $\"try to use a void expression.\");\n        }\n\n        /// <summary> 把一个表达式压缩成一个变量 </summary>\n        /// <remarks> 也就是说，添加一个辅助变量用来表示这个表达式，然后传回一个只有一个变量的表达式。 </remarks>\n        /// <param name=\"expression\"> 待压缩的表达式 </param>\n        /// <param name=\"getName\"> 用于获取辅助变量的名字的函数 </param>\n        /// <returns> 由这压缩成的变量单独构成的表达式 </returns>\n        VariableExpression CompressedExpression(Expression expression, Func<string> getName)\n        {\n            if (expression is VariableExpression ve)\n                return ve;\n            else\n            {\n                Debug.Assert(currentBlock != null);\n                LocalVariable variable = new LocalVariable\n                {\n                    type = expression.type,\n                    name = getName()\n                };\n                currentBlock.AddStatement(new VariableAssignStatement\n                {\n                    variable = variable,\n                    rhs = expression\n                });\n                return new VariableExpression(variable);\n            }\n        }\n\n        /// <summary> 一个用来作 alpha renaming 的辅助类，从 Counter 里得到的所有变量名都是全局唯一的。 </summary>\n        public class Counter\n        {\n            // 这个是用来作 alpha renaming 的，每个 function 会清空一次\n            // 局部变量作 alpha-renaming 会变成：{name}${number}\n            // 成员变量作 alpha-renaming 会变成：{structName}${number}${memberName}\n            Dictionary<string, int> variableCounter = new Dictionary<string, int>();\n            public string GetVariable(string variable)\n            {\n                int number = variableCounter.GetValueOrDefault<string, int>(variable) + 1;\n                variableCounter[variable] = number;\n                return variable + \"$\" + number;\n            }\n\n            // 我们需要为每一个函数调用搞一个临时变量\n            // 这个临时变量的名字是：_call_{variable}${number}\n            Dictionary<string, int> callCounter = new Dictionary<string, int>();\n            public string GetCall(string variable)\n            {\n                int number = callCounter.GetValueOrDefault<string, int>(variable) + 1;\n                callCounter[variable] = number;\n                return \"_call_\" + variable + \"$\" + number;\n            }\n\n            // 如果一个 condition 不是只有一个变量组成的，\n            // 那么我们需要为这个 condition 搞一个临时变量\n            // 这个临时变量的名字是：_cond${number}\n            int conditionCounter = 0;\n            public string GetCondition()\n            {\n                return \"_cond\" + \"$\" + ++conditionCounter;\n            }\n\n            // 我们也需要为每一个新数组搞一个临时变量：_array${number}\n            // 注意：这个仅用于 new 出来的数组。\n            // 有名字的数组，包括局部变量、参数或返回值，还是会被视为变量来处理。\n            int newArrayCounter = 0;\n            public string GetArray()\n            {\n                return \"_array\" + \"$\" + ++newArrayCounter;\n            }\n\n            // 我们其实也需要为每一个参数搞一个临时变量：_arg${number}\n            int newArgNumber = 0;\n            public string GetArg()\n            {\n                return \"_arg\" + \"$\" + ++newArgNumber;\n            }\n\n            // 为数组下标搞一个临时变量：_sub${number}\n            // 这是为了方便 assert 其合法性（runtime assertion）\n            int subCounter = 0;\n            public string GetSub()\n            {\n                return \"_sub\" + \"$\" + ++subCounter;\n            }\n\n            // 为数组长度搞一个临时变量：_length${name}\n            // 因为我们已知数组的变量名便是全局 unique 的，\n            // 所以长度的变量名也是全局 unique 的。\n            public static string GetLength(string variable)\n            {\n                return \"_length\" + \"$\" + variable;\n            }\n\n            // 为除数搞一个临时变量：_divisor${number}\n            // 这是为了方便 assert 其非零性\n            // 方便起见，这里我们统一考虑 /, div 和 %\n            int divisorCounter = 0;\n            public string GetDivisor()\n            {\n                return \"_divisor\" + \"$\" + ++divisorCounter;\n            }\n        }\n    }\n}"
  },
  {
    "path": "ir/Block.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.IO;\nusing System.Collections.Generic;\n\nusing System.Diagnostics.Contracts;\n\nnamespace cminor\n{\n    /// <summary> 用于表示“程序块”的抽象类。 </summary>\n    abstract class Block\n    {\n        public LinkedList<Block> predecessors = new LinkedList<Block>();\n        public LinkedList<Block> successors = new LinkedList<Block>();\n\n        static public void AddEdge(Block from, Block to)\n        {\n            from.successors.AddLast(to);\n            to.predecessors.AddLast(from);\n        }\n\n        // statements 里是可能没有东西的\n        public LinkedList<Statement> statements = new LinkedList<Statement>();\n\n        public void AddStatement(Statement statement)\n        {\n            statements.AddLast(statement);\n        }\n\n        public Block() { }\n        public Block(Function currentFunction, Block? predecessor)\n        {\n            currentFunction.blocks.AddLast(this);\n            if (predecessor != null)\n                AddEdge(predecessor, this);\n        }\n\n        public abstract void Print(TextWriter writer);\n        protected void PrintPredecessors(TextWriter writer)\n        {\n            writer.Write(\"\\tpredecessors:\");\n            foreach (Block predecessor in predecessors)\n                writer.Write(\" \" + predecessor);\n            writer.WriteLine(\"\");\n        }\n        protected void PrintSuccessors(TextWriter writer)\n        {\n            writer.Write(\"\\tsuccessors:\");\n            foreach (Block successor in successors)\n                writer.Write(\" \" + successor);\n            writer.WriteLine(\"\");\n        }\n        protected void PrintCondition(TextWriter writer, string name, Expression condition)\n        {\n            writer.Write($\"\\t{name} \");\n            condition.Print(writer);\n            writer.Write(\"\\n\");\n        }\n\n        protected void PrintStatements(TextWriter writer)\n        {\n            foreach (Statement statement in statements)\n                statement.Print(writer);\n        }\n    }\n\n    /// <summary> 基本块 </summary>\n    sealed class BasicBlock : Block\n    {\n        static int numberCounter = 0;\n        public int number { get; } = ++numberCounter;\n\n        public override void Print(TextWriter writer)\n        {\n            writer.WriteLine(this + \":\");\n\n            PrintPredecessors(writer);\n            PrintSuccessors(writer);\n\n            PrintStatements(writer);\n        }\n\n        public BasicBlock(Function currentFunction, Block? predecessor = null)\n            : base(currentFunction, predecessor) { }\n\n        public override string ToString() => $\"_BASIC#{number}\";\n    }\n\n    sealed class PostconditionBlock : Block\n    {\n        public List<Expression> conditions = new List<Expression>();\n\n        static int numberCounter = 0;\n        public int number { get; } = ++numberCounter;\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            Contract.Invariant(statements.Count == 0);\n            Contract.Invariant(predecessors.Count == 1);\n            Contract.Invariant(successors.Count == 0);\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.WriteLine(this + \":\");\n\n            PrintPredecessors(writer);\n\n            foreach (Expression condition in conditions)\n                PrintCondition(writer, \"ensures\", condition);\n        }\n\n        public override string ToString() => $\"_POSTCOND#{number}\";\n    }\n\n    /// <summary> 用于表示“头”（循环头以及函数头）的程序块的抽象类。 </summary>\n    abstract class HeadBlock : Block\n    {\n        public List<Expression> rankingFunctions = new List<Expression>();\n\n        public HeadBlock() { }\n        public HeadBlock(Function currentFunction, Block? predecessor)\n            : base(currentFunction, predecessor) { }\n\n        abstract protected void PrintRankingFunction(TextWriter writer);\n    }\n\n    /// <summary> 前置条件块，或者说函数头块，里面包括前置条件和秩函数。 </summary>\n    sealed class PreconditionBlock : HeadBlock\n    {\n        public List<Expression> conditions = new List<Expression>();\n\n        static int numberCounter = 0;\n        public int number { get; } = ++numberCounter;\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            Contract.Invariant(statements.Count == 0);\n            Contract.Invariant(predecessors.Count == 0);\n            Contract.Invariant(successors.Count == 1);\n            foreach (Expression cond in conditions)\n                Contract.Invariant(cond.type is BoolType);\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.WriteLine(this + \":\");\n\n            PrintSuccessors(writer);\n\n            foreach (Expression cond in conditions)\n                PrintCondition(writer, \"requires\", cond);\n\n            PrintRankingFunction(writer);\n        }\n\n        protected override void PrintRankingFunction(TextWriter writer)\n        {\n            writer.WriteLine(\"\\tdecreases (\");\n            foreach (Expression rankingFunction in rankingFunctions)\n            {\n                writer.Write(\"\\t\");\n                rankingFunction.Print(writer);\n                writer.WriteLine(\"\");\n            }\n            writer.WriteLine(\")\");\n        }\n\n        public override string ToString() => $\"_PRECOND#{number}\";\n    }\n\n    /// <summary> 循环头块，其中包括循环不变式和秩函数。 </summary>\n    sealed class LoopHeadBlock : HeadBlock\n    {\n        // 这里的 statements 是用来算 condition 的！\n\n        public List<Expression> invariants = new List<Expression>();\n\n        static int numberCounter = 0;\n        public int number { get; } = ++numberCounter;\n\n        public LoopHeadBlock(Function currentFunction, Block? predecessor = null)\n            : base(currentFunction, predecessor) { }\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            foreach (Expression cond in invariants)\n                Contract.Invariant(cond.type is BoolType);\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.WriteLine(this + \":\");\n\n            PrintPredecessors(writer);\n            PrintSuccessors(writer);\n\n            foreach (Expression invariant in invariants)\n                PrintCondition(writer, \"loop invariant\", invariant);\n\n            PrintRankingFunction(writer);\n\n            PrintStatements(writer);\n        }\n\n        protected override void PrintRankingFunction(TextWriter writer)\n        {\n            writer.WriteLine(\"\\tloop variant (\");\n            foreach (Expression rankingFunction in rankingFunctions)\n            {\n                writer.Write(\"\\t\");\n                rankingFunction.Print(writer);\n                writer.WriteLine(\"\");\n            }\n            writer.WriteLine(\"\");\n        }\n\n        public override string ToString() => $\"_LOOPHEAD#{number}\";\n    }\n}\n"
  },
  {
    "path": "ir/Expression.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Collections.Generic;\n\nusing System.Diagnostics;\nusing System.Diagnostics.Contracts;\n\nnamespace cminor\n{\n    /**\n        <summary>\n        我们统一来处理表达式，既包括 C 里的表达式，也包括 ACSL 里的表达式。\n        其支持三个基本功能：打印（Print）、替换（Substitute）、求表达式中的自由变量（GetFreeVariables）。\n        </summary>\n     */\n    abstract class Expression\n    {\n        public VarType type { get; protected set; } = default!;\n\n        public abstract void Print(TextWriter writer);\n\n        public abstract Expression Substitute(LocalVariable s, Expression t);\n\n        public abstract HashSet<LocalVariable> GetFreeVariables();\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            // 如果表达式的类型是 struct，那么它一定是一个 VariableExpression\n            // 注意：FunctionCallExpression 并不是 Expression 的 subclass\n            Contract.Invariant(!(type is StructType) || (this is VariableExpression));\n\n            // 如果一个 expression 是一个 array expression，当且仅当，它是一个 variable expression，并且其中的 variable 是一个 array variable\n            Contract.Invariant((type is ArrayType) == (this is VariableExpression ve && ve.variable.type is ArrayType));\n        }\n    }\n\n    sealed class VariableExpression : Expression\n    {\n        public LocalVariable variable;\n\n        public VariableExpression(LocalVariable variable)\n        {\n            this.type = variable.type;\n            this.variable = variable;\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(variable.name);\n        }\n\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            if (s == variable)\n            {\n                return t;\n            }\n            else\n            {\n                Debug.Assert(s.name != variable.name);\n                return this;\n            }\n        }\n\n        public override HashSet<LocalVariable> GetFreeVariables()\n        {\n            return new HashSet<LocalVariable> { variable };\n        }\n    }\n\n    abstract class ConstantExpression : Expression\n    {\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            return this;\n        }\n\n        public override HashSet<LocalVariable> GetFreeVariables()\n        {\n            return new HashSet<LocalVariable>();\n        }\n    }\n\n    sealed class IntConstantExpression : ConstantExpression\n    {\n        public int constant;\n\n        public IntConstantExpression(int constant)\n        {\n            this.type = IntType.Get();\n            this.constant = constant;\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(constant);\n        }\n    }\n\n    sealed class FloatConstantExpression : ConstantExpression\n    {\n        public float constant;\n\n        public FloatConstantExpression(float constant)\n        {\n            this.type = FloatType.Get();\n            this.constant = constant;\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(constant);\n        }\n    }\n\n    sealed class BoolConstantExpression : ConstantExpression\n    {\n        public bool constant;\n\n        public BoolConstantExpression(bool constant)\n        {\n            this.type = BoolType.Get();\n            this.constant = constant;\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(constant ? \"true\" : \"false\");\n        }\n    }\n\n    // 这是一个极为特殊的 expression，我们规定 expression 的类型不能为 void，\n    // 所以 function call 不能算在常规的 expression 里面。\n    // 并且，function call 只会出现在 FunctionCallStatement 这个 statement 里。\n    sealed class FunctionCallExpression\n    {\n        public Function function = default!;\n        public List<LocalVariable> argumentVariables = default!;\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            Contract.Invariant(this.argumentVariables.Count == function.type.paraTypes.Count);\n        }\n\n        public void Print(TextWriter writer)\n        {\n            writer.Write($\"{function.name}(\");\n            for (int i = 0; i < argumentVariables.Count; ++i)\n            {\n                if (i != 0) writer.Write(\", \");\n                writer.Write(argumentVariables[i].name);\n            }\n            writer.Write(\")\");\n        }\n    }\n\n    sealed class ArrayAccessExpression : Expression\n    {\n        public Expression array;\n        public Expression subscript;\n\n        public ArrayAccessExpression(Expression array, Expression subscript)\n        {\n            Debug.Assert(array.type is ArrayType);\n            Debug.Assert(subscript.type is IntType);\n\n            this.type = ((ArrayType)(array.type)).atomicType;\n            this.array = array;\n            this.subscript = subscript;\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            array.Print(writer);\n            writer.Write(\"[\");\n            subscript.Print(writer);\n            writer.Write(\"]\");\n        }\n\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            return new ArrayAccessExpression(array.Substitute(s, t), subscript.Substitute(s, t));\n        }\n\n        public override HashSet<LocalVariable> GetFreeVariables()\n        {\n            var fvs = array.GetFreeVariables();\n            fvs.UnionWith(subscript.GetFreeVariables());\n            return fvs;\n        }\n    }\n\n    sealed class ArrayUpdateExpression : Expression\n    {\n        public Expression array;\n        public Expression subscript;\n        public Expression rhs;\n\n        // The length is not actually a part of expression,\n        // but derived from the array.\n        public VariableExpression length;\n\n        public ArrayUpdateExpression(Expression array, Expression subscript, Expression rhs, VariableExpression length)\n        {\n            Debug.Assert(array.type is ArrayType);\n            Debug.Assert(subscript.type is IntType);\n            Debug.Assert(((ArrayType)(array.type)).atomicType == rhs.type);\n            Debug.Assert(length.type is IntType);\n\n            this.type = array.type;\n            this.array = array;\n            this.subscript = subscript;\n            this.rhs = rhs;\n            this.length = length;\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            array.Print(writer);\n            writer.Write(\"{\");\n            subscript.Print(writer);\n            writer.Write(\" <- \");\n            rhs.Print(writer);\n            writer.Write(\"}\");\n        }\n\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            Expression array = this.array.Substitute(s, t);\n            Expression subscript = this.subscript.Substitute(s, t);\n            Expression rhs = this.rhs.Substitute(s, t);\n\n            if (array is VariableExpression ve && ve.variable is ArrayVariable av)\n            {\n                return new ArrayUpdateExpression(array, subscript, rhs, new VariableExpression(av.length));\n            }\n            else\n            {\n                Debug.Assert(array is ArrayUpdateExpression);\n                return new ArrayUpdateExpression(array, subscript, rhs, ((ArrayUpdateExpression)array).length);\n            }\n        }\n\n        public override HashSet<LocalVariable> GetFreeVariables()\n        {\n            var fvs = array.GetFreeVariables();\n            fvs.UnionWith(subscript.GetFreeVariables());\n            fvs.UnionWith(rhs.GetFreeVariables());\n            return fvs;\n        }\n    }\n\n    sealed class ITEExpression : Expression\n    {\n        public Expression cond;\n        public Expression thenExpr, elseExpr;\n\n        public ITEExpression(Expression cond, Expression thenExpr, Expression elseExpr)\n        {\n            Debug.Assert(cond.type is BoolType);\n            Debug.Assert(thenExpr.type == elseExpr.type);\n\n            this.cond = cond;\n            this.thenExpr = thenExpr;\n            this.elseExpr = elseExpr;\n            this.type = thenExpr.type;\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            cond.Print(writer);\n            writer.Write(\" ? \");\n            thenExpr.Print(writer);\n            writer.Write(\" : \");\n            elseExpr.Print(writer);\n        }\n\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            Expression cond = this.cond.Substitute(s, t);\n            Expression thenExpr = this.thenExpr.Substitute(s, t);\n            Expression elseExpr = this.elseExpr.Substitute(s, t);\n            return new ITEExpression(cond, thenExpr, elseExpr);\n        }\n\n        public override HashSet<LocalVariable> GetFreeVariables()\n        {\n            var fvs = cond.GetFreeVariables();\n            fvs.UnionWith(thenExpr.GetFreeVariables());\n            fvs.UnionWith(elseExpr.GetFreeVariables());\n            return fvs;\n        }\n    }\n\n    abstract class UnaryExpression : Expression\n    {\n        public Expression expression = default!;\n\n        public override HashSet<LocalVariable> GetFreeVariables()\n        {\n            return expression.GetFreeVariables();\n        }\n\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            Object? result = Activator.CreateInstance(this.GetType(), new object[] {\n                expression.Substitute(s, t)\n            });\n            Debug.Assert(result != null);\n            Debug.Assert(result is Expression);\n            return (Expression)result;\n        }\n    }\n\n    sealed class NotExpression : UnaryExpression\n    {\n        public NotExpression(Expression expression)\n        {\n            Debug.Assert(expression.type is BoolType);\n            this.type = expression.type;\n            this.expression = expression;\n        }\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(\"!\");\n            expression.Print(writer);\n        }\n    }\n\n    sealed class NegExpression : UnaryExpression\n    {\n        public NegExpression(Expression expression)\n        {\n            Debug.Assert(expression.type is IntType || expression.type is FloatType);\n            this.type = expression.type;\n            this.expression = expression;\n        }\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(\"-\");\n            expression.Print(writer);\n        }\n    }\n\n    abstract class BinaryExpression : Expression\n    {\n        public Expression le = default!, re = default!;\n\n        // 由于我们删去了可能的括号，为了避免歧义，这里必须要强制加上括号\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(\"(\");\n            le.Print(writer);\n            string op = (string)this.GetType().GetMethod(\"GetOperator\")!.Invoke(null, null)!;\n            writer.Write($\" {op} \");\n            re.Print(writer);\n            writer.Write(\")\");\n        }\n\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            // 调用子类的 constructor\n            Object? result = Activator.CreateInstance(this.GetType(), new object[] {\n                le.Substitute(s, t), re.Substitute(s, t)\n            });\n            Debug.Assert(result != null);\n            Debug.Assert(result is Expression);\n            return (Expression)result;\n        }\n\n        public override HashSet<LocalVariable> GetFreeVariables()\n        {\n            HashSet<LocalVariable> fvs = le.GetFreeVariables();\n            fvs.UnionWith(re.GetFreeVariables());\n            return fvs;\n        }\n\n        public static BinaryExpression FromOp(string op, Expression le, Expression re)\n        {\n            foreach (System.Type type in typeof(BinaryExpression).Assembly.GetTypes())\n                if (type.IsSubclassOf(typeof(BinaryExpression)))\n                {\n                    if ((string)type.GetMethod(\"GetOperator\")!.Invoke(null, null)! == op)\n                    {\n                        return (BinaryExpression)type\n                                .GetConstructor(new System.Type[] { typeof(Expression), typeof(Expression) })!\n                                .Invoke(new object[] { le, re });\n                    }\n                }\n            throw new ArgumentException($\"There is no binary expression of operator '{op}'.\");\n        }\n    }\n\n    sealed class MultiExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"*\";\n\n        public MultiExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType);\n            this.type = le.type;\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class DivExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"/\";\n\n        public DivExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is FloatType && re.type is FloatType || le.type is IntType && re.type is IntType);\n            this.type = le.type;\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class ModExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"%\";\n\n        public ModExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType);\n            this.type = IntType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class AddExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"+\";\n\n        public AddExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType);\n            this.type = le.type;\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class SubExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"-\";\n\n        public SubExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType);\n            this.type = le.type;\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class LTExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"<\";\n\n        public LTExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class LEExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"<=\";\n\n        public LEExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class GTExpression : BinaryExpression\n    {\n        public static string GetOperator() => \">\";\n\n        public GTExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class GEExpression : BinaryExpression\n    {\n        public static string GetOperator() => \">=\";\n\n        public GEExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class EQExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"==\";\n\n        public EQExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType || le.type is BoolType && re.type is BoolType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class NEExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"!=\";\n\n        public NEExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is IntType && re.type is IntType || le.type is FloatType && re.type is FloatType || le.type is BoolType && re.type is BoolType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class AndExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"&&\";\n\n        public AndExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is BoolType && re.type is BoolType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class OrExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"||\";\n\n        public OrExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is BoolType && re.type is BoolType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class LengthExpression : UnaryExpression\n    {\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            Contract.Invariant(expression.type is ArrayType);\n            Contract.Invariant(expression is VariableExpression || expression is ArrayUpdateExpression);\n        }\n\n        public LengthExpression(Expression expression)\n        {\n            Debug.Assert(expression.type is ArrayType);\n            this.type = IntType.Get();\n            this.expression = expression;\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(\"\\\\length(\");\n            expression.Print(writer);\n            writer.Write(\")\");\n        }\n\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            Expression expression = this.expression.Substitute(s, t);\n            if (expression is VariableExpression ve)\n            {\n                Debug.Assert(ve.variable is ArrayVariable);\n                if (((ArrayVariable)(ve.variable)).length == s)\n                {\n                    return t;\n                }\n                else\n                {\n                    return new LengthExpression(expression);\n                }\n            }\n            else\n            {\n                Debug.Assert(expression is ArrayUpdateExpression);\n                if (((ArrayUpdateExpression)expression).length.variable == s)\n                    return t;\n                else\n                    return new LengthExpression(expression);\n            }\n        }\n    }\n\n    abstract class QuantifiedExpression : Expression\n    {\n        // notice: the key string is not alpha-renamed\n        public Dictionary<string, QuantifiedVariable> vars;\n        public Expression expression;\n\n        public QuantifiedExpression(Dictionary<string, QuantifiedVariable> vars, Expression expression)\n        {\n            this.type = BoolType.Get();\n            this.vars = vars;\n            this.expression = expression;\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write($\"(\\\\{GetQuantifier()} \");\n            bool isFirst = true;\n            foreach (var v in vars.Values)\n            {\n                if (isFirst) isFirst = false;\n                else writer.Write(\", \");\n                writer.Write($\"({v.name}: {v.type})\");\n            }\n            writer.Write(\". \");\n            expression.Print(writer);\n            writer.Write(\")\");\n        }\n\n        protected abstract string GetQuantifier();\n\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            if (vars.ContainsKey(s.name))\n            {\n                return this;\n            }\n            else\n            {\n                // 调用子类的 constructor\n                Object? result = Activator.CreateInstance(this.GetType(), new object[] {\n                    vars, expression.Substitute(s, t)\n                });\n                Debug.Assert(result != null);\n                Debug.Assert(result is Expression);\n                return (Expression)result;\n            }\n        }\n\n        public override HashSet<LocalVariable> GetFreeVariables()\n        {\n            return new HashSet<LocalVariable>();\n        }\n    }\n\n    sealed class ForallQuantifiedExpression : QuantifiedExpression\n    {\n        public ForallQuantifiedExpression(Dictionary<string, QuantifiedVariable> vars, Expression expression) : base(vars, expression) { }\n\n        protected override string GetQuantifier() => \"forall\";\n    }\n\n    sealed class ExistsQuantifiedExpression : QuantifiedExpression\n    {\n        public ExistsQuantifiedExpression(Dictionary<string, QuantifiedVariable> vars, Expression expression) : base(vars, expression) { }\n\n        protected override string GetQuantifier() => \"exists\";\n    }\n\n    sealed class ImplicationExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"==>\";\n\n        public ImplicationExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is BoolType && re.type is BoolType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class IffExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"<==>\";\n\n        public IffExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is BoolType && re.type is BoolType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class XorExpression : BinaryExpression\n    {\n        public static string GetOperator() => \"^^\";\n\n        public XorExpression(Expression le, Expression re)\n        {\n            Debug.Assert(le.type is BoolType && re.type is BoolType);\n            this.type = BoolType.Get();\n            this.le = le;\n            this.re = re;\n        }\n    }\n\n    sealed class PredicateCallExpression : Expression\n    {\n        public Predicate predicate;\n        public List<Expression> argumentExpressions;\n\n        public PredicateCallExpression(Predicate predicate, List<Expression> argumentExpressions)\n        {\n            this.type = BoolType.Get();\n            this.predicate = predicate;\n            this.argumentExpressions = argumentExpressions;\n        }\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            Contract.Invariant(this.argumentExpressions.Count == predicate.type.paraTypes.Count);\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write($\"{predicate.name}(\");\n            for (int i = 0; i < argumentExpressions.Count; ++i)\n            {\n                if (i != 0) writer.Write(\", \");\n                argumentExpressions[i].Print(writer);\n            }\n            writer.Write(\")\");\n        }\n\n        public override Expression Substitute(LocalVariable s, Expression t)\n        {\n            return new PredicateCallExpression(predicate,\n                new List<Expression>(\n                    argumentExpressions.Select(\n                        argumentExpression =>\n                            argumentExpression.Substitute(s, t))));\n        }\n\n        public override HashSet<LocalVariable> GetFreeVariables()\n        {\n            var fvs = new HashSet<LocalVariable>();\n            foreach (var ae in argumentExpressions)\n                fvs.UnionWith(ae.GetFreeVariables());\n            return fvs;\n        }\n    }\n}"
  },
  {
    "path": "ir/Statement.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.IO;\nusing System.Collections.Generic;\n\nusing System.Diagnostics.Contracts;\n\nnamespace cminor\n{\n    /**\n        <summary> 用来刻画语句的抽象类 </summary>\n        <remarks>\n        我们支持五种语句：\n        <list type=\"bullet\">\n            <item> <c>VariableAssignStatement</c>：对一个局部变量赋值 </item>\n            <item> <c>SubscriptAssignStatement</c>：对数组中的一个元素赋值 </item>\n            <item> <c>FunctionCallStatement</c>：函数调用 </item>\n            <item> <c>AssertStatement</c>：包括在 CMinor 中显式写出的 assertion 和 runtime assertion </item>\n            <item> <c>AssumeStatement</c>：只能出现在块首，表示进入这个块需要满足的条件，即控制流结构（分支及循环）的守卫条件 </item>\n        </list>\n        </remarks>\n    */\n    abstract class Statement\n    {\n        // A globally unique integer\n        // 主要是为了做谓词分析\n        public int location { get; }\n        static int currentLocation = 0;\n\n        public Statement()\n        {\n            location = ++currentLocation;\n        }\n\n        // 注意这里打印的时候一定是前面带 \\t，后面带 \\n\n        public abstract void Print(TextWriter writer);\n    }\n\n    abstract class AssignStatement : Statement\n    {\n        public Expression rhs = default!;\n\n        // 为了让事情更清晰，我们在打印这种语句时总是显示地标注一下左边的变量的类型\n    }\n\n    sealed class VariableAssignStatement : AssignStatement\n    {\n        public LocalVariable variable = default!;\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            Contract.Invariant(variable is not QuantifiedVariable);\n            Contract.Invariant(variable.type == rhs.type);\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write($\"\\t({variable.name}: {variable.type}) = \");\n            rhs.Print(writer);\n            writer.Write(\"\\n\");\n        }\n    }\n\n    sealed class SubscriptAssignStatement : AssignStatement\n    {\n        public ArrayVariable array = default!;\n        public VariableExpression subscript = default!;\n\n        [ContractInvariantMethod]\n        void ObjectInvariant()\n        {\n            Contract.Invariant(array.type is ArrayType);\n            Contract.Invariant(subscript.type is IntType);\n        }\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write($\"\\t({array.name}[\");\n            subscript.Print(writer);\n            writer.Write($\"]: {((ArrayType)(array.type)).atomicType}) := \");\n            rhs.Print(writer);\n            writer.WriteLine(\"\");\n        }\n    }\n\n    sealed class FunctionCallStatement : Statement\n    {\n        public List<LocalVariable> lhs = new List<LocalVariable>();\n        public FunctionCallExpression rhs = default!;\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(\"\\t\");\n            foreach (LocalVariable lv in lhs)\n            {\n                writer.Write(\n                    (lhs != null\n                        ? $\"({lv.name}: {lv.type})\"\n                        : \"(void)\")\n                    + \" := \");\n            }\n            rhs.Print(writer);\n            writer.WriteLine(\"\");\n        }\n    }\n\n    sealed class AssertStatement : Statement\n    {\n        public Expression pred = default!;\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(\"\\t@assert \");\n            pred.Print(writer);\n            writer.WriteLine(\"\");\n        }\n    }\n\n    sealed class AssumeStatement : Statement\n    {\n        public Expression condition = default!;\n\n        public override void Print(TextWriter writer)\n        {\n            writer.Write(\"\\tassume \");\n            condition.Print(writer);\n            writer.WriteLine(\"\");\n        }\n    }\n}"
  },
  {
    "path": "ir/TopLevel.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nusing System.IO;\nusing System.Collections.Generic;\n\nnamespace cminor\n{\n    /// <summary> IR 的最顶层，其中包含了若干函数定义和谓词定义。 </summary>\n\n    class IRMain\n    {\n        public LinkedList<Function> functions = new LinkedList<Function>();\n        public LinkedList<Predicate> predicates = new LinkedList<Predicate>();\n\n        public void Print(TextWriter writer)\n        {\n            // writer.WriteLine(\"// predicates\");\n            foreach (Predicate p in predicates)\n            {\n                p.Print(writer);\n                writer.WriteLine(\"\");\n            }\n            // writer.WriteLine(\"\");\n\n            // writer.WriteLine(\"// functions\");\n            foreach (Function f in functions)\n            {\n                f.Print(writer);\n                writer.WriteLine(\"\");\n            }\n        }\n    }\n\n\n    /// <summary> 函数的主体是若干个 block 构成的 CFG，入口块是 precondition block，出口块是 postcondition block。 </summary>\n    class Function\n    {\n        // 注意，这个 type 在 CFG 中\n        public FunType type = default!;\n\n        public string name = default!;\n        public List<LocalVariable> parameters = default!;\n\n        public PreconditionBlock preconditionBlock = default!;\n        public PostconditionBlock postconditionBlock = default!;\n\n        // All blocks except precondition block and postcondition block.\n        // For minimization we don't need the following one,\n        // this is only for convenience.\n        public LinkedList<Block> blocks = new LinkedList<Block>();\n\n        // 如果是 void，那么就为空\n        // 如果是 int, float, bool 或者 array，那么就只有一个\n        // 如果是 struct 的话，就有 struct 的成员数量那么多个\n        public List<LocalVariable> rvs = new List<LocalVariable>();\n\n        public void Print(TextWriter writer)\n        {\n            writer.Write($\"[function] (\\\\result: (\");\n            foreach (Type returnType in type.returnTypes)\n                writer.Write(returnType);\n            writer.WriteLine($\")) {name} \\n(\");\n            for (int i = 0; i < parameters.Count; ++i)\n                writer.WriteLine($\"\\t({parameters[i].name}: {parameters[i].type}),\");\n            writer.WriteLine(\")\");\n\n            preconditionBlock.Print(writer);\n            writer.WriteLine(\"\");\n            foreach (Block block in blocks)\n            {\n                block.Print(writer);\n                writer.WriteLine(\"\");\n            }\n            postconditionBlock.Print(writer);\n        }\n    }\n\n    /// <summary> 谓词的主体就是一个逻辑表达式。 </summary>\n    class Predicate\n    {\n        // a predicate can be regarded as a function,\n        // of which the return value is bool and the body\n        // is just one return statement.\n        public PredType type = default!;\n        public string name = default!;\n        public List<LocalVariable> parameters = default!;\n        public Expression expression = default!;\n\n        public void Print(TextWriter writer)\n        {\n            writer.WriteLine($\"[predicate] {name}\\n(\");\n            for (int i = 0; i < parameters.Count; ++i)\n                writer.WriteLine($\"\\t({parameters[i].name}: {parameters[i].type}),\");\n            writer.WriteLine(\")\");\n            writer.Write(\"\\t:= \");\n            expression.Print(writer);\n        }\n    }\n}"
  },
  {
    "path": "ir/Type.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\n/*\n    CMinor 的类型系统最核心的设计如下：\n\n    Type：最抽象的类型\n        VarType：变量类型\n            AtomicType：原子类型\n                IntType：整数类型\n                FloatType：浮点类型\n                BoolType：布尔类型（仅用于标注中）\n            ArrayType：数组类型，是一个复合类型，会带一个原子类型\n        FunType：函数类型，可以携带若干参数类型，并且返回若干参数类型（之所以允许返回多个，是因为我们会将结构体“拍扁”成“tuple”）\n        PredType：谓词类型，可以携带若干参数类型\n    \n    注意：在 CMinor 中不允许（隐式和显式的）类型转换\n*/\n\nusing System;\nusing System.Collections.Generic;\n\nnamespace cminor\n{\n    abstract class Type { }\n\n    abstract class VarType : Type { }\n\n    /// <summary> 原子类型，包括整数、浮点数和布尔 </summary>\n    /// <remarks> 这里我们尝试拿 singleton design pattern 来简化繁琐的比较。 </remarks>\n    abstract class AtomicType : VarType\n    {\n        public static AtomicType FromString(string s)\n        {\n            switch (s)\n            {\n                case \"int\":\n                case \"integer\":\n                    return IntType.Get();\n                case \"float\":\n                case \"real\":\n                    return FloatType.Get();\n                case \"bool\":\n                case \"boolean\":\n                    return BoolType.Get();\n                default:\n                    throw new ArgumentException($\"Failed to parse {s} as an atomic type, which is neither int/integer, float/real nor bool/boolean.\");\n            }\n        }\n\n        public static HashSet<String> availableNames = new HashSet<String>()\n        {\n            \"int\", \"integer\", \"float\", \"real\", \"bool\", \"boolean\"\n        };\n    }\n\n    sealed class IntType : AtomicType\n    {\n        private static IntType singleton = new IntType();\n\n        private IntType() { }\n\n        public static IntType Get()\n        {\n            return singleton;\n        }\n\n        public override string ToString()\n        {\n            return \"int\";\n        }\n    }\n\n    sealed class FloatType : AtomicType\n    {\n        private static FloatType singleton = new FloatType();\n\n        private FloatType() { }\n\n        public static FloatType Get()\n        {\n            return singleton;\n        }\n\n        public override string ToString()\n        {\n            return \"float\";\n        }\n    }\n\n    sealed class BoolType : AtomicType\n    {\n        private static BoolType singleton = new BoolType();\n\n        private BoolType() { }\n\n        public static BoolType Get()\n        {\n            return singleton;\n        }\n\n        public override string ToString()\n        {\n            return \"bool\";\n        }\n    }\n\n    sealed class ArrayType : VarType\n    {\n        public AtomicType atomicType;\n\n        private static ArrayType intArraySingleton = new ArrayType(IntType.Get());\n        private static ArrayType boolArraySingleton = new ArrayType(BoolType.Get());\n        private static ArrayType floatArraySingleton = new ArrayType(FloatType.Get());\n\n        private ArrayType(AtomicType atomicType)\n        {\n            this.atomicType = atomicType;\n        }\n\n        public static ArrayType Get(AtomicType atomicType)\n        {\n            switch (atomicType)\n            {\n                case IntType:\n                    return intArraySingleton;\n                case BoolType:\n                    return boolArraySingleton;\n                case FloatType:\n                    return floatArraySingleton;\n                default:\n                    throw new ArgumentException(\n                        message: \"an atomic type that is not int, float, nor bool is found when constructing an array type. Probably a bug occurs.\",\n                        paramName: nameof(atomicType));\n            }\n        }\n\n        public override string ToString()\n        {\n            return $\"{atomicType}[]\";\n        }\n    }\n\n    class FunType : Type\n    {\n        public List<VarType> returnTypes;\n        public List<VarType> paraTypes;\n\n        private static LinkedList<FunType> singletons = new LinkedList<FunType>();\n\n        private FunType(List<VarType> returnTypes, List<VarType> paraTypes)\n        {\n            this.returnTypes = returnTypes;\n            this.paraTypes = paraTypes;\n        }\n\n        public static FunType Get(List<VarType> returnTypes, List<VarType> paraTypes)\n        {\n            Func<FunType, bool> Equals = (FunType funType) =>\n            {\n                if (returnTypes.Count != funType.returnTypes.Count)\n                    return false;\n                for (int i = 0; i < funType.returnTypes.Count; ++i)\n                    if (returnTypes[i] != funType.returnTypes[i])\n                        return false;\n\n                if (paraTypes.Count != funType.paraTypes.Count)\n                    return false;\n                for (int i = 0; i < funType.paraTypes.Count; ++i)\n                    if (paraTypes[i] != funType.paraTypes[i])\n                        return false;\n\n                return true;\n            };\n            foreach (FunType funType in singletons)\n                if (Equals(funType))\n                    return funType;\n\n            // if there is no equal FunType to be find\n            FunType newFunType = new FunType(returnTypes, paraTypes);\n            singletons.AddLast(newFunType);\n            return newFunType;\n        }\n\n        public override string ToString()\n        {\n            string s = \"\";\n            for (int i = 0; i < returnTypes.Count; ++i)\n            {\n                if (i > 0) s += \",\";\n                s += paraTypes[i].ToString();\n            }\n            s += \"(\";\n            for (int i = 0; i < paraTypes.Count; ++i)\n            {\n                if (i > 0) s += \",\";\n                s += paraTypes[i].ToString();\n            }\n            s += \")\";\n            return s;\n        }\n    }\n\n    /// <summary> 谓词类型（可以近似理解为一个 inline logic function） </summary>\n    /// <remarks>\n    /// 尽管 <c>PredType</c> 和 <c>FunType</c> 似乎有一点类似，但我们还是应该将其分开处理。\n    /// 毕竟在我们的设计里，谓词只能在 annotation 里调用，它不能被视为一个 function，不是嘛？\n    /// </remarks>\n    sealed class PredType : Type\n    {\n        public List<VarType> paraTypes;\n\n        private static LinkedList<PredType> singletons = new LinkedList<PredType>();\n\n        private PredType(List<VarType> paraTypes)\n        {\n            this.paraTypes = paraTypes;\n        }\n\n        public static PredType Get(List<VarType> paraTypes)\n        {\n            Func<PredType, bool> Equals = (PredType predType) =>\n            {\n                if (paraTypes.Count != predType.paraTypes.Count)\n                    return false;\n                for (int i = 0; i < predType.paraTypes.Count; ++i)\n                    if (paraTypes[i] != predType.paraTypes[i])\n                        return false;\n\n                return true;\n            };\n            foreach (PredType predType in singletons)\n                if (Equals(predType))\n                    return predType;\n\n            // if there is no equal PredType to be find\n            PredType newPredType = new PredType(paraTypes);\n            singletons.AddLast(newPredType);\n            return newPredType;\n        }\n\n        public override string ToString()\n        {\n            string s = \"predicate(\";\n            for (int i = 0; i < paraTypes.Count; ++i)\n            {\n                if (i > 0) s += \",\";\n                s += paraTypes[i].ToString();\n            }\n            s += \")\";\n            return s;\n        }\n    }\n}"
  },
  {
    "path": "ir/Variable.cs",
    "content": "/* Copyright 2022 Xingyu Xie\n\nThis file is part of CMinor.\n\nCMinor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nCMinor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with CMinor. If not, see <https://www.gnu.org/licenses/>. */\n\nnamespace cminor\n{\n    /// <summary> 一个变量的抽象类型 </summary>\n    /// <remarks>\n    /// 在最终的 IR 中，所有变量都会被视作局部变量（<c>LocalVariable</c>）来处理，数组和约束变量会被视作特殊的局部变量。\n    /// 不过在 IR 的生成过程中，为了方便，我们还会有成员变量和结构体变量，细节可见于 frontend/Struct.cs。\n    /// </remarks>\n    abstract class Variable\n    {\n        public VarType type = default!;\n        public string name = default!;\n    }\n\n    /// <summary> 包括局部变量，函数参数，辅助变量，额外的，成员变量也会被转成 <c>LocalVariable</c> 来处理 </summary>\n    class LocalVariable : Variable { }\n\n    class ArrayVariable : LocalVariable\n    {\n        // 只有在 new array 的时候需要对 length 作一个非负性的 runtime assertion\n        public LocalVariable length = default!;\n    }\n\n    sealed class QuantifiedVariable : LocalVariable { }\n\n    /// <summary> 结构体的成员变量 </summary>\n    /// <remarks> <c>MemberVariable</c> 和其他的 sibling class 不太一样，它是放在结构体的定义里的，并不会实际出现在表达式里。 </remarks>\n    sealed class MemberVariable : Variable { }\n}"
  },
  {
    "path": "readme.md",
    "content": "![](logo.jpeg)\n\n## 简介\n\n本项目为 2022 年春季学期清华大学《软件分析与验证》课程实验平台，作业平台提供了一个 CMinor 的验证框架，你需要在其中实现核心的验证算法。CMinor 是一个面向验证的教学语言，其包括源程序和验证标注两部分，其中源程序部分大致是 C 语言的子集，验证标注部分大致是 [ACSL (ANSI/ISO C Specification Language)](https://frama-c.com/html/acsl.html) 的子集。从 C 语言的角度来看，验证标注是写在注释中的，不会影响 C 代码通常的编译和运行。\n\n在本实验中你需要实现本工具中的核心验证算法部分，具体的说明请见[任务说明文档](task-doc.md)。\n\n本项目使用 [git submodules](https://git-scm.com/book/en/v2/Git-Tools-Submodules) 来集成公开测例仓库，在 clone 后可以使用 `git submodule update --remote` 来更新测例仓库。\n\n## 安装\n\n本项目依赖于 .NET 6，你可以从[这里](https://dotnet.microsoft.com/download)下载其最新的 SDK。\n\n你可以使用任意你喜欢的 IDE，我们推荐：\n- [Visual Studio 2022 (>= 17.0.0)](https://visualstudio.microsoft.com/)：可以在安装的时候打包安装 .NET 的 SDK，不需要再单独下载\n- [Visual Studio Code](https://code.visualstudio.com/)：配合 [C# 插件](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp)\n- [Rider](https://www.jetbrains.com/rider/)\n\n> 注意：建议不要通过 `homebrew` 或 `apt` 直接安装，因为其软件源中的 dotnet 的版本很有可能是过时的。建议从[这里](https://dotnet.microsoft.com/download)下载最新版。\n\n> 注意：如果你遇到了错误 `Unhandled exception. System.DllNotFoundException: Unable to load shared library 'libz3' or one of its dependencies.`，那么你需要从[这里](https://github.com/Z3Prover/z3/releases/tag/z3-4.8.16)单独安装 Z3 4.8.16。\n\n## 使用\n\n为了使用在线评测功能，你需要先 fork 本仓库。\n\n本项目基本的运行方法是在根目录下运行以下指令：\n\n```bash\ndotnet run -- --source <path>\n```\n\n你可以使用 `--printCFG` 来打印出得到的 CFG。\n\n所支持的各命令行选项的具体含义为：\n\n```bash\n--source      Required. The source file of CMinor language (recommended with filename extension '.c').\n\n--printCFG    The file (or 'console') to which the control flow graph is printed.\n\n--help        Display this help screen.\n\n--version     Display version information.\n```\n\n## 评测方式\n\n我们不再使用传统的 OJ 来提交代码，而是用 [GitHub Actions](https://github.com/features/actions) 将自动化测试直接集成进项目中。\n简而言之，你的每一次 push 都相当于自动提交了代码，会触发一个名为 `Build and Test` 的 job，其会构建项目并评测所有测例，其得分（百分制）为：\n\n![Error when building and testing](https://byob.yarr.is/thufv/CMinor/score)\n\n> 注1：请在 fork 后将上面的 URL 中的 `thufv` 替换为你的用户名。\n\n> 注2：以上显示的得分需要等待每次 push 所触发的 GitHub Action 执行完毕后才会被更新。\n\n\n## 结构\n\n该编译器的设计可以分为三个部分：\n\n * 前端（frontend）：使用由 [ANTLR](https://www.antlr.org/) 自动生成的 parser 将源文件解析为 CST (concrete syntax tree，具体语法树)，再遍历 CST，生成 CFG（control flow graph，控制流图）；\n * 中间表示（ir）：面向验证来设计的控制流图；\n * 后端（backend）：使用 deductive verification 的方法从 CFG 中生成验证条件（verification condition），再将其喂给 SMT Solver 来求解。\n   * 这部分是你需要来实现的。\n\n你唯一被允许修改、并且你也必须要修改的文件是 `Verifier.cs`，你需要在其中实现演绎验证的算法主体。\n\n## API 文档\n\n如需阅读 API 文档，你可以使用 [doxygen](https://www.doxygen.nl/index.html)，在本项目根目录下运行 `doxygen` 即可生成。\n\n所生成的 API 文档在 `./api-doc/`，打开 `./api-doc/index.html` 即可浏览。\n\n## 贡献者\n\n * [谢兴宇](https://github.com/namasikanam)\n * [陈建辉](https://www.zhihu.com/people/yan-jing-ye-35)\n * [徐荣琛](https://xurongchen.github.io/)\n * [刘江宜](https://github.com/panda2134)\n * [孙志航](https://www.pixiv.net/users/73044167)\n * [贺飞](https://feihe.github.io/)\n\n## 参考\n\nCMinor 语言大致是以下语言标准的子集：\n\n- Standard C: [ISO/IEC 9899:2018, aka C17 or C18](https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf)\n- ANSI/ISO C Specification Language: [ACSL v1.17](https://frama-c.com/download/acsl-1.17.pdf)\n"
  },
  {
    "path": "task-doc.md",
    "content": "# 课程大作业任务说明文档\n\n## 任务说明\n\n这里是 2021-2022 年春季学期**软件分析与验证**课程大作业任务说明文档，本次课程大作业的目标是完成一个具有以下功能的程序验证工具：\n\n- 对于给定的带有部分正确性验证标注的输入程序源码，能够返回其**部分正确性**验证的结果。\n- 对于给定的带有部分正确性验证标注和秩函数的输入程序源码，能够返回其**完全正确性**验证的结果。\n- 完成工具报告，大致描述你的实现过程、过程中遇到的问题以及解决方式。\n\n推荐实现的验证算法为**演绎验证**，其在参考教材 *The Calculus of Computation: Decision Procedures with Applications to Verification* 的第五章 *Program Correctness: Mechanics* 中有详尽的介绍。\n\n## 输入和输出\n\n以下是对本次大作业所需实现的程序验证工具的输入和输出的描述。\n\n### 输入\n\n一个符合语法规范的，带有**前置条件**、**后置条件**、**循环不变式**、**断言**以及**秩函数**等验证标注的，文本格式的 CMinor 语言的代码文件。\n\nCMinor 语言的源程序部分大致是 C 语言的子集，验证标注部分大致是 ACSL 语言的子集。\n\n> 注意：秩函数是一个整型表达式或整形表达式的元组，对于带有秩函数的源码文件，我们保证其文件中所有函数及循环都被标注了秩函数，且要么所有秩函数都是一个整形表达式、要么所有秩函数的元组长度均相同。\n\n### 输出\n\n对于一个合法的输入，所实现的验证工具会在运行结束后，在其标准输出流中输出对应的验证结果。具体格式为：\n\n- `VERIFIED`：程序中所有验证标注均为有效的，即其部分正确（如果源码中没有秩函数）或者完全正确（如果源码中有秩函数）；\n- `UNVERIFIED`：程序中并非所有验证标注都有效的，即其部分正确性（如果源码中没有秩函数）或者完全正确性（如果源码中有秩函数）不成立；\n- `UNKNOWN`：程序中验证标注的有效性未知。\n\n## 实现流程\n\n验证工具的实现框图如下图所示。它包含了从程序源码到验证结果的全部流程。其中，`src` 表示程序**源代码**，`AST` 表示抽象语法树（Abstract Syntax Tree），`CFG` 表示**控制流图**（Control-flow Graph），`VC` 表示验证条件（Verification Condition），`solver` 表示 SMT 求解器，`res` 表示需要输出的验证结果。其中，验证条件`VC`的生成，我们使用 `ded-verif`（deductive verification）验证算法。\n\n在以下框图中，从源代码（`src`）到控制流图（`CFG`）的部分，和本课程教授的内容关系不大。因此，在本次作业任务中，这部分的实现，已经由助教完成，并以源码的形式给出，大家可以直接使用。而从 `CFG` 到验证结果（`res`）的部分，则是本课程所教授的核心内容，需要同学们自己独立完成。\n\n```sh\n   parser          | ded-verif    solver\n     |             |     |          |\nsrc ---> AST ---> CFG -------> VCs ---> res\n                   |   \n      by TA        |    by 'yourself'\n                   |\n```\n\n\n### CMinor 语言\n\n验证工具输入的源代码 `src` 使用 CMinor 语言，一种面向教学的验证语言，其形式化语法文法如 ANTLR 文法文件 `CMinorParser.g4` 和 `CMinorLexer.g4` 中所示。\n\nCMinor 语言支持两种 C 中的原子类型 `int`、`float`，支持这两种原子类型的定长的*一维数组*的定义和读写，也支持以这两种原则类型为成员的结构体（`struct`），同时也支持 C 语言中最基本的**顺序**、**条件**（`if-then-else`）和**循环**（`while`、`for` 和 `do-while`）语句，以及函数。\n\n以下是一个使用 CMinor 语言描述的程序的例子。在函数 `fun` 中，变量 `count` 的值从 `0` 开始不断增大 `1`，直到其值不再小于 `10`。随后，该函数将返回 `count`。\n\n```c\nint fun() {\n    int count = 0;\n    while (count < 10)\n    {\n        count = count + 1;\n    }\n    return count;\n}\n```\n\n由于 CMinor 语言是验证语言，所以还会额外支持用于程序验证的标注，这些标注是一种以 `/*@` 或者 `//@` 开头的特殊的注释。\n\n对于 CMinor 语言中的任意一个函数，都必须使用一阶逻辑公式标注其**前置条件**（`requires`）和**后置条件**（`ensures`）。同时，在循环头位置，也必须标注对应位置的**循环不变式**。基于前置条件和后置条件的标注，形成了一个程序**验证任务**。即证明对于所有在初始情况下，满足前置条件的程序执行路径，在其“末端”后置条件也需要满足。\n\n除了前置后置条件和循环不变式外，CMinor 语言还支持对断言的标注。并且对于除数、数组下标和数组长度，会自动生成运行时断言（runtime assertion）：“除数不为零”、“数组下标非负”、“数组下标小于数组长度”。\n\n在验证标注中，CMinor 支持三种数学意义上的原子类型：`integer`、`real` 和 `boolean`，类型为 C 中的 `int` 或 `float` 的程序变量，在验证标注中会被提升成类型为 `integer` 或 `real` 的数学变量，也就是说我们在验证标注中无需考虑越界和取整的问题。所有标注的逻辑公式均使用*一阶逻辑*描述，即其可以被量词（`\\forall` 和 `\\exists`）限定。\n\n以如下的程序为例，函数 `fun` 的前置条件 为 `\\true`，后置条件 为 `\\result == 10`，即返回值（return value）等于 `10`。那么，对于如下的输入，程序验证工具需要证明，函数 `fun` 在任何条件下（`\\true` 表示始终满足），其返回值都满足 `\\result == 10`。为证明该结论，需要使用循环不变式 `count <= 10`。\n\n```c\n/*@ requires \\true;\n  @ ensures \\result == 10; */\nint fun() {\n    int count = 0;\n    //@ loop invariant count <= 10;\n    while (count < 10)\n    {\n        count = count + 1;\n    }\n    return count;\n}\n```\n\n为了证明程序的**完全正确性**，还需要证明程序的终止性，即程序的执行路径都是有限的。为此，CMinor 语言还支持用于证明终止性的**秩函数**的标注。秩函数是一个整形表达式或整形表达式的元组，在函数头以 `decreases` 标出，在循环头以 `loop variant` 标出。所有有效的秩函数标注的值都是**非负的**。同时，对于程序中的任意一条基本路径，在路径头标注的秩函数的值，都**严格大于**路径尾标注的秩函数的值（对于元组而言，是字典序意义上的大于）。以此便可以证明程序的任意执行路径都是有限的。\n\n以如下的程序为例，函数 `fun` 入口位置标注的秩函数表达式为 `11`，而在循环入口标注的秩函数表达式为 `10 - count`。从程序入口的 `11` 到循环头的 `10 - count` 的基本路径上，可以证明秩函数表达式的值是严格下降的。同时，从循环头的 `10 - count` 到其自身的基本路径上，由于经过了语句 `count = count + 1`，故秩函数表达式的值也是严格下降的。`11` 是一个自然数，由循环不变式 `count <= 10` 可知 `10 - count` 的非负性，所以全体秩函数也是非负的。因此，可以判定秩函数标注的有效性，即程序的终止性。\n\n> 注：在本次作业的验证任务中，对于函数头的秩函数，我们要求其非负性可以被函数的前置条件所蕴含；对于循环头的秩函数，我们要求其非负性可以被循环不变式所蕴含。\n\n```c\n/*@ requires \\true;\n  @ decreases 11;\n  @ ensures \\result == 10; */\nint fun() {\n    int count = 0;\n    /*@ loop invariant count <= 10;\n      @ loop variant 10 - count; */\n    while (count < 10)\n    {\n        count = count + 1;\n    }\n    return count;\n}\n```\n\n### 控制流图\n\n程序分析和验证一般在程序的**控制流图**上进行。控制流图是程序的一种图形表示，它将程序的控制流结构，以有向图的形式表示出来。在控制流图上的每一个节点是一个**基本代码块**（Basic Block），简称为**基本块**。而连接各个基本块的有向边称为**控制流边**。在控制流图中，原程序中的所有控制流语句，如 `if-then-else` 和 `while` 等，都被替换为 `assume` 语句以及相应的控制流边。其中，`assume` 语句表达的含义是，在当前的执行路径中，若 `assume` 的条件被满足，则路径继续执行，否则，路径将阻塞，从而不再继续执行。\n\n下图所示的是上一个例子中的 CMinor 源码的控制流图，其中总计有 7 个块。除了基本块外，`_PRECOND#1` 是整个控制流图的入口块，同时也用来表达函数的前置条件及秩函数，`_POSTCOND#1` 是整个控制流图的出口块，同时也用来表达函数的后置条件，`_LOOPHEAD#1` 是循环头的虚拟基本块。这个例子展示了出于验证需要，我们在常规的控制流图上，额外设计的三类虚拟块。\n\n```ASCII\n                   _PRECOND#1:\n                       requires true\n                       decreases 11\n                           |\n                           |\n                           V\n                   _BASIC#1:\n                       count$1 = 0;\n                           |\n                           |<-------------------\n                           V                   |\n                   _LOOPHEAD#1:                |\n               loop invariant (count$1 <= 10)  |\n               loop variant (10 - count$1)     |\n                   _cond$1 = (count$1 < 10)    |\n                           |                   |\n       --------------------|                   |\n       |                   V                   |\n   _BASIC#3         _BASIC#2:                  |\nassume !_cond$1        assume _cond$1          |\n       |          count$1 = (count$1 + 1)      |\n       |                   |                   |\n       |                   |                   |\n       |                   |--------------------\n       ------------------->|\n                           |\n                   _BASIC#4:\n                    \\result$1 = count$1\n                           |\n                           |\n                           V\n                   _POSTCOND#1:\n                ensures (\\result$1 == 10)\n```\n\n为了方便后续的验证，我们会对程序中的所有变量作 [alpha conversion](https://wiki.haskell.org/Alpha_conversion)，即对变量重命名，保证所有变量不重名，比如上图中的 `$1` 即是通过 alpha conversion 所得。对于函数调用、实参、条件表达式、数组长度、数组下标和除数，我们会为其新建临时变量，比如上图中的 `_cond$1`。我们在数据流图这一层中间表示中不保留结构体的概念，结构体会被以类似于“元组”的形式处理，注意这也会导致函数调用时可能会有多个返回值。\n\n在我们的控制流图中，有四类语句：\n- assign：赋值语句，包括对变量的 assign 和对数组中元素的 assign 两种\n- assert：程序断言\n- assume：守卫（guard）条件，仅会出现在块首\n- function call：函数调用，保证所有参数都是变量，并且可能有多个返回值\n\n至此，从验证工具输入的源文件形式 CMinor 语言，到验证算法所依赖的程序控制流图，都已经有了一个大致的介绍。同时，在本次大作业所给出的初始代码中，也已经完成了对于以上内容的实现。同学们需要结合初始代码，以及课程所讲授的内容，完成本次课程大作业。\n\n## 附加任务\n\n我们鼓励感兴趣的同学在学有余力的同时，完成一些更加进阶的验证算法。比如：\n\n- [BMC 算法](https://zhuanlan.zhihu.com/p/318446383)\n- [可递归逻辑函数](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/12/krml250.pdf)\n- [谓词抽象算法](https://zhuanlan.zhihu.com/p/332406712)\n- 其他自选题目...\n\n## 参考教材\n\n*The Calculus of Computation: Decision Procedures with Applications to Verification*\n"
  }
]