├── .gitignore
├── 1 Compiler
├── Foreign
│ └── pom.xml
├── version1
│ └── Compiler
│ │ ├── pom.xml
│ │ ├── src
│ │ └── main
│ │ │ └── java
│ │ │ ├── Encoder.java
│ │ │ ├── GenerateLexerAndParser.java
│ │ │ ├── Test.java
│ │ │ ├── antl
│ │ │ ├── AllDescTable.java
│ │ │ ├── Errors.java
│ │ │ ├── Function.java
│ │ │ ├── Type.java
│ │ │ ├── Variable.java
│ │ │ ├── ggggg.g
│ │ │ ├── ggggg.tokens
│ │ │ ├── gggggLexer.java
│ │ │ └── gggggParser.java
│ │ │ └── com
│ │ │ └── kadet
│ │ │ └── compiler
│ │ │ └── antlrManager
│ │ │ └── CompilerHelper.java
│ │ ├── test
│ │ └── test-old
├── version2
│ └── Compiler
│ │ ├── pom.xml
│ │ ├── src
│ │ └── main
│ │ │ └── java
│ │ │ ├── Encoder.java
│ │ │ ├── GenerateLexerAndParser.java
│ │ │ ├── Test.java
│ │ │ ├── antl
│ │ │ ├── AllDescTable.java
│ │ │ ├── Errors.java
│ │ │ ├── Function.java
│ │ │ ├── Type.java
│ │ │ ├── Variable.java
│ │ │ ├── ggggg.g
│ │ │ ├── ggggg.tokens
│ │ │ ├── gggggLexer.java
│ │ │ └── gggggParser.java
│ │ │ └── com
│ │ │ └── kadet
│ │ │ └── compiler
│ │ │ └── antlrManager
│ │ │ └── CompilerHelper.java
│ │ ├── test
│ │ └── test-old
├── version3
│ ├── example
│ │ └── antlr3xtut-part9.zip
│ ├── pom.xml
│ └── src
│ │ ├── main
│ │ ├── antlr3
│ │ │ └── com
│ │ │ │ └── kadet
│ │ │ │ └── compiler
│ │ │ │ ├── EvaluatorWalker.g
│ │ │ │ ├── Sample.g
│ │ │ │ ├── Sample2.g
│ │ │ │ ├── Sample3.g
│ │ │ │ └── Sample4.g
│ │ └── java
│ │ │ └── com
│ │ │ └── kadet
│ │ │ └── compiler
│ │ │ ├── AbstractCompiler.java
│ │ │ ├── Sample2Compiler.java
│ │ │ ├── Sample3Compiler.java
│ │ │ ├── Sample4Compiler.java
│ │ │ ├── SampleCompiler.java
│ │ │ └── evaluators
│ │ │ ├── DivideEvaluator.java
│ │ │ ├── Evaluator.java
│ │ │ ├── IntEvaluator.java
│ │ │ ├── MinusEvaluator.java
│ │ │ ├── ModEvaluator.java
│ │ │ ├── NegationEvaluator.java
│ │ │ ├── PlusEvaluator.java
│ │ │ └── TimesEvaluator.java
│ │ └── test
│ │ └── java
│ │ └── com
│ │ └── kadet
│ │ └── compiler
│ │ ├── Sample2Test.java
│ │ ├── Sample3Test.java
│ │ ├── Sample4Test.java
│ │ └── SampleTest.java
├── version3Old
│ ├── AbstractCompiler.java
│ ├── Edge.java
│ ├── Graph.g
│ ├── Graph.java
│ ├── GraphCompiler.java
│ ├── ListGrammar.g
│ ├── ListGrammarCompiler.java
│ ├── ListGrammarTest.java
│ ├── S001HelloWord.g
│ ├── S001HelloWordCompiler.java
│ ├── S001HelloWordTest.java
│ ├── S002HelloWord.g
│ ├── S002HelloWordCompiler.java
│ ├── S002HelloWordTest.java
│ ├── S003HelloWord.g
│ ├── S003HelloWordCompiler.java
│ ├── S003HelloWordTest.java
│ ├── S004HelloWord.g
│ ├── S004HelloWordCompiler.java
│ ├── S004HelloWordTest.java
│ ├── SimpleGrammar.g
│ ├── SimpleGrammarCompiler.java
│ ├── SimpleGrammarWordTest.java
│ ├── Vertex.java
│ └── mmemory.java
├── version4
│ ├── pom.xml
│ └── src
│ │ ├── main
│ │ ├── antlr3
│ │ │ └── com
│ │ │ │ └── kadet
│ │ │ │ └── compiler
│ │ │ │ ├── TODO.txt
│ │ │ │ └── kadet.g
│ │ └── java
│ │ │ └── com
│ │ │ └── kadet
│ │ │ └── compiler
│ │ │ ├── AbstractCompiler.java
│ │ │ ├── KadetCompiler.java
│ │ │ ├── entities
│ │ │ ├── Bool.java
│ │ │ ├── Choice.java
│ │ │ ├── Constant.java
│ │ │ ├── Element.java
│ │ │ ├── Function.java
│ │ │ ├── Int.java
│ │ │ ├── List.java
│ │ │ ├── Procedure.java
│ │ │ ├── ProcedureParameter.java
│ │ │ ├── Program.java
│ │ │ ├── Type.java
│ │ │ ├── Value.java
│ │ │ └── Variable.java
│ │ │ ├── evaluators
│ │ │ ├── AssignmentEvaluator.java
│ │ │ ├── CallEvaluator.java
│ │ │ ├── ChoiceEvaluator.java
│ │ │ ├── Evaluator.java
│ │ │ ├── ForEvaluator.java
│ │ │ ├── FunctionEvaluator.java
│ │ │ ├── IfEvaluator.java
│ │ │ ├── KadOutEvaluator.java
│ │ │ ├── ProcedureCallEvaluator.java
│ │ │ ├── ProcedureEvaluator.java
│ │ │ ├── ProgramEvaluator.java
│ │ │ ├── ReturnStatementEvaluator.java
│ │ │ ├── StatementEvaluator.java
│ │ │ └── WhileEvaluator.java
│ │ │ ├── expressions
│ │ │ ├── AddToListExpression.java
│ │ │ ├── AndExpression.java
│ │ │ ├── BinaryExpression.java
│ │ │ ├── ConstantOrVariableValueExpression.java
│ │ │ ├── DivideExpression.java
│ │ │ ├── ElementFromListExpression.java
│ │ │ ├── EqualExpression.java
│ │ │ ├── Expression.java
│ │ │ ├── FunctionCallExpression.java
│ │ │ ├── GreaterExpression.java
│ │ │ ├── GreaterOrEqualExpression.java
│ │ │ ├── KadInExpression.java
│ │ │ ├── LessExpression.java
│ │ │ ├── LessOrEqualExpression.java
│ │ │ ├── ListExpression.java
│ │ │ ├── MinusExpression.java
│ │ │ ├── MultipleExpression.java
│ │ │ ├── NotEqualExpression.java
│ │ │ ├── OrExpression.java
│ │ │ ├── OverListExpression.java
│ │ │ ├── PlusExpression.java
│ │ │ ├── RemoveAllElementEntriesExpression.java
│ │ │ ├── RemoveFromListExpression.java
│ │ │ ├── UnaryOperation.java
│ │ │ └── ValueExpression.java
│ │ │ ├── initializers
│ │ │ ├── Initializer.java
│ │ │ └── ProcedureInitializer.java
│ │ │ └── util
│ │ │ ├── Errors.java
│ │ │ ├── KadetError.java
│ │ │ ├── KadetException.java
│ │ │ ├── ProcedureUtils.java
│ │ │ ├── ValueFactory.java
│ │ │ ├── ValueUtils.java
│ │ │ └── VariableUtils.java
│ │ └── test
│ │ └── java
│ │ └── com
│ │ └── kadet
│ │ └── compiler
│ │ ├── KadetTest.java
│ │ └── Main.java
└── version4Old
│ └── old
│ ├── AllDescTable.java
│ ├── Errors.java
│ ├── Function.java
│ ├── GggCompiler.java
│ ├── Sample3.g
│ ├── Sample3Compiler.java
│ ├── Sample3Test.java
│ ├── Stewie.g
│ ├── Type.java
│ ├── Variable.java
│ ├── evaluators
│ ├── DivideEvaluator.java
│ ├── Evaluator.java
│ ├── IntEvaluator.java
│ ├── MinusEvaluator.java
│ ├── ModEvaluator.java
│ ├── NegationEvaluator.java
│ ├── PlusEvaluator.java
│ └── TimesEvaluator.java
│ ├── gggTest.java
│ ├── ggggg.g
│ ├── test.java
│ └── tokens
│ ├── Errors.java
│ ├── Function.java
│ ├── Program.java
│ ├── Type.java
│ └── Variable.java
├── Foreign
└── ListLang-master
│ ├── .gitignore
│ ├── README.md
│ ├── examples
│ ├── error_lexer.ll
│ ├── error_parser.ll
│ ├── error_semantic.ll
│ ├── merge_sorted_lists.ll
│ ├── quicksort.ll
│ ├── recursion.ll
│ ├── reverse.ll
│ └── simple.ll
│ ├── rebuild.bat
│ ├── run.bat
│ └── src
│ ├── List.java
│ ├── ListLang.g
│ ├── ListLangWalker.g
│ ├── adds
│ └── META-INF
│ │ └── MANIFEST.MF
│ ├── listlang.py
│ ├── llcompiler
│ ├── __init__.py
│ ├── error_processor.py
│ ├── globals.py
│ ├── jcodemaker.py
│ ├── jtrans.py
│ └── ll_scope.py
│ └── readme.txt
├── books
├── Terence Parr - The Definitive ANTLR Reference.pdf
├── Ахо, Сети, Ульман. Компиляторы. Принципы, технологии, инструменты.2ed.2008.djvu
├── Ахо, Сети, Ульман. Компиляторы. Принципы, технологии, инструменты.2ed.2008.pdf
├── Ахо, Сети, Ульман. Компиляторы. Принципы, технологии, инструменты.djvu
├── Дополнительная литература
│ └── Примеры языков
│ │ ├── www.engin.umd.umich.edu.chm
│ │ └── www.ntecs.de.chm
├── Пратт, Зелковиц. Языки программирования Разработка и реализация.djvu
└── Себеста. Основные копцепции языков программирования.djvu
└── exam
└── YaPIS.quest.end-2010.doc
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | #idea files
4 | *.iml
5 | .idea/
6 |
7 | #maven build dirs
8 | target/
--------------------------------------------------------------------------------
/1 Compiler/Foreign/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.kadet.compiler
6 | kadetCompiler
7 | 1.0
8 | jar
9 |
10 | kadetCompiler
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 | org.antlr
20 | antlr
21 | 3.3
22 | jar
23 | compile
24 |
25 |
26 | junit
27 | junit
28 | 4.8.2
29 | jar
30 | test
31 |
32 |
33 |
34 |
35 |
36 |
37 | org.antlr
38 | antlr3-maven-plugin
39 | 3.3
40 |
41 |
42 | run antlr
43 | generate-sources
44 |
45 | antlr
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | org.codehaus.mojo
54 | build-helper-maven-plugin
55 |
56 |
57 | add-source
58 | generate-sources
59 |
60 | add-source
61 |
62 |
63 |
64 | ${basedir}/target/generated-sources/antlr3
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | Compiler
6 | Compiler
7 | 1.0-SNAPSHOT
8 | jar
9 |
10 | Compiler
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 |
20 | org.antlr
21 | antlr-complete
22 | 3.5.1
23 |
24 |
25 |
26 | junit
27 | junit
28 | 4.11
29 | test
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/src/main/java/Encoder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Date: 14.02.14
3 | * Time: 17:28
4 | *
5 | * @author SarokaA
6 | */
7 | public class Encoder {
8 |
9 |
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/src/main/java/GenerateLexerAndParser.java:
--------------------------------------------------------------------------------
1 | import com.kadet.compiler.antlrManager.CompilerHelper;
2 | import org.antlr.runtime.ANTLRInputStream;
3 |
4 | import java.io.File;
5 | import java.io.IOException;
6 |
7 | /**
8 | * Date: 13.02.14
9 | * Time: 21:02
10 | *
11 | * @author SarokaA
12 | */
13 | public class GenerateLexerAndParser {
14 |
15 | public static final String G_FILE = "src/main/java/antl/ggggg.g";
16 |
17 | public static final String SRC_FOLDER = "src/main/java/antl";
18 |
19 | public static void main(String[] args) throws IOException {
20 |
21 | CompilerHelper.compile(
22 | new File(SRC_FOLDER).getAbsolutePath(),
23 | new File(G_FILE).getAbsolutePath()
24 | );
25 |
26 | }
27 |
28 | }
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/src/main/java/Test.java:
--------------------------------------------------------------------------------
1 | import antl.gggggLexer;
2 | import antl.gggggParser;
3 | import org.antlr.runtime.ANTLRFileStream;
4 | import org.antlr.runtime.CharStream;
5 | import org.antlr.runtime.CommonTokenStream;
6 | import org.antlr.runtime.RecognitionException;
7 |
8 | import java.io.IOException;
9 |
10 | public class Test {
11 |
12 | public static void main(String[] arg) throws IOException, RecognitionException {
13 |
14 | CharStream input = new ANTLRFileStream("test");
15 |
16 | gggggLexer lexer = new gggggLexer(input);
17 |
18 | CommonTokenStream tokens = new CommonTokenStream(lexer);
19 |
20 |
21 | gggggParser pars = new gggggParser(tokens);
22 | pars.program();
23 | System.out.println("done!!!");
24 |
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/src/main/java/antl/Errors.java:
--------------------------------------------------------------------------------
1 | package antl;
2 |
3 | import java.util.List;
4 |
5 | public class Errors {
6 |
7 | public void DuplicateError(String name_var, int line) {
8 | System.out.println("ERROR : Duplicate local variable '" + name_var
9 | + "' in line " + line);
10 | }
11 |
12 | public void UndefinedVar(String name_var, int line) {
13 | System.out.println("ERROR : The var '" + name_var
14 | + "' is undefined in line " + line);
15 | }
16 |
17 | public void UndefinedMethod(String name_func, int line) {
18 | System.out.println("ERROR : The method '" + name_func
19 | + "' is undefined in line " + line);
20 | }
21 |
22 | public void DuplicateMethod(String name_funcElse, int line) {
23 | System.out.println("ERROR : Duplicate local method '" + name_funcElse
24 | + "' in line " + line);
25 | }
26 |
27 | public void MethodWithoutParams(String name_func, int line) {
28 | System.out.println("ERROR : Method '" + name_func
29 | + "' must't have any parametrs in line " + line);
30 | }
31 |
32 | public void MethodWithParams(String name_func, int line, int kol_params) {
33 | System.out.println("ERROR : Method '" + name_func + "' must have "
34 | + kol_params + " parametrs in line " + line);
35 | }
36 |
37 | public void MethodWithErrorsParams(String name_func, int line,
38 | List params) {
39 | System.out.println("ERROR : Method '" + name_func + "' must have "
40 | + params + " parametrs in line " + line);
41 | }
42 |
43 | public void WrongType(String type1, String type2, int line) {
44 | System.out.println("ERROR : Types '" + type1
45 | + "' and '" + type2 + "' must be casts in line " + line);
46 | }
47 |
48 | public void BadRetType(String type, String prevType, int line) {
49 | System.out.println("ERROR : Return type must be '" + type
50 | + "' first return has '" + prevType + "' in line " + line);
51 | }
52 |
53 | public void NotReturnFunc(String name, int line) {
54 | System.out.println("ERROR : Function '" + name
55 | + "' can't return smth in line " + line);
56 | }
57 |
58 | public void ReturnFunc(String name, int line) {
59 | System.out.println("ERROR : Function '" + name
60 | + "' must have a return value in line " + line);
61 | }
62 |
63 | public void CheckOnRet(int line) {
64 | System.out.println("ERROR : Function must be returnble " + line);
65 | }
66 |
67 | public void LastRet(int line) {
68 | System.out.println("ERROR : Function must have last return " + line);
69 | }
70 |
71 | ////
72 |
73 | public static void BadAfterRet(int line) {
74 | System.out.println("ERROR : instraction can't be after return in line " + line);
75 | }
76 |
77 | public void RetDontNeed(int line) {
78 | System.out.println("ERROR : Return don't need in this func in line " + line);
79 | }
80 |
81 | public void VarDontInit(String name, int line) {
82 | System.out.println("ERROR : Variable '" + name
83 | + "' must be initialize in line " + line);
84 | }
85 |
86 | public static void BadBlockLine(int line) {
87 | System.out.println("ERROR : Block line have uncorrect tab number in line " + line);
88 | }
89 |
90 | public static void WrongStageVar(int line) {
91 | System.out.println("ERROR : wrong stage for define global var in line " + line);
92 | }
93 |
94 | public static void WrongStageFun(int line) {
95 | System.out.println("ERROR : wrong stage for define global fun in line " + line);
96 | }
97 |
98 | public static void WrongStageMain(int line) {
99 | System.out.println("ERROR : wrong stage for define global main in line " + line);
100 | }
101 |
102 | public static void WrongIfElse(int line) {
103 | System.out.println("ERROR : wrong If Else operator in line " + line);
104 | }
105 | }
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/src/main/java/antl/Function.java:
--------------------------------------------------------------------------------
1 | package antl;
2 |
3 | import java.util.LinkedList;
4 | import java.util.List;
5 |
6 | public class Function {
7 | private String name;
8 | private Type type = Type.NON;
9 | private List params = new LinkedList();
10 | private boolean hasLastRet = false;
11 |
12 |
13 | public Function(String name) {
14 | super();
15 | this.name = name;
16 | }
17 |
18 | public Function(String name, Type type) {
19 | super();
20 | this.name = name;
21 | this.type = type;
22 | if (type != null && !Type.NON.equals(type)) setHasLastRet(true);
23 | }
24 |
25 | public String getName() {
26 | return name;
27 | }
28 |
29 | public void setName(String name) {
30 | this.name = name;
31 | }
32 |
33 | public Type getType() {
34 | return type;
35 | }
36 |
37 | public void setType(Type type) {
38 | this.type = type;
39 | if (type != null && !Type.NON.equals(type)) setHasLastRet(true);
40 | }
41 |
42 | public List getParams() {
43 | return params;
44 | }
45 |
46 | public void setParams(List params) {
47 | this.params = params;
48 | }
49 |
50 | public boolean isHasLastRet() {
51 | return hasLastRet;
52 | }
53 |
54 | public void setHasLastRet(boolean hasLastRet) {
55 | this.hasLastRet = hasLastRet;
56 | }
57 |
58 | public boolean equals(Object other) {
59 | if (this.getClass() != other.getClass())
60 | return false;
61 | Function otherObj = (Function) other;
62 | return this.name.equals(otherObj.getName());
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/src/main/java/antl/Type.java:
--------------------------------------------------------------------------------
1 | package antl;
2 |
3 | public enum Type {
4 |
5 | INT("int"), FLOAT("float"),BOOL ("bool"), NON("none");
6 |
7 | private String name;
8 |
9 | Type(String name) {
10 | this.name = name;
11 | }
12 |
13 | public String getName() {
14 | return name;
15 | }
16 | }
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/src/main/java/antl/Variable.java:
--------------------------------------------------------------------------------
1 | package antl;
2 |
3 | public class Variable {
4 |
5 | public Variable(String name,String funName) {
6 | super();
7 | this.name = name;
8 | this.funcName = funName;
9 | }
10 |
11 | private String name;
12 | private Type type = Type.NON;
13 | private String funcName;
14 |
15 | public Type getType() {
16 | return type;
17 | }
18 |
19 | public void setType(Type type) {
20 | this.type = type;
21 | }
22 |
23 | public String getFuncName() {
24 | return funcName;
25 | }
26 |
27 | public void setFuncName(String funcName) {
28 | this.funcName = funcName;
29 | }
30 |
31 | public String getName() {
32 | return name;
33 | }
34 |
35 | public void setName(String name) {
36 | this.name = name;
37 | }
38 |
39 | public boolean equals(Object other) {
40 | if (this.getClass() != other.getClass())
41 | return false;
42 | Variable otherObj = (Variable) other;
43 | return this.name.equals(otherObj.getName());
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/src/main/java/antl/ggggg.tokens:
--------------------------------------------------------------------------------
1 | T__21=21
2 | T__22=22
3 | T__23=23
4 | T__24=24
5 | T__25=25
6 | T__26=26
7 | T__27=27
8 | T__28=28
9 | T__29=29
10 | T__30=30
11 | T__31=31
12 | T__32=32
13 | T__33=33
14 | T__34=34
15 | T__35=35
16 | T__36=36
17 | T__37=37
18 | T__38=38
19 | T__39=39
20 | T__40=40
21 | T__41=41
22 | CLEAR_LINE=4
23 | COMMENT=5
24 | DEDENT=6
25 | ELSE=7
26 | ENDL=8
27 | FLOAT=9
28 | FOR=10
29 | FUNCTION=11
30 | ID=12
31 | IF=13
32 | INDENT=14
33 | INT=15
34 | MAIN=16
35 | STRING=17
36 | TAB=18
37 | WHILE=19
38 | WS=20
39 | '!='=21
40 | '%'=22
41 | '*'=23
42 | '+'=24
43 | ','=25
44 | '-'=26
45 | '/'=27
46 | ';'=6
47 | '<'=28
48 | '<='=29
49 | '='=30
50 | '=='=31
51 | '>'=32
52 | '>='=33
53 | 'Alin'=34
54 | 'Alout'=35
55 | '['=36
56 | ']'=37
57 | '^'=38
58 | 'float'=39
59 | 'int'=40
60 | 'return'=41
61 |
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/src/main/java/com/kadet/compiler/antlrManager/CompilerHelper.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.antlrManager;
2 |
3 | /**
4 | * Date: 13.02.14
5 | * Time: 21:06
6 | *
7 | * @author SarokaA
8 | */
9 | public class CompilerHelper {
10 |
11 | public static void compile (String src, String grammar) {
12 | org.antlr.Tool.main(
13 | new String[]{
14 | "-o",
15 | src,
16 | grammar});
17 | }
18 |
19 | }
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/test:
--------------------------------------------------------------------------------
1 | a=5;
2 | Alenafun fun [b,c]
3 | return 0.0;
4 |
5 |
6 | Alenamain
7 | a = 0;
8 | b = 0;
9 | c = 0;
10 | result = fun [b,c];
11 | if [result != 0.0]
12 | Alout["(a+b)/(c-2)="];
13 | Alout [result];
14 | else
15 | Alout["На ноль делить нельзя!"];
16 |
17 |
18 |
--------------------------------------------------------------------------------
/1 Compiler/version1/Compiler/test-old:
--------------------------------------------------------------------------------
1 | a=5;
2 | Alenafun fun [b,c]
3 | d = 3.5;
4 | rez = d*15.0;
5 | c = [int]c;
6 | d = [int]c^5-2;
7 | if [d != 0]
8 | rez = [a+[int]b]/[c-2];
9 | return rez;
10 | else
11 | if [d != 0]
12 | rez = [a+[int]b]/[c-2];
13 | return rez;
14 | else
15 | return 0.0;
16 |
17 |
18 | Alenafun fun1 [b,c]
19 | d = 0;
20 | rez = 0;
21 | d = c-2;
22 |
23 |
24 | Alenamain
25 | a = 0;
26 | b = 0;
27 | c = 0;
28 | result=0;
29 | Alout["Введите a"];
30 | Alin[a];
31 | Alout["Введите b"];
32 | Alin[b];
33 | Alout["Введите c"];
34 | Alin[c];
35 | result = fun [b,c];
36 | if [result != 0]
37 | Alout["(a+b)/(c-2)="];
38 | Alout [result];
39 | else
40 | Alout["На ноль делить нельзя!"];
41 |
42 |
43 |
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | Compiler
6 | Compiler
7 | 1.0-SNAPSHOT
8 | jar
9 |
10 | Compiler
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 |
20 | org.antlr
21 | antlr-complete
22 | 3.5.1
23 |
24 |
25 |
26 | junit
27 | junit
28 | 4.11
29 | test
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/src/main/java/Encoder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Date: 14.02.14
3 | * Time: 17:28
4 | *
5 | * @author SarokaA
6 | */
7 | public class Encoder {
8 |
9 |
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/src/main/java/GenerateLexerAndParser.java:
--------------------------------------------------------------------------------
1 | import com.kadet.compiler.antlrManager.CompilerHelper;
2 | import org.antlr.runtime.ANTLRInputStream;
3 |
4 | import java.io.File;
5 | import java.io.IOException;
6 |
7 | /**
8 | * Date: 13.02.14
9 | * Time: 21:02
10 | *
11 | * @author SarokaA
12 | */
13 | public class GenerateLexerAndParser {
14 |
15 | public static final String G_FILE = "src/main/java/antl/ggggg.g";
16 |
17 | public static final String SRC_FOLDER = "src/main/java/antl";
18 |
19 | public static void main(String[] args) throws IOException {
20 |
21 | CompilerHelper.compile(
22 | new File(SRC_FOLDER).getAbsolutePath(),
23 | new File(G_FILE).getAbsolutePath()
24 | );
25 |
26 | }
27 |
28 | }
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/src/main/java/Test.java:
--------------------------------------------------------------------------------
1 | import antl.gggggLexer;
2 | import antl.gggggParser;
3 | import org.antlr.runtime.ANTLRFileStream;
4 | import org.antlr.runtime.CharStream;
5 | import org.antlr.runtime.CommonTokenStream;
6 | import org.antlr.runtime.RecognitionException;
7 |
8 | import java.io.IOException;
9 |
10 | public class Test {
11 |
12 | public static void main(String[] arg) throws IOException, RecognitionException {
13 |
14 | CharStream input = new ANTLRFileStream("test");
15 |
16 | gggggLexer lexer = new gggggLexer(input);
17 |
18 | CommonTokenStream tokens = new CommonTokenStream(lexer);
19 |
20 |
21 | gggggParser pars = new gggggParser(tokens);
22 | pars.program();
23 | System.out.println("done!!!");
24 |
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/src/main/java/antl/Errors.java:
--------------------------------------------------------------------------------
1 | package antl;
2 |
3 | import java.util.List;
4 |
5 | public class Errors {
6 |
7 | public void DuplicateError(String name_var, int line) {
8 | System.out.println("ERROR : Duplicate local variable '" + name_var
9 | + "' in line " + line);
10 | }
11 |
12 | public void UndefinedVar(String name_var, int line) {
13 | System.out.println("ERROR : The var '" + name_var
14 | + "' is undefined in line " + line);
15 | }
16 |
17 | public void UndefinedMethod(String name_func, int line) {
18 | System.out.println("ERROR : The method '" + name_func
19 | + "' is undefined in line " + line);
20 | }
21 |
22 | public void DuplicateMethod(String name_funcElse, int line) {
23 | System.out.println("ERROR : Duplicate local method '" + name_funcElse
24 | + "' in line " + line);
25 | }
26 |
27 | public void MethodWithoutParams(String name_func, int line) {
28 | System.out.println("ERROR : Method '" + name_func
29 | + "' must't have any parametrs in line " + line);
30 | }
31 |
32 | public void MethodWithParams(String name_func, int line, int kol_params) {
33 | System.out.println("ERROR : Method '" + name_func + "' must have "
34 | + kol_params + " parametrs in line " + line);
35 | }
36 |
37 | public void MethodWithErrorsParams(String name_func, int line,
38 | List params) {
39 | System.out.println("ERROR : Method '" + name_func + "' must have "
40 | + params + " parametrs in line " + line);
41 | }
42 |
43 | public void WrongType(String type1, String type2, int line) {
44 | System.out.println("ERROR : Types '" + type1
45 | + "' and '" + type2 + "' must be casts in line " + line);
46 | }
47 |
48 | public void BadRetType(String type, String prevType, int line) {
49 | System.out.println("ERROR : Return type must be '" + type
50 | + "' first return has '" + prevType + "' in line " + line);
51 | }
52 |
53 | public void NotReturnFunc(String name, int line) {
54 | System.out.println("ERROR : Function '" + name
55 | + "' can't return smth in line " + line);
56 | }
57 |
58 | public void ReturnFunc(String name, int line) {
59 | System.out.println("ERROR : Function '" + name
60 | + "' must have a return value in line " + line);
61 | }
62 |
63 | public void CheckOnRet(int line) {
64 | System.out.println("ERROR : Function must be returnble " + line);
65 | }
66 |
67 | public void LastRet(int line) {
68 | System.out.println("ERROR : Function must have last return " + line);
69 | }
70 |
71 | ////
72 |
73 | public static void BadAfterRet(int line) {
74 | System.out.println("ERROR : instraction can't be after return in line " + line);
75 | }
76 |
77 | public void RetDontNeed(int line) {
78 | System.out.println("ERROR : Return don't need in this func in line " + line);
79 | }
80 |
81 | public void VarDontInit(String name, int line) {
82 | System.out.println("ERROR : Variable '" + name
83 | + "' must be initialize in line " + line);
84 | }
85 |
86 | public static void BadBlockLine(int line) {
87 | System.out.println("ERROR : Block line have uncorrect tab number in line " + line);
88 | }
89 |
90 | public static void WrongStageVar(int line) {
91 | System.out.println("ERROR : wrong stage for define global var in line " + line);
92 | }
93 |
94 | public static void WrongStageFun(int line) {
95 | System.out.println("ERROR : wrong stage for define global fun in line " + line);
96 | }
97 |
98 | public static void WrongStageMain(int line) {
99 | System.out.println("ERROR : wrong stage for define global main in line " + line);
100 | }
101 |
102 | public static void WrongIfElse(int line) {
103 | System.out.println("ERROR : wrong If Else operator in line " + line);
104 | }
105 | }
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/src/main/java/antl/Function.java:
--------------------------------------------------------------------------------
1 | package antl;
2 |
3 | import java.util.LinkedList;
4 | import java.util.List;
5 |
6 | public class Function {
7 | private String name;
8 | private Type type = Type.NON;
9 | private List params = new LinkedList();
10 | private boolean hasLastRet = false;
11 |
12 |
13 | public Function(String name) {
14 | super();
15 | this.name = name;
16 | }
17 |
18 | public Function(String name, Type type) {
19 | super();
20 | this.name = name;
21 | this.type = type;
22 | if (type != null && !Type.NON.equals(type)) setHasLastRet(true);
23 | }
24 |
25 | public String getName() {
26 | return name;
27 | }
28 |
29 | public void setName(String name) {
30 | this.name = name;
31 | }
32 |
33 | public Type getType() {
34 | return type;
35 | }
36 |
37 | public void setType(Type type) {
38 | this.type = type;
39 | if (type != null && !Type.NON.equals(type)) setHasLastRet(true);
40 | }
41 |
42 | public List getParams() {
43 | return params;
44 | }
45 |
46 | public void setParams(List params) {
47 | this.params = params;
48 | }
49 |
50 | public boolean isHasLastRet() {
51 | return hasLastRet;
52 | }
53 |
54 | public void setHasLastRet(boolean hasLastRet) {
55 | this.hasLastRet = hasLastRet;
56 | }
57 |
58 | public boolean equals(Object other) {
59 | if (this.getClass() != other.getClass())
60 | return false;
61 | Function otherObj = (Function) other;
62 | return this.name.equals(otherObj.getName());
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/src/main/java/antl/Type.java:
--------------------------------------------------------------------------------
1 | package antl;
2 |
3 | public enum Type {
4 |
5 | INT("int"), FLOAT("float"),BOOL ("bool"), NON("none");
6 |
7 | private String name;
8 |
9 | Type(String name) {
10 | this.name = name;
11 | }
12 |
13 | public String getName() {
14 | return name;
15 | }
16 | }
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/src/main/java/antl/Variable.java:
--------------------------------------------------------------------------------
1 | package antl;
2 |
3 | public class Variable {
4 |
5 | public Variable(String name,String funName) {
6 | super();
7 | this.name = name;
8 | this.funcName = funName;
9 | }
10 |
11 | private String name;
12 | private Type type = Type.NON;
13 | private String funcName;
14 |
15 | public Type getType() {
16 | return type;
17 | }
18 |
19 | public void setType(Type type) {
20 | this.type = type;
21 | }
22 |
23 | public String getFuncName() {
24 | return funcName;
25 | }
26 |
27 | public void setFuncName(String funcName) {
28 | this.funcName = funcName;
29 | }
30 |
31 | public String getName() {
32 | return name;
33 | }
34 |
35 | public void setName(String name) {
36 | this.name = name;
37 | }
38 |
39 | public boolean equals(Object other) {
40 | if (this.getClass() != other.getClass())
41 | return false;
42 | Variable otherObj = (Variable) other;
43 | return this.name.equals(otherObj.getName());
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/src/main/java/antl/ggggg.tokens:
--------------------------------------------------------------------------------
1 | T__21=21
2 | T__22=22
3 | T__23=23
4 | T__24=24
5 | T__25=25
6 | T__26=26
7 | T__27=27
8 | T__28=28
9 | T__29=29
10 | T__30=30
11 | T__31=31
12 | T__32=32
13 | T__33=33
14 | T__34=34
15 | T__35=35
16 | T__36=36
17 | T__37=37
18 | T__38=38
19 | T__39=39
20 | T__40=40
21 | T__41=41
22 | CLEAR_LINE=4
23 | COMMENT=5
24 | DEDENT=6
25 | ELSE=7
26 | ENDL=8
27 | FLOAT=9
28 | FOR=10
29 | FUNCTION=11
30 | ID=12
31 | IF=13
32 | INDENT=14
33 | INT=15
34 | MAIN=16
35 | STRING=17
36 | TAB=18
37 | WHILE=19
38 | WS=20
39 | '!='=21
40 | '%'=22
41 | '*'=23
42 | '+'=24
43 | ','=25
44 | '-'=26
45 | '/'=27
46 | ';'=6
47 | '<'=28
48 | '<='=29
49 | '='=30
50 | '=='=31
51 | '>'=32
52 | '>='=33
53 | 'Alin'=34
54 | 'Alout'=35
55 | '['=36
56 | ']'=37
57 | '^'=38
58 | 'float'=39
59 | 'int'=40
60 | 'return'=41
61 |
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/src/main/java/com/kadet/compiler/antlrManager/CompilerHelper.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.antlrManager;
2 |
3 | /**
4 | * Date: 13.02.14
5 | * Time: 21:06
6 | *
7 | * @author SarokaA
8 | */
9 | public class CompilerHelper {
10 |
11 | public static void compile (String src, String grammar) {
12 | org.antlr.Tool.main(
13 | new String[]{
14 | "-o",
15 | src,
16 | grammar});
17 | }
18 |
19 | }
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/test:
--------------------------------------------------------------------------------
1 | a=5;
2 | Alenafun fun [b,c]
3 | <<<<<<< HEAD
4 | return 0.0;
5 | =======
6 | d = 3.5;
7 | rez = d*15.0;
8 | c = [int]c;
9 | d = [int]c^5-2;
10 | if [d != 0]
11 | rez = [a+[int]b]/[c-2];
12 | return rez;
13 | else
14 | if [d != 0]
15 | rez = [a+[int]b]/[c-2];
16 | return rez;
17 | else
18 | return 0.0;
19 |
20 |
21 | Alenafun fun1 [b,c]
22 | d = 0;
23 | rez = 0;
24 | d = c-2;
25 | >>>>>>> 50d148d6a9a9a5e54a80fc0cd985011ec975056d
26 |
27 |
28 | Alenamain
29 | a = 0;
30 | b = 0;
31 | c = 0;
32 | <<<<<<< HEAD
33 | result = fun [b,c];
34 | if [result != 0.0]
35 | =======
36 | result=0;
37 | Alout["Введите a"];
38 | Alin[a];
39 | Alout["Введите b"];
40 | Alin[b];
41 | Alout["Введите c"];
42 | Alin[c];
43 | result = fun [b,c];
44 | if [result != 0]
45 | >>>>>>> 50d148d6a9a9a5e54a80fc0cd985011ec975056d
46 | Alout["(a+b)/(c-2)="];
47 | Alout [result];
48 | else
49 | Alout["На ноль делить нельзя!"];
50 |
51 |
52 |
--------------------------------------------------------------------------------
/1 Compiler/version2/Compiler/test-old:
--------------------------------------------------------------------------------
1 | a=5;
2 | Alenafun fun [b,c]
3 | d = 3.5;
4 | rez = d*15.0;
5 | c = [int]c;
6 | d = [int]c^5-2;
7 | if [d != 0]
8 | rez = [a+[int]b]/[c-2];
9 | return rez;
10 | else
11 | if [d != 0]
12 | rez = [a+[int]b]/[c-2];
13 | return rez;
14 | else
15 | return 0.0;
16 |
17 |
18 | Alenafun fun1 [b,c]
19 | d = 0;
20 | rez = 0;
21 | d = c-2;
22 |
23 |
24 | Alenamain
25 | a = 0;
26 | b = 0;
27 | c = 0;
28 | result=0;
29 | Alout["Введите a"];
30 | Alin[a];
31 | Alout["Введите b"];
32 | Alin[b];
33 | Alout["Введите c"];
34 | Alin[c];
35 | result = fun [b,c];
36 | if [result != 0]
37 | Alout["(a+b)/(c-2)="];
38 | Alout [result];
39 | else
40 | Alout["На ноль делить нельзя!"];
41 |
42 |
43 |
--------------------------------------------------------------------------------
/1 Compiler/version3/example/antlr3xtut-part9.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/1 Compiler/version3/example/antlr3xtut-part9.zip
--------------------------------------------------------------------------------
/1 Compiler/version3/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | org.meri
6 | antlr-step-by-step
7 | 0.0.1-SNAPSHOT
8 | jar
9 |
10 | antlr-step-by-step
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 | org.antlr
20 | antlr
21 | 3.3
22 | jar
23 | compile
24 |
25 |
26 | junit
27 | junit
28 | 4.8.2
29 | jar
30 | test
31 |
32 |
33 |
34 |
35 |
36 |
37 | org.antlr
38 | antlr3-maven-plugin
39 | 3.3
40 |
41 |
42 | run antlr
43 | generate-sources
44 |
45 | antlr
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | org.codehaus.mojo
54 | build-helper-maven-plugin
55 |
56 |
57 | add-source
58 | generate-sources
59 |
60 | add-source
61 |
62 |
63 |
64 | ${basedir}/target/generated-sources/antlr3
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/antlr3/com/kadet/compiler/EvaluatorWalker.g:
--------------------------------------------------------------------------------
1 | tree grammar EvaluatorWalker;
2 |
3 | options {
4 | language = Java;
5 | tokenVocab = Sample4;
6 | ASTLabelType = CommonTree;
7 | }
8 |
9 | @header {
10 | package com.kadet.compiler;
11 | import java.util.Map;
12 | import java.util.HashMap;
13 | }
14 |
15 | @members {
16 | private Map variables = new HashMap();
17 | }
18 |
19 | evaluator returns [int result]
20 | : assignment* e=expression EOF { result = e; }
21 | ;
22 |
23 | assignment
24 | : ^(':=' IDENT e=expression)
25 | { variables.put($IDENT.text, e); }
26 | ;
27 |
28 | expression returns [int result]
29 | : ^('+' op1=expression op2=expression) { result = op1 + op2; }
30 | | ^('-' op1=expression op2=expression) { result = op1 - op2; }
31 | | ^('*' op1=expression op2=expression) { result = op1 * op2; }
32 | | ^('/' op1=expression op2=expression) { result = op1 / op2; }
33 | | ^('%' op1=expression op2=expression) { result = op1 \% op2; }
34 | | ^(NEGATION e=expression) { result = -e; }
35 | | IDENT { result = variables.get($IDENT.text); }
36 | | INTEGER { result = Integer.parseInt($INTEGER.text); }
37 | ;
38 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/antlr3/com/kadet/compiler/Sample2.g:
--------------------------------------------------------------------------------
1 | grammar Sample2;
2 |
3 | options {
4 |
5 | // java lexer and parser
6 | language = Java;
7 |
8 | // abstract syntax tree
9 | output = AST;
10 |
11 | }
12 |
13 | @lexer::header {
14 | package com.kadet.compiler;
15 | }
16 |
17 | @parser::header {
18 | package com.kadet.compiler;
19 | }
20 |
21 |
22 | evaluator returns [int result]
23 | : expression EOF { $result = $expression.result; }
24 | ;
25 |
26 |
27 | // expressions fun time
28 |
29 | term returns [int result]
30 | : IDENT { $result = 0;}
31 | | '(' expression ')' { $result = $expression.result;}
32 | | INTEGER { $result = Integer.parseInt($INTEGER.text);}
33 | ;
34 |
35 |
36 | unary returns [int result]
37 | : { boolean positive = true;}
38 | ( '+'
39 | | '-' { positive = !positive; }
40 | )* term {
41 | $result = $term.result;
42 | if (!positive)
43 | $result = -$result;
44 | }
45 | ;
46 |
47 | mult returns [int result]
48 | : op1 = unary { $result = $op1.result; }
49 | ( '*' op2 = unary { $result = $result * $op2.result; }
50 | | '/' op2 = unary { $result = $result / $op2.result; }
51 | | 'mod' op2 = unary { $result = $result \% $op2.result; }
52 | )*
53 | ;
54 |
55 | expression returns [int result]
56 | : op1 = mult {$result = $op1.result;}
57 | ( '+' op2 = mult { $result = $result + $op2.result; }
58 | | '-' op2 = mult { $result = $result - $op2.result; }
59 | )*
60 | ;
61 |
62 | fragment LETTER
63 | : ('a'..'z' | 'A'..'Z')
64 | ;
65 |
66 | fragment DIGIT
67 | : '0'..'9'
68 | ;
69 |
70 | IDENT
71 | : ( LETTER )( LETTER | DIGIT )*
72 | ;
73 |
74 | INTEGER
75 | : DIGIT+
76 | ;
77 |
78 | STRING_LITERAL
79 | : '"'
80 | {
81 | StringBuilder b = new StringBuilder();
82 | }
83 | (
84 | ('\\' '"') { b.appendCodePoint('"');}
85 | |
86 | c = ~( '"' | '\r' | '\n' ) { b.appendCodePoint(c);}
87 | )*
88 | '"'
89 | { setText (b.toString());}
90 | ;
91 |
92 | CHAR_LITERAL
93 | : '\'' . '\'' {setText(getText().substring(1, 2));}
94 | ;
95 |
96 | WS
97 | : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}
98 | ;
99 |
100 | COMMENT
101 | : '//' .* ('\n' | '\r') {$channel = HIDDEN;}
102 | ;
103 |
104 | MULTIPLE_COMMENT
105 | : '/*' .* '*/' {$channel = HIDDEN;}
106 | ;
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/antlr3/com/kadet/compiler/Sample3.g:
--------------------------------------------------------------------------------
1 | grammar Sample3;
2 |
3 | options {
4 |
5 | // java lexer and parser
6 | language = Java;
7 |
8 | // abstract syntax tree
9 | output = AST;
10 |
11 | }
12 |
13 | @lexer::header {
14 | package com.kadet.compiler;
15 |
16 | import com.kadet.compiler.evaluators.*;
17 | }
18 |
19 | @parser::header {
20 | package com.kadet.compiler;
21 |
22 | import com.kadet.compiler.evaluators.*;
23 | }
24 |
25 |
26 | evaluator returns [Evaluator e]
27 | : expression EOF { $e = $expression.e; }
28 | ;
29 |
30 |
31 | // expressions fun time
32 |
33 | term returns [Evaluator e]
34 | : IDENT { $e = new IntEvaluator(0); }
35 | | '(' expression ')' { $e = $expression.e; }
36 | | INTEGER { $e = new IntEvaluator(Integer.parseInt($INTEGER.text)); }
37 | ;
38 |
39 |
40 | unary returns [Evaluator e]
41 | : { boolean positive = true;}
42 | ( '+'
43 | | '-' { positive = !positive; }
44 | )* term {
45 | $e = $term.e;
46 | if (!positive)
47 | $e = new NegationEvaluator($e);
48 | }
49 | ;
50 |
51 | mult returns [Evaluator e]
52 | : op1 = unary { $e = $op1.e; }
53 | ( '*' op2 = unary { $e = new TimesEvaluator($e, $op2.e); }
54 | | '/' op2 = unary { $e = new DivideEvaluator($e, $op2.e); }
55 | | 'mod' op2 = unary { $e = new ModEvaluator($e, $op2.e); }
56 | )*
57 | ;
58 |
59 | expression returns [Evaluator e]
60 | : op1 = mult { $e = $op1.e;}
61 | ( '+' op2 = mult { $e = new PlusEvaluator($e, $op2.e); }
62 | | '-' op2 = mult { $e = new MinusEvaluator($e, $op2.e); }
63 | )*
64 | ;
65 |
66 | fragment LETTER
67 | : ('a'..'z' | 'A'..'Z')
68 | ;
69 |
70 | fragment DIGIT
71 | : '0'..'9'
72 | ;
73 |
74 | IDENT
75 | : ( LETTER )( LETTER | DIGIT )*
76 | ;
77 |
78 | INTEGER
79 | : DIGIT+
80 | ;
81 |
82 | STRING_LITERAL
83 | : '"'
84 | {
85 | StringBuilder b = new StringBuilder();
86 | }
87 | (
88 | ('\\' '"') { b.appendCodePoint('"');}
89 | |
90 | c = ~( '"' | '\r' | '\n' ) { b.appendCodePoint(c);}
91 | )*
92 | '"'
93 | { setText (b.toString());}
94 | ;
95 |
96 | CHAR_LITERAL
97 | : '\'' . '\'' {setText(getText().substring(1, 2));}
98 | ;
99 |
100 | WS
101 | : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}
102 | ;
103 |
104 | COMMENT
105 | : '//' .* ('\n' | '\r') {$channel = HIDDEN;}
106 | ;
107 |
108 | MULTIPLE_COMMENT
109 | : '/*' .* '*/' {$channel = HIDDEN;}
110 | ;
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/antlr3/com/kadet/compiler/Sample4.g:
--------------------------------------------------------------------------------
1 | grammar Sample4;
2 |
3 | options {
4 | language = Java;
5 | output=AST;
6 | ASTLabelType=CommonTree;
7 | }
8 |
9 | tokens {
10 | NEGATION;
11 | }
12 |
13 |
14 | @header {
15 | package com.kadet.compiler;
16 | }
17 |
18 |
19 | @lexer::header {
20 | package com.kadet.compiler;
21 | }
22 |
23 |
24 |
25 | evaluator
26 | : assignment* expression EOF!
27 | ;
28 |
29 |
30 | assignment
31 | : IDENT ':='^ expression ';'^
32 | ;
33 |
34 | term
35 | : IDENT
36 | | '('! expression ')'!
37 | | INTEGER
38 | ;
39 |
40 | unary
41 | : ('+'! | negation^)* term
42 | ;
43 |
44 | negation
45 | : '-' -> NEGATION
46 | ;
47 |
48 | add
49 | : unary ( ('+'^ | '-'^) unary)*
50 | ;
51 |
52 | mult
53 | : add ( ('*'^ | '/'^ | 'mod'^) add)*
54 | ;
55 |
56 | expression
57 | : mult ( ('and' | 'or') mult)*
58 | ;
59 |
60 |
61 |
62 | fragment LETTER
63 | : ('a'..'z' | 'A'..'Z')
64 | ;
65 |
66 | fragment DIGIT
67 | : '0'..'9'
68 | ;
69 |
70 | IDENT
71 | : ( LETTER )( LETTER | DIGIT )*
72 | ;
73 |
74 | INTEGER
75 | : DIGIT+
76 | ;
77 |
78 |
79 | WS
80 | : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}
81 | ;
82 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/AbstractCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.tree.CommonTree;
4 |
5 | /**
6 | * Date: 27.02.14
7 | * Time: 1:27
8 | *
9 | * @author SarokaA
10 | */
11 | public abstract class AbstractCompiler {
12 |
13 | public abstract CommonTree compile (String expression);
14 |
15 | protected void printTree (CommonTree ast) {
16 | print(ast, 0);
17 | }
18 |
19 | private void print (CommonTree tree, int level) {
20 | //indent level
21 | for (int i = 0; i < level; i++)
22 | System.out.print("--");
23 |
24 | //print node description: type code followed by token text
25 | System.out.println(" " + tree.getType() + " " + tree.getText());
26 |
27 | //print all children
28 | if (tree.getChildren() != null)
29 | for (Object ie : tree.getChildren()) {
30 | print((CommonTree) ie, level + 1);
31 | }
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/Sample2Compiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 |
9 | public class Sample2Compiler extends AbstractCompiler{
10 |
11 |
12 | public CommonTree compile(String expression) {
13 | try {
14 | System.out.println("expression: " + expression);
15 |
16 | //lexer splits input into tokens
17 | ANTLRStringStream input = new ANTLRStringStream(expression);
18 | Sample2Lexer lexer = new Sample2Lexer(input);
19 | TokenStream tokens = new CommonTokenStream(lexer);
20 |
21 | //parser generates abstract syntax tree
22 | Sample2Parser parser = new Sample2Parser(tokens);
23 | Sample2Parser.evaluator_return programReturn = parser.evaluator();
24 |
25 | System.out.println("result = " + programReturn.result);
26 |
27 | //acquire parse result
28 | CommonTree ast = (CommonTree) programReturn.tree;
29 | printTree(ast);
30 | return ast;
31 |
32 | } catch (RecognitionException e) {
33 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
34 | }
35 |
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/Sample3Compiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 |
9 | public class Sample3Compiler extends AbstractCompiler{
10 |
11 |
12 | public CommonTree compile(String expression) {
13 | try {
14 | System.out.println("expression: " + expression);
15 |
16 | //lexer splits input into tokens
17 | ANTLRStringStream input = new ANTLRStringStream(expression);
18 | Sample3Lexer lexer = new Sample3Lexer(input);
19 | TokenStream tokens = new CommonTokenStream(lexer);
20 |
21 | //parser generates abstract syntax tree
22 | Sample3Parser parser = new com.kadet.compiler.Sample3Parser(tokens);
23 | Sample3Parser.evaluator_return programReturn = parser.evaluator();
24 |
25 | System.out.println("result = " + programReturn.e.evaluate());
26 |
27 | //acquire parse result
28 | CommonTree ast = (CommonTree) programReturn.tree;
29 | printTree(ast);
30 | return ast;
31 |
32 | } catch (RecognitionException e) {
33 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
34 | }
35 |
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/Sample4Compiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 | import org.antlr.runtime.tree.CommonTreeNodeStream;
9 |
10 | public class Sample4Compiler extends AbstractCompiler{
11 |
12 |
13 | public CommonTree compile(String expression) {
14 | try {
15 | System.out.println("expression: " + expression);
16 |
17 | //lexer splits input into tokens
18 | ANTLRStringStream input = new ANTLRStringStream(expression);
19 | Sample4Lexer lexer = new Sample4Lexer(input);
20 | TokenStream tokens = new CommonTokenStream(lexer);
21 |
22 | //parser generates abstract syntax tree
23 | Sample4Parser parser = new Sample4Parser(tokens);
24 |
25 | Sample4Parser.evaluator_return evaluator = parser.evaluator();
26 | CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(evaluator.tree);
27 | EvaluatorWalker walker = new EvaluatorWalker(nodeStream);
28 | int result = walker.evaluator();
29 | System.out.println("ok - result = " + result);
30 |
31 |
32 | /*System.out.println("result = " + programReturn.result);
33 |
34 | //acquire parse result
35 | CommonTree ast = (CommonTree) programReturn.tree;
36 | System.out.println(ast.toStringTree());
37 | // printTree(ast);
38 | return ast;*/
39 | return null;
40 |
41 | } catch (RecognitionException e) {
42 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
43 | }
44 |
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/SampleCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 |
9 | public class SampleCompiler extends AbstractCompiler{
10 |
11 |
12 | public CommonTree compile(String expression) {
13 | try {
14 | System.out.println("expression: " + expression);
15 |
16 | //lexer splits input into tokens
17 | ANTLRStringStream input = new ANTLRStringStream(expression);
18 | SampleLexer lexer = new SampleLexer(input);
19 | TokenStream tokens = new CommonTokenStream(lexer);
20 |
21 | //parser generates abstract syntax tree
22 | SampleParser parser = new SampleParser(tokens);
23 | SampleParser.program_return programReturn = parser.program();
24 |
25 | //acquire parse result
26 | CommonTree ast = (CommonTree) programReturn.tree;
27 | printTree(ast);
28 | return ast;
29 |
30 | } catch (RecognitionException e) {
31 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
32 | }
33 |
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/evaluators/DivideEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class DivideEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public DivideEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() / op2.evaluate(); //To change body of implemented methods use File | Settings | File Templates.
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/evaluators/Evaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:22
6 | *
7 | * @author Кадет
8 | */
9 | public interface Evaluator {
10 |
11 | int evaluate ();
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/evaluators/IntEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:25
6 | *
7 | * @author Кадет
8 | */
9 | public class IntEvaluator implements Evaluator {
10 |
11 | private int value;
12 |
13 | public IntEvaluator (int value) {
14 | this.value = value;
15 | }
16 |
17 | @Override
18 | public int evaluate () {
19 | return value; //To change body of implemented methods use File | Settings | File Templates.
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/evaluators/MinusEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class MinusEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public MinusEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() - op2.evaluate(); //To change body of implemented methods use File | Settings | File Templates.
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/evaluators/ModEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class ModEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public ModEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() % op2.evaluate(); //To change body of implemented methods use File | Settings | File Templates.
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/evaluators/NegationEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class NegationEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 |
13 | public NegationEvaluator (Evaluator op1) {
14 | this.op1 = op1;
15 | }
16 |
17 | @Override
18 | public int evaluate () {
19 | return -op1.evaluate();
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/evaluators/PlusEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class PlusEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public PlusEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() + op2.evaluate(); //To change body of implemented methods use File | Settings | File Templates.
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/main/java/com/kadet/compiler/evaluators/TimesEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class TimesEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public TimesEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() * op2.evaluate();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/test/java/com/kadet/compiler/Sample2Test.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.junit.Test;
4 |
5 | public class Sample2Test {
6 |
7 | @Test
8 | public void expressionEvaluation () {
9 | Sample2Compiler sample2Compiler = new Sample2Compiler();
10 | sample2Compiler.compile("4 * 3\n\r");
11 | }
12 |
13 | @Test
14 | public void bigExpressionEvaluation () {
15 | Sample2Compiler sample2Compiler = new Sample2Compiler();
16 | sample2Compiler.compile("3 * (4 + 2) - 3\n\r");
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/test/java/com/kadet/compiler/Sample3Test.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.junit.Test;
4 |
5 | public class Sample3Test {
6 |
7 | @Test
8 | public void expressionEvaluation () {
9 | Sample3Compiler sample3Compiler = new Sample3Compiler();
10 | sample3Compiler.compile("4 * 3\n\r");
11 | }
12 |
13 | @Test
14 | public void bigExpressionEvaluation () {
15 | Sample3Compiler sample3Compiler = new Sample3Compiler();
16 | sample3Compiler.compile("3 * (4 + 2) - 3\n\r");
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/1 Compiler/version3/src/test/java/com/kadet/compiler/Sample4Test.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.junit.Test;
4 |
5 | public class Sample4Test {
6 |
7 | @Test
8 | public void expressionEvaluation () {
9 | Sample4Compiler sample4Compiler = new Sample4Compiler();
10 | sample4Compiler.compile("4 * 3\n\r");
11 | }
12 |
13 | @Test
14 | public void bigExpressionEvaluation () {
15 | Sample4Compiler sample4Compiler = new Sample4Compiler();
16 | sample4Compiler.compile("x := 4; y := 3; 3 * (-x+y)*3\n\r");
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/AbstractCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.tree.CommonTree;
4 |
5 | /**
6 | * Date: 27.02.14
7 | * Time: 1:27
8 | *
9 | * @author SarokaA
10 | */
11 | public abstract class AbstractCompiler {
12 |
13 | public abstract CommonTree compile (String expression);
14 |
15 | protected void printTree (CommonTree ast) {
16 | print(ast, 0);
17 | }
18 |
19 | private void print (CommonTree tree, int level) {
20 | //indent level
21 | for (int i = 0; i < level; i++)
22 | System.out.print("--");
23 |
24 | //print node description: type code followed by token text
25 | System.out.println(" " + tree.getType() + " " + tree.getText());
26 |
27 | //print all children
28 | if (tree.getChildren() != null)
29 | for (Object ie : tree.getChildren()) {
30 | print((CommonTree) ie, level + 1);
31 | }
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/Edge.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | /**
4 | * Date: 27.02.14
5 | * Time: 3:55
6 | *
7 | * @author SarokaA
8 | */
9 | public class Edge {
10 |
11 | private Vertex fromVertex;
12 | private Vertex toVertex;
13 | private Double weight;
14 |
15 | public Edge() {
16 | }
17 |
18 | public Edge(Vertex fromVertex,
19 | Vertex toVertex,
20 | Double weight) {
21 | this.fromVertex = fromVertex;
22 | this.toVertex = toVertex;
23 | this.weight = weight;
24 | }
25 |
26 | @Override
27 | public String toString() {
28 | return fromVertex.getLabel() +
29 | " to " + toVertex.getLabel() +
30 | " with weight " + getWeight();
31 | }
32 |
33 | public Vertex getFromVertex() {
34 | return fromVertex;
35 | }
36 |
37 | public void setFromVertex(Vertex fromVertex) {
38 | this.fromVertex = fromVertex;
39 | }
40 |
41 | public Vertex getToVertex() {
42 | return toVertex;
43 | }
44 |
45 | public void setToVertex(Vertex toVertex) {
46 | this.toVertex = toVertex;
47 | }
48 |
49 | public Double getWeight() {
50 | return weight;
51 | }
52 |
53 | public void setWeight(Double weight) {
54 | this.weight = weight;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/Graph.g:
--------------------------------------------------------------------------------
1 | grammar Graph;
2 |
3 | options {
4 |
5 | // java lexer and parser
6 | language = Java;
7 |
8 | // abstract syntax tree
9 | output = AST;
10 |
11 | }
12 |
13 | @lexer::header {
14 | package com.kadet.compiler;
15 | }
16 |
17 | @parser::header {
18 | package com.kadet.compiler;
19 | }
20 |
21 |
22 |
23 | ID
24 | : ('a'..'z'|'A'..'Z') ('a'..'z'|'A'..'Z')*
25 | ;
26 |
27 |
28 |
29 | NUM
30 | : ('0'..'9')+
31 | ;
32 |
33 |
34 | vertex
35 | : ID
36 | ;
37 |
38 | edge
39 | : vertex '->' vertex '(' NUM ')'
40 | ;
41 |
42 | graph
43 | : 'Graph {' edge+ '}';
--------------------------------------------------------------------------------
/1 Compiler/version3Old/Graph.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Set;
6 | import java.util.TreeSet;
7 |
8 | /**
9 | * Date: 27.02.14
10 | * Time: 3:54
11 | *
12 | * @author SarokaA
13 | */
14 | public class Graph {
15 | private List edges;
16 | private Set vertices;
17 |
18 | public Graph() {
19 | edges = new ArrayList();
20 | vertices = new TreeSet();
21 | }
22 | public void addEdge(Edge edge){
23 | getEdges().add(edge);
24 | getVertices().add(edge.getFromVertex());
25 | getVertices().add(edge.getToVertex());
26 | }
27 |
28 | public void addVertice(Vertex v){
29 | getVertices().add(v);
30 | }
31 |
32 | public List getEdges() {
33 | return edges;
34 | }
35 |
36 | public Set getVertices() {
37 | return vertices;
38 | }
39 |
40 | public static void printGraph(Graph g){
41 | System.out.println("Vertices...");
42 | for (Vertex v : g.getVertices()) {
43 | System.out.print(v.getLabel() + " ");
44 | }
45 | System.out.println("");
46 | System.out.println("Edges...");
47 | for (Edge e : g.getEdges()) {
48 | System.out.println(e);
49 | }
50 | }
51 |
52 | }
53 |
54 |
55 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/GraphCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 |
9 | public class GraphCompiler extends AbstractCompiler {
10 |
11 | public CommonTree compile(String expression) {
12 | try {
13 | //lexer splits input into tokens
14 | ANTLRStringStream input = new ANTLRStringStream(expression);
15 | TokenStream tokens = new CommonTokenStream(new S001HelloWordLexer(input));
16 |
17 | //parser generates abstract syntax tree
18 | S001HelloWordParser parser = new S001HelloWordParser(tokens);
19 | S001HelloWordParser.expression_return ret = parser.expression();
20 |
21 | //acquire parse result
22 | CommonTree ast = (CommonTree) ret.tree;
23 | printTree(ast);
24 | return ast;
25 | } catch (RecognitionException e) {
26 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
27 | }
28 | }
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/ListGrammarCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 |
9 | /**
10 | * Date: 02.03.14
11 | * Time: 17:53
12 | *
13 | * @author Кадет
14 | */
15 | public class ListGrammarCompiler extends AbstractCompiler {
16 |
17 | public CommonTree compile(String expression) {
18 | try {
19 | //lexer splits input into tokens
20 | ANTLRStringStream input = new ANTLRStringStream(expression);
21 | TokenStream tokens = new CommonTokenStream(new S001HelloWordLexer(input));
22 |
23 | //parser generates abstract syntax tree
24 | S001HelloWordParser parser = new S001HelloWordParser(tokens);
25 | S001HelloWordParser.expression_return ret = parser.expression();
26 |
27 | //acquire parse result
28 | CommonTree ast = (CommonTree) ret.tree;
29 | printTree(ast);
30 | return ast;
31 | } catch (RecognitionException e) {
32 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
33 | }
34 | }
35 |
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/ListGrammarTest.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.junit.Test;
4 |
5 | public class ListGrammarTest {
6 |
7 | @Test
8 | public void correctTest () {
9 | SimpleGrammarCompiler compiler = new SimpleGrammarCompiler();
10 | compiler.compile("int a, b;");
11 | }
12 |
13 | @Test
14 | public void incorrectTest () {
15 | SimpleGrammarCompiler compiler = new SimpleGrammarCompiler();
16 | compiler.compile("int a, b");
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S001HelloWord.g:
--------------------------------------------------------------------------------
1 | grammar S001HelloWord;
2 |
3 | options {
4 |
5 | // java lexer and parser
6 | language = Java;
7 |
8 | // abstract syntax tree
9 | output = AST;
10 |
11 | }
12 |
13 | @lexer::header {
14 | package com.kadet.compiler;
15 | }
16 |
17 | @parser::header {
18 | package com.kadet.compiler;
19 | }
20 |
21 |
22 | SALUTATION: 'Hello World';
23 | ENDSYMBOL: '!';
24 |
25 | expression: SALUTATION ENDSYMBOL;
26 |
27 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S001HelloWordCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 |
9 | public class S001HelloWordCompiler extends AbstractCompiler {
10 |
11 | public CommonTree compile(String expression) {
12 | try {
13 | //lexer splits input into tokens
14 | ANTLRStringStream input = new ANTLRStringStream(expression);
15 | TokenStream tokens = new CommonTokenStream(new S001HelloWordLexer(input));
16 |
17 | //parser generates abstract syntax tree
18 | S001HelloWordParser parser = new S001HelloWordParser(tokens);
19 | S001HelloWordParser.expression_return ret = parser.expression();
20 |
21 | //acquire parse result
22 | CommonTree ast = (CommonTree) ret.tree;
23 | printTree(ast);
24 | return ast;
25 | } catch (RecognitionException e) {
26 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
27 | }
28 | }
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S001HelloWordTest.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.antlr.runtime.tree.CommonTree;
6 | import org.junit.Test;
7 |
8 | public class S001HelloWordTest {
9 |
10 | /**
11 | * Abstract syntax tree generated from "Hello word!" should have an unnamed
12 | * root node with two children. First child corresponds to salutation token
13 | * and second child corresponds to end symbol token.
14 | *
15 | * Token type constants are defined in generated S001HelloWordParser class.
16 | */
17 | @Test
18 | public void testCorrectExpression() {
19 | //compile the expression
20 | S001HelloWordCompiler compiler = new S001HelloWordCompiler();
21 | CommonTree ast = compiler.compile("Hello World!");
22 |
23 | //check AST structure
24 | assertEquals(S001HelloWordParser.SALUTATION, ast.getChild(0).getType());
25 | assertEquals(S001HelloWordParser.ENDSYMBOL, ast.getChild(1).getType());
26 | }
27 |
28 |
29 | @Test
30 | public void testBiggerError() {
31 | //compile the expression
32 | S001HelloWordCompiler compiler = new S001HelloWordCompiler();
33 | CommonTree ast = compiler.compile("Bye!");
34 | //check AST structure
35 | assertEquals(S001HelloWordParser.SALUTATION, ast.getChild(0).getType());
36 | assertEquals(S001HelloWordParser.ENDSYMBOL, ast.getChild(1).getType());
37 | }
38 |
39 |
40 | @Test
41 | public void testCompletelyWrong() {
42 | //compile the expression
43 | S001HelloWordCompiler compiler = new S001HelloWordCompiler();
44 | CommonTree ast = compiler.compile("Incorrect Expression");
45 |
46 | //check AST structure
47 | assertEquals(0, ast.getChildCount());
48 | }
49 |
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S002HelloWord.g:
--------------------------------------------------------------------------------
1 | grammar S002HelloWord;
2 |
3 | options {
4 |
5 | // java lexer and parser
6 | language = Java;
7 |
8 | // abstract syntax tree
9 | output = AST;
10 |
11 | }
12 |
13 | @lexer::header {
14 | package com.kadet.compiler;
15 | }
16 |
17 | @parser::header {
18 | package com.kadet.compiler;
19 | import com.kadet.compiler.S002HelloWordCompiler.S002HelloWordError;
20 | }
21 |
22 |
23 | SALUTATION: 'Hello World';
24 | ENDSYMBOL: '!';
25 |
26 | expression: SALUTATION ENDSYMBOL;
27 | catch[RecognitionException e] {
28 | throw new S002HelloWordError(":(", e);
29 | }
30 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S002HelloWordCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 | import org.omg.CORBA._PolicyStub;
9 |
10 | public class S002HelloWordCompiler extends AbstractCompiler{
11 |
12 | public CommonTree compile(String expression) {
13 | try {
14 | //lexer splits input into tokens
15 | ANTLRStringStream input = new ANTLRStringStream(expression);
16 | TokenStream tokens = new CommonTokenStream(new S001HelloWordLexer(input));
17 |
18 | //parser generates abstract syntax tree
19 | S002HelloWordParser parser = new S002HelloWordParser(tokens);
20 | S002HelloWordParser.expression_return ret = parser.expression();
21 |
22 | //acquire parse result
23 | CommonTree ast = (CommonTree) ret.tree;
24 | printTree(ast);
25 | return ast;
26 | } catch (RecognitionException e) {
27 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
28 | }
29 | }
30 |
31 | @SuppressWarnings("serial")
32 | public static class S002HelloWordError extends RuntimeException {
33 |
34 | public S002HelloWordError(String message, Throwable cause) {
35 | super(message, cause);
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S002HelloWordTest.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.antlr.runtime.tree.CommonTree;
6 | import org.junit.Test;
7 |
8 | public class S002HelloWordTest {
9 |
10 | /**
11 | * Abstract syntax tree generated from "Hello word!" should have an unnamed
12 | * root node with two children. First child corresponds to salutation token
13 | * and second child corresponds to end symbol token.
14 | *
15 | * Token type constants are defined in generated S001HelloWordParser class.
16 | */
17 | @Test
18 | public void testCorrectExpression() {
19 | //compile the expression
20 | S002HelloWordCompiler compiler = new S002HelloWordCompiler();
21 | CommonTree ast = compiler.compile("Hello World?");
22 |
23 | //check AST structure
24 | assertEquals(S002HelloWordParser.SALUTATION, ast.getChild(0).getType());
25 | assertEquals(S002HelloWordParser.ENDSYMBOL, ast.getChild(1).getType());
26 | }
27 |
28 |
29 | @Test(expected = S002HelloWordCompiler.S002HelloWordError.class)
30 | public void testCompletelyWrong() {
31 | //compile the expression
32 | S002HelloWordCompiler compiler = new S002HelloWordCompiler();
33 | CommonTree ast = compiler.compile("Incorrect Expression");
34 |
35 | //check AST structure
36 | assertEquals(0, ast.getChildCount());
37 | }
38 |
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S003HelloWord.g:
--------------------------------------------------------------------------------
1 | grammar S003HelloWord;
2 |
3 | options {
4 |
5 | // java lexer and parser
6 | language = Java;
7 |
8 | // abstract syntax tree
9 | output = AST;
10 |
11 | }
12 |
13 | @lexer::header {
14 | package com.kadet.compiler;
15 | }
16 |
17 | @parser::header {
18 | package com.kadet.compiler;
19 | import com.kadet.compiler.S003HelloWordCompiler.S003HelloWordError;
20 | }
21 |
22 | @rulecatch {
23 | catch(RecognitionException e) {
24 | throw new S003HelloWordError(":(", e);
25 | }
26 | }
27 |
28 | SALUTATION: 'Hello World';
29 | ENDSYMBOL: '!';
30 |
31 | expression: SALUTATION ENDSYMBOL;
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S003HelloWordCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 | import org.omg.CORBA._PolicyStub;
9 |
10 | public class S003HelloWordCompiler extends AbstractCompiler{
11 |
12 | public CommonTree compile(String expression) {
13 | try {
14 | //lexer splits input into tokens
15 | ANTLRStringStream input = new ANTLRStringStream(expression);
16 | TokenStream tokens = new CommonTokenStream(new S001HelloWordLexer(input));
17 |
18 | //parser generates abstract syntax tree
19 | S003HelloWordParser parser = new S003HelloWordParser(tokens);
20 | S003HelloWordParser.expression_return ret = parser.expression();
21 |
22 | //acquire parse result
23 | CommonTree ast = (CommonTree) ret.tree;
24 | printTree(ast);
25 | return ast;
26 | } catch (RecognitionException e) {
27 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
28 | }
29 | }
30 |
31 | @SuppressWarnings("serial")
32 | public static class S003HelloWordError extends RuntimeException {
33 |
34 | public S003HelloWordError(String message, Throwable cause) {
35 | super(message, cause);
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S003HelloWordTest.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.antlr.runtime.tree.CommonTree;
6 | import org.junit.Test;
7 |
8 | public class S003HelloWordTest {
9 |
10 | /**
11 | * Abstract syntax tree generated from "Hello word!" should have an unnamed
12 | * root node with two children. First child corresponds to salutation token
13 | * and second child corresponds to end symbol token.
14 | *
15 | * Token type constants are defined in generated S001HelloWordParser class.
16 | */
17 | @Test
18 | public void testCorrectExpression() {
19 | //compile the expression
20 | S003HelloWordCompiler compiler = new S003HelloWordCompiler();
21 | CommonTree ast = compiler.compile("Hello World?");
22 |
23 | //check AST structure
24 | assertEquals(S002HelloWordParser.SALUTATION, ast.getChild(0).getType());
25 | assertEquals(S002HelloWordParser.ENDSYMBOL, ast.getChild(1).getType());
26 | }
27 |
28 |
29 | @Test(expected = S003HelloWordCompiler.S003HelloWordError.class)
30 | public void testCompletelyWrong() {
31 | //compile the expression
32 | S003HelloWordCompiler compiler = new S003HelloWordCompiler();
33 | CommonTree ast = compiler.compile("Incorrect Expression");
34 |
35 | //check AST structure
36 | assertEquals(0, ast.getChildCount());
37 | }
38 |
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S004HelloWord.g:
--------------------------------------------------------------------------------
1 | grammar S004HelloWord;
2 |
3 | options {
4 |
5 | // java lexer and parser
6 | language = Java;
7 |
8 | // abstract syntax tree
9 | output = AST;
10 |
11 | }
12 |
13 | @lexer::header {
14 | package com.kadet.compiler;
15 | }
16 |
17 | @parser::header {
18 | package com.kadet.compiler;
19 | import com.kadet.compiler.S002HelloWordCompiler.S002HelloWordError;
20 | }
21 |
22 |
23 | @lexer::members {
24 |
25 | private List errors = new ArrayList();
26 |
27 | public List getAllErrors () {
28 | return new ArrayList(errors);
29 | }
30 |
31 | public boolean hasErrors () {
32 | return !errors.isEmpty();
33 | }
34 |
35 | public void reportError (RecognitionException e) {
36 | errors.add(e);
37 | displayRecognitionError(this.getTokenNames(), e);
38 | }
39 |
40 | }
41 |
42 | @parser::members {
43 |
44 | private List errors = new ArrayList();
45 |
46 | public List getAllErrors () {
47 | return new ArrayList(errors);
48 | }
49 |
50 | public boolean hasErrors () {
51 | return !errors.isEmpty();
52 | }
53 |
54 | public void reportError (RecognitionException e) {
55 | errors.add(e);
56 | displayRecognitionError(this.getTokenNames(), e);
57 | }
58 |
59 | }
60 |
61 |
62 |
63 |
64 | SALUTATION: 'Hello World';
65 | ENDSYMBOL: '!';
66 |
67 | expression: SALUTATION ENDSYMBOL;
68 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S004HelloWordCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 | import org.omg.CORBA._PolicyStub;
9 |
10 | import java.util.ArrayList;
11 | import java.util.List;
12 |
13 | public class S004HelloWordCompiler extends AbstractCompiler{
14 |
15 | private List errors = new ArrayList();
16 |
17 | public CommonTree compile(String expression) {
18 | try {
19 | System.out.println("expression: " + expression);
20 |
21 | // clean error logs
22 | errors = new ArrayList();
23 |
24 | //lexer splits input into tokens
25 | ANTLRStringStream input = new ANTLRStringStream(expression);
26 | S004HelloWordLexer lexer = new S004HelloWordLexer(input);
27 | TokenStream tokens = new CommonTokenStream(lexer);
28 |
29 | //parser generates abstract syntax tree
30 | S004HelloWordParser parser = new S004HelloWordParser(tokens);
31 | S004HelloWordParser.expression_return ret = parser.expression();
32 |
33 | if (lexer.hasErrors()) {
34 | errors.addAll(lexer.getAllErrors());
35 | }
36 |
37 | if (parser.hasErrors()) {
38 | errors.addAll(parser.getAllErrors());
39 | }
40 |
41 |
42 | //acquire parse result
43 | CommonTree ast = (CommonTree) ret.tree;
44 | printTree(ast);
45 | return ast;
46 |
47 | } catch (RecognitionException e) {
48 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
49 | }
50 |
51 | }
52 |
53 | public List getErrors() {
54 | return errors;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/S004HelloWordTest.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.antlr.runtime.tree.CommonTree;
6 | import org.junit.Test;
7 |
8 | public class S004HelloWordTest {
9 |
10 | /**
11 | * Abstract syntax tree generated from "Hello word!" should have an unnamed
12 | * root node with two children. First child corresponds to salutation token
13 | * and second child corresponds to end symbol token.
14 | *
15 | * Token type constants are defined in generated S001HelloWordParser class.
16 | */
17 | @Test
18 | public void testCorrectExpression() {
19 | //compile the expression
20 | S004HelloWordCompiler compiler = new S004HelloWordCompiler();
21 | CommonTree ast = compiler.compile("Hello World!");
22 |
23 | assertEquals(0, compiler.getErrors().size());
24 |
25 | //check AST structure
26 | assertEquals(S004HelloWordParser.SALUTATION, ast.getChild(0).getType());
27 | assertEquals(S004HelloWordParser.ENDSYMBOL, ast.getChild(1).getType());
28 | }
29 |
30 | @Test
31 | public void testSmallerError () {
32 |
33 | S004HelloWordCompiler compiler = new S004HelloWordCompiler();
34 | CommonTree commonTree = compiler.compile("Hello World?");
35 |
36 | assertEquals(2, compiler.getErrors().size());
37 |
38 | }
39 |
40 | @Test
41 | public void testBiggerError() {
42 |
43 | S004HelloWordCompiler compiler = new S004HelloWordCompiler();
44 | CommonTree commonTree = compiler.compile("Bye!");
45 |
46 | assertEquals(4, compiler.getErrors().size());
47 |
48 | }
49 |
50 | @Test()
51 | public void testCompletelyWrong () {
52 |
53 | S004HelloWordCompiler compiler = new S004HelloWordCompiler();
54 | CommonTree commonTree = compiler.compile("Incorrect Expression");
55 |
56 | assertEquals(21, compiler.getErrors().size());
57 |
58 | }
59 |
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/SimpleGrammar.g:
--------------------------------------------------------------------------------
1 | grammar SimpleGrammar;
2 |
3 | options {
4 |
5 | // java lexer and parser
6 | language = Java;
7 |
8 | // abstract syntax tree
9 | output = AST;
10 |
11 | }
12 |
13 | @lexer::header {
14 | package com.kadet.compiler;
15 | }
16 |
17 | @parser::header {
18 | package com.kadet.compiler;
19 | }
20 |
21 |
22 |
23 | DATATYPE
24 | : 'int'|'float'
25 | ;
26 |
27 |
28 | ID
29 | : ('a'..'z'|'A'..'Z'|'_')('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'.'|'a'..'z'|'A'..'Z')*
30 | ;
31 |
32 | COMMA
33 | : ','
34 | ;
35 |
36 | SEMICOLON
37 | : ';'
38 | ;
39 |
40 |
41 |
42 |
43 | decl
44 | : DATATYPE ID(',' ID)* SEMICOLON
45 | ;
--------------------------------------------------------------------------------
/1 Compiler/version3Old/SimpleGrammarCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 | import org.omg.CORBA._PolicyStub;
9 |
10 | import java.util.ArrayList;
11 | import java.util.List;
12 |
13 | public class SimpleGrammarCompiler extends AbstractCompiler{
14 |
15 |
16 | public CommonTree compile(String expression) {
17 | try {
18 | System.out.println("expression: " + expression);
19 |
20 | //lexer splits input into tokens
21 | ANTLRStringStream input = new ANTLRStringStream(expression);
22 | SimpleGrammarLexer lexer = new SimpleGrammarLexer(input);
23 | TokenStream tokens = new CommonTokenStream(lexer);
24 |
25 | //parser generates abstract syntax tree
26 | SimpleGrammarParser parser = new SimpleGrammarParser(tokens);
27 | SimpleGrammarParser.decl_return ret = parser.decl();
28 |
29 | //acquire parse result
30 | CommonTree ast = (CommonTree) ret.tree;
31 | printTree(ast);
32 | return ast;
33 |
34 | } catch (RecognitionException e) {
35 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
36 | }
37 |
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/SimpleGrammarWordTest.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.antlr.runtime.tree.CommonTree;
6 | import org.junit.Test;
7 |
8 | public class SimpleGrammarWordTest {
9 |
10 | @Test
11 | public void correctTest () {
12 | SimpleGrammarCompiler compiler = new SimpleGrammarCompiler();
13 | compiler.compile("int a, b;");
14 | }
15 |
16 | @Test
17 | public void incorrectTest () {
18 | SimpleGrammarCompiler compiler = new SimpleGrammarCompiler();
19 | compiler.compile("int a, b");
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/Vertex.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | /**
4 | * Date: 27.02.14
5 | * Time: 3:55
6 | *
7 | * @author SarokaA
8 | */
9 | public class Vertex implements Comparable {
10 | private String label;
11 |
12 | public Vertex(String label) {
13 | this.label = label.toUpperCase();
14 | }
15 |
16 | @Override
17 | public int compareTo(Vertex o) {
18 | return (this.getLabel().compareTo(o.getLabel()));
19 | }
20 |
21 | public String getLabel() {
22 | return label;
23 | }
24 |
25 | public void setLabel(String label) {
26 | this.label = label;
27 | }
28 |
29 | }
30 |
31 |
--------------------------------------------------------------------------------
/1 Compiler/version3Old/mmemory.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/1 Compiler/version3Old/mmemory.java
--------------------------------------------------------------------------------
/1 Compiler/version4/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.kadet.compiler
6 | kadetCompiler
7 | 1.0
8 | jar
9 |
10 | kadetCompiler
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 | org.antlr
20 | antlr
21 | 3.3
22 | jar
23 | compile
24 |
25 |
26 | junit
27 | junit
28 | 4.8.2
29 | jar
30 | test
31 |
32 |
33 |
34 |
35 |
36 |
37 | org.antlr
38 | antlr3-maven-plugin
39 | 3.3
40 |
41 |
42 | run antlr
43 | generate-sources
44 |
45 | antlr
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | org.codehaus.mojo
54 | build-helper-maven-plugin
55 |
56 |
57 | add-source
58 | generate-sources
59 |
60 | add-source
61 |
62 |
63 |
64 | ${basedir}/target/generated-sources/antlr3
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/antlr3/com/kadet/compiler/TODO.txt:
--------------------------------------------------------------------------------
1 | TODO:
2 | 1) check errors on add variable
3 | 2) check errors on add constants
4 | 3) check errors on not direct constant assignment
5 | 4) check errors on use not assignment value
6 |
7 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/AbstractCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import com.kadet.compiler.evaluators.ProgramEvaluator;
4 | import org.antlr.runtime.tree.CommonTree;
5 |
6 | /**
7 | * Date: 27.02.14
8 | * Time: 1:27
9 | *
10 | * @author SarokaA
11 | */
12 | public abstract class AbstractCompiler {
13 |
14 | public abstract ProgramEvaluator compile (String expression);
15 |
16 | public void compileCode (String code) {
17 |
18 | }
19 |
20 | protected void printTree (CommonTree ast) {
21 | print(ast, 0);
22 | }
23 |
24 | private void print (CommonTree tree, int level) {
25 | //indent level
26 | for (int i = 0; i < level; i++)
27 | System.out.print("--");
28 |
29 | //print node description: type code followed by token text
30 | System.out.println(" " + tree.getType() + " " + tree.getText());
31 |
32 | //print all children
33 | if (tree.getChildren() != null)
34 | for (Object ie : tree.getChildren()) {
35 | print((CommonTree) ie, level + 1);
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/KadetCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import com.kadet.compiler.evaluators.ProgramEvaluator;
4 | import org.antlr.runtime.ANTLRStringStream;
5 | import org.antlr.runtime.CommonTokenStream;
6 | import org.antlr.runtime.RecognitionException;
7 | import org.antlr.runtime.TokenStream;
8 | import org.antlr.runtime.tree.CommonTree;
9 |
10 | /**
11 | * Date: 16.03.14
12 | * Time: 16:37
13 | *
14 | * @author Кадет
15 | */
16 | public class KadetCompiler extends AbstractCompiler {
17 | @Override
18 | public ProgramEvaluator compile (String expression) {
19 | System.out.println("expression: " + expression);
20 |
21 | //lexer splits input into tokens
22 | ANTLRStringStream input = new ANTLRStringStream(expression);
23 | kadetLexer lexer = new kadetLexer(input);
24 | TokenStream tokens = new CommonTokenStream(lexer);
25 |
26 | //parser generates abstract syntax tree
27 | kadetParser parser = new kadetParser(tokens);
28 | kadetParser.program_return programReturn = null;
29 | try {
30 | programReturn = parser.program();
31 | } catch (RecognitionException e) {
32 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
33 | }
34 |
35 | //acquire parse result
36 | CommonTree ast = (CommonTree) programReturn.tree;
37 | printTree(ast);
38 |
39 | return programReturn.evaluator;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Bool.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | /**
4 | * Date: 31.03.14
5 | * Time: 0:28
6 | *
7 | * @author Кадет
8 | */
9 | public class Bool extends Element {
10 |
11 | public Bool (java.lang.Boolean bool) {
12 | super(bool);
13 | this.type = Type.BOOLEAN;
14 | }
15 |
16 | @Override
17 | public Value copy() {
18 | return new Bool((Boolean)getContent());
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Choice.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | import com.kadet.compiler.evaluators.StatementEvaluator;
4 | import com.kadet.compiler.expressions.Expression;
5 |
6 | import java.util.*;
7 | import java.util.List;
8 |
9 | /**
10 | * Date: 29.04.14
11 | * Time: 16:32
12 | *
13 | * @author SarokaA
14 | */
15 | public class Choice {
16 |
17 |
18 | private Expression expression;
19 | private java.util.List statementEvaluators = new ArrayList();
20 |
21 | public Choice() {
22 | }
23 |
24 | public Choice(Expression expression) {
25 | this.expression = expression;
26 | }
27 |
28 | public void addStatementEvaluator(StatementEvaluator statementEvaluator) {
29 | statementEvaluators.add(statementEvaluator);
30 | }
31 |
32 | public List getStatementEvaluators() {
33 | return statementEvaluators;
34 | }
35 |
36 | public Expression getExpression() {
37 | return expression;
38 | }
39 |
40 | @Override
41 | public String toString() {
42 | return "Choice{" +
43 | "expression=" + expression +
44 | ", statementEvaluators=" + statementEvaluators +
45 | '}';
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Constant.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | import com.kadet.compiler.expressions.Expression;
4 | import com.kadet.compiler.util.KadetException;
5 | import com.kadet.compiler.util.ValueFactory;
6 |
7 | /**
8 | * Date: 30.03.14
9 | * Time: 14:08
10 | *
11 | * @author Кадет
12 | */
13 | public class Constant extends Variable{
14 |
15 | private Expression expression;
16 |
17 | public Constant (String name) {
18 | super(name);
19 | setValue(ValueFactory.createValue(Type.VALUE));
20 | }
21 |
22 | public void setExpression(Expression expression) {
23 | this.expression = expression;
24 | }
25 |
26 | public void initialize() throws KadetException {
27 | setValue(expression.calculate());
28 | System.out.println("Constant is initialized!: " + toString());
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Element.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | /**
4 | * Date: 30.03.14
5 | * Time: 17:25
6 | *
7 | * @author Кадет
8 | */
9 | public class Element extends Value {
10 |
11 | private Object content;
12 |
13 | public Element (Object content) {
14 | this.type = Type.ELEMENT;
15 | this.content = content;
16 | }
17 |
18 | public Object getContent () {
19 | return content;
20 | }
21 |
22 | @Override
23 | public String toString () {
24 | return "Content: " + content;
25 | }
26 |
27 | @Override
28 | public Value copy () {
29 | return new Element(content);
30 | }
31 |
32 | @Override
33 | public boolean equals (Object obj) {
34 | if (obj == null) {
35 | return false;
36 | }
37 | if (this == obj || getClass() != obj.getClass()) {
38 | return false;
39 | }
40 | Element element = (Element) obj;
41 | if (content != element.getContent() || type != element.getType()) {
42 | return false;
43 | }
44 | return true;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Function.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | import com.kadet.compiler.evaluators.ReturnStatementEvaluator;
4 |
5 | import java.util.*;
6 | import java.util.List;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 12:37
11 | *
12 | * @author Кадет
13 | */
14 | public class Function extends Procedure {
15 |
16 | public Function (String name) {
17 | super(name);
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Int.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | /**
4 | * Date: 31.03.14
5 | * Time: 0:25
6 | *
7 | * @author Кадет
8 | */
9 | public class Int extends Element{
10 |
11 | public Int (java.lang.Integer integer) {
12 | super(integer);
13 | this.type = Type.INTEGER;
14 | }
15 |
16 |
17 | @Override
18 | public Value copy () {
19 | return new Int((Integer) getContent());
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/List.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | import java.util.ArrayList;
4 |
5 | /**
6 | * Date: 30.03.14
7 | * Time: 17:25
8 | *
9 | * @author Кадет
10 | */
11 | public class List extends Value {
12 |
13 | private java.util.List values = new ArrayList();
14 |
15 | public List () {
16 | this.type = Type.LIST;
17 | }
18 |
19 | public List (java.util.List values) {
20 | this();
21 | this.values = values;
22 | }
23 |
24 | public void addElement (Value value) {
25 | values.add(value);
26 | }
27 |
28 | public void removeElement (Value value) {
29 | values.remove(value);
30 | }
31 |
32 | public void removeAllElementEntries (Value value) {
33 | while (values.contains(value)) {
34 | values.remove(value);
35 | }
36 | }
37 |
38 | @Override
39 | public String toString () {
40 | return "List{" +
41 | "values=" + values +
42 | '}';
43 | }
44 |
45 | public java.util.List getValues () {
46 | return values;
47 | }
48 |
49 | @Override
50 | public Value copy () {
51 | java.util.List newValues = new ArrayList();
52 | for (Value value : values) {
53 | newValues.add(value.copy());
54 | }
55 | return new List(newValues);
56 | }
57 |
58 | public void addElementsFromOtherList (List list) {
59 | for (Value value : list.getValues()) {
60 | values.add(value);
61 | }
62 | }
63 |
64 | @Override
65 | public boolean equals (Object obj) {
66 | if (obj == null) {
67 | return false;
68 | }
69 | if (this == obj || getClass() != obj.getClass()) {
70 | return false;
71 | }
72 | List list = (List) obj;
73 | java.util.List objValues = list.getValues();
74 | if (values.size() != objValues.size()) {
75 | return false;
76 | }
77 | boolean equalValues = true;
78 | for (int valueIndex = values.size() - 1; valueIndex >= 0; --valueIndex) {
79 | if (!values.get(valueIndex).equals(objValues.get(valueIndex))) {
80 | equalValues = false;
81 | }
82 | }
83 | return equalValues;
84 | }
85 | }
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Procedure.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | import com.kadet.compiler.evaluators.StatementEvaluator;
4 |
5 | import java.util.*;
6 | import java.util.List;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 12:41
11 | *
12 | * @author Кадет
13 | */
14 | public class Procedure {
15 |
16 | private String name;
17 | private Procedure parentProcedure;
18 | private java.util.List parameters = new ArrayList();
19 | private java.util.List statementEvaluators = new ArrayList();
20 | private java.util.List variables = new ArrayList();
21 | private java.util.List constants = new ArrayList();
22 | private java.util.List procedures = new ArrayList();
23 | private java.util.List functions = new ArrayList();
24 |
25 |
26 | public Procedure () {
27 | }
28 |
29 | public Procedure(String name) {
30 | this.name = name;
31 | }
32 |
33 | public void setParentProcedure(Procedure parentProcedure) {
34 | this.parentProcedure = parentProcedure;
35 | }
36 |
37 | public void setParameters (List parameters) {
38 | this.parameters = parameters;
39 | for (ProcedureParameter parameter : parameters) {
40 | Variable variable = new Variable(parameter);
41 | variables.add(variable);
42 | }
43 | }
44 |
45 | public void addStatementEvaluator (StatementEvaluator statementEvaluator) {
46 | statementEvaluators.add(statementEvaluator);
47 | }
48 |
49 | public void addVariables (List variables) {
50 | for (Variable variable : variables) {
51 | addVariable(variable);
52 | }
53 | }
54 |
55 | public void addConstants (List constants) {
56 | for (Constant constant : constants) {
57 | addConstant(constant);
58 | }
59 | }
60 |
61 | public void addVariable (Variable variable) {
62 | variables.add(variable);
63 | System.out.println("To procedure " + name + " added Variable : " + variable);
64 | }
65 |
66 | public void addConstant (Constant constant) {
67 | constants.add(constant);
68 | System.out.println("To procedure " + name + " added Constant : " + constant);
69 | }
70 |
71 | public void addFunction (Function function) {
72 | functions.add(function);
73 | System.out.println("Added Function : " + function);
74 | }
75 |
76 | public void addProcedure (Procedure procedure) {
77 | procedures.add(procedure);
78 | System.out.println("Added Procedure :" + procedure);
79 | }
80 |
81 | public String getName () {
82 | return name;
83 | }
84 |
85 |
86 | public boolean hasSuchName (String name) {
87 | return this.name.equals(name);
88 | }
89 |
90 | @Override
91 | public String toString () {
92 | return "Procedure{" +
93 | "name='" + name + '\'' +
94 | ", parameters=" + parameters +
95 | ", statementEvaluators=" + statementEvaluators +
96 | '}';
97 | }
98 |
99 | public List getParameters() {
100 | return parameters;
101 | }
102 |
103 | public List getStatementEvaluators() {
104 | return statementEvaluators;
105 | }
106 |
107 | public List getVariables() {
108 | return variables;
109 | }
110 |
111 | public List getConstants() {
112 | return constants;
113 | }
114 |
115 | public List getProcedures() {
116 | return procedures;
117 | }
118 |
119 | public List getFunctions() {
120 | return functions;
121 | }
122 |
123 | public Procedure getParentProcedure() {
124 | return parentProcedure;
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/ProcedureParameter.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | /**
4 | * Date: 31.03.14
5 | * Time: 14:26
6 | *
7 | * @author Кадет
8 | */
9 | public class ProcedureParameter {
10 |
11 | private String name;
12 | private Type type;
13 |
14 | public ProcedureParameter (String name, Type type) {
15 | this.name = name;
16 | this.type = type;
17 | }
18 |
19 | public String getName () {
20 | return name;
21 | }
22 |
23 | public Type getType () {
24 | return type;
25 | }
26 |
27 | @Override
28 | public String toString () {
29 | return "ProcedureParameter{" +
30 | "name='" + name + '\'' +
31 | ", type=" + type +
32 | '}';
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Program.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | import com.kadet.compiler.util.Errors;
4 |
5 | import java.util.LinkedList;
6 | import java.util.List;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 12:37
11 | *
12 | * @author Кадет
13 | */
14 | public class Program {
15 |
16 | private static Program instance = new Program();
17 |
18 | public static Program getInstance () {
19 | return instance;
20 | }
21 |
22 | private String programName = "";
23 |
24 | private List procedures = new LinkedList();
25 | private List functions = new LinkedList();
26 | private List variables = new LinkedList();
27 | private List constants = new LinkedList();
28 | private Errors errors = new Errors();
29 | private Procedure currentProcedure = null;
30 |
31 | private Program () {}
32 |
33 | public void setProgramName(String programName) {
34 | this.programName = programName;
35 | }
36 |
37 | public void setCurrentProcedure(Procedure currentProcedure) {
38 | this.currentProcedure = currentProcedure;
39 | }
40 |
41 | public Procedure getCurrentProcedure () {
42 | return currentProcedure;
43 | }
44 |
45 | public String getProgramName() {
46 | return programName;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Type.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | /**
4 | * Date: 30.03.14
5 | * Time: 13:19
6 | *
7 | * @author Кадет
8 | */
9 | public enum Type {
10 |
11 |
12 | VALUE,
13 | ELEMENT,
14 | LIST,
15 | INTEGER,
16 | BOOLEAN
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Value.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | /**
4 | * Date: 30.03.14
5 | * Time: 17:25
6 | *
7 | * @author Кадет
8 | */
9 | public class Value {
10 |
11 | protected Type type = Type.VALUE;
12 |
13 | public Type getType () {
14 | return type;
15 | }
16 |
17 | public Value copy () {
18 | return new Value();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/entities/Variable.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.entities;
2 |
3 | import com.kadet.compiler.util.ValueFactory;
4 |
5 | /**
6 | * Date: 30.03.14
7 | * Time: 12:38
8 | *
9 | * @author Кадет
10 | */
11 | public class Variable {
12 |
13 | private String name;
14 | private Value value;
15 |
16 | public Variable (String name) {
17 | this.name = name;
18 | }
19 |
20 | public Variable(ProcedureParameter parameter) {
21 | this.name = parameter.getName();
22 | this.value = ValueFactory.createValue(parameter.getType());
23 | }
24 |
25 | public void setValue (Value value) {
26 | this.value = value;
27 | }
28 |
29 | @Override
30 | public String toString () {
31 | return "Variable{" +
32 | "name='" + name + '\'' +
33 | ", value=" + value +
34 | '}';
35 | }
36 |
37 | public Variable copy () {
38 | Variable variable = new Variable(name);
39 | variable.setValue(value);
40 | return variable;
41 | }
42 |
43 | public boolean hasSuchName (String name) {
44 | return this.name.equals(name);
45 | }
46 |
47 | public Value getValue() {
48 | return value;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/AssignmentEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.Procedure;
4 | import com.kadet.compiler.entities.Program;
5 | import com.kadet.compiler.entities.Value;
6 | import com.kadet.compiler.entities.Variable;
7 | import com.kadet.compiler.expressions.Expression;
8 | import com.kadet.compiler.util.Errors;
9 | import com.kadet.compiler.util.KadetError;
10 | import com.kadet.compiler.util.KadetException;
11 | import com.kadet.compiler.util.VariableUtils;
12 |
13 | import java.util.List;
14 |
15 | /**
16 | * Date: 30.03.14
17 | * Time: 14:01
18 | *
19 | * @author Кадет
20 | */
21 | public class AssignmentEvaluator implements StatementEvaluator {
22 |
23 | private String name;
24 | private Expression expression;
25 |
26 | public AssignmentEvaluator(String name, Expression expression) {
27 | this.name = name;
28 | this.expression = expression;
29 | }
30 |
31 | @Override
32 | public void evaluate() throws KadetException {
33 | System.out.println("Assignment Evaluator Starts!");
34 | Procedure currentProcedure = Program.getInstance().getCurrentProcedure();
35 | System.out.println("Assignment in procedure: " + currentProcedure);
36 | if (currentProcedure == null) {
37 | throw new KadetException("There is no current procedure!");
38 | }
39 | if (!VariableUtils.hasSuchVariableName(name, currentProcedure)) {
40 | throw new KadetException("No such variable!");
41 | }
42 | /*Variable currentVariable = null;
43 | for (Variable variable : VariableUtils.getVariablesFromProcedure(currentProcedure)) {
44 | if (variable.hasSuchName(name)) {
45 | currentVariable = variable;
46 | break;
47 | }
48 | } */
49 | Variable currentVariable = VariableUtils.getVariableFromProcedure(name, currentProcedure);
50 | Value value = expression.calculate();
51 | if (value == null) {
52 | throw new KadetException("Bad Value!");
53 | }
54 | currentVariable.setValue(value.copy());
55 | System.out.println("Value assign to variable. Variable : " + currentVariable);
56 | }
57 |
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/CallEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.*;
4 | import com.kadet.compiler.expressions.Expression;
5 | import com.kadet.compiler.util.*;
6 |
7 | import java.util.ArrayList;
8 | import java.util.List;
9 |
10 | /**
11 | * Date: 30.04.14
12 | * Time: 14:54
13 | *
14 | * @author SarokaA
15 | */
16 | public abstract class CallEvaluator implements StatementEvaluator {
17 |
18 | private String procedureName;
19 | private List actualParameters = new ArrayList();
20 |
21 | public CallEvaluator(String procedureName, List actualParameters) {
22 | this.procedureName = procedureName;
23 | this.actualParameters = actualParameters;
24 | }
25 |
26 | @Override
27 | public void evaluate() throws KadetException {
28 | System.out.println("Procedure Call Evaluator Starts!");
29 | Procedure currentProcedure = Program.getInstance().getCurrentProcedure();
30 | if (currentProcedure == null) {
31 | throw new KadetException("There is no current procedure!");
32 | }
33 | Procedure procedure = getProcedure(procedureName, currentProcedure);
34 | System.out.println("Called procedure: " + procedure.getName());
35 | List parameterValues
36 | = evaluateExpressions(actualParameters);
37 | addParametersValuesToProcedure(parameterValues, procedure);
38 | Evaluator procedureEvaluator
39 | = createCallEvaluator(procedure);
40 | procedureEvaluator.evaluate();
41 | }
42 |
43 | abstract protected Procedure getProcedure(String procedureName, Procedure parentProcedure) throws KadetException;
44 |
45 | abstract protected Evaluator createCallEvaluator(Procedure procedure);
46 |
47 | private List evaluateExpressions(List expressions) throws KadetException {
48 | List values = new ArrayList();
49 | for (Expression expression : expressions) {
50 | values.add(expression.calculate());
51 | }
52 | return values;
53 | }
54 |
55 | private void addParametersValuesToProcedure(List values, Procedure procedure) throws KadetException {
56 | List variableNames
57 | = getParametersNamesFromParameters(procedure.getParameters());
58 | List variables
59 | = getVariablesFromProcedureByNames(variableNames, procedure);
60 | for (int valueIndex = 0, valuesNumber = values.size(); valueIndex < valuesNumber; ++valueIndex) {
61 | if (valueIndex >= variables.size()) {
62 | break;
63 | }
64 | Variable currentVariable = variables.get(valueIndex);
65 | Value value = values.get(valueIndex);
66 | if (!currentVariable.getValue().getType().equals(value.getType())) {
67 | throw new KadetException("Wrong type of parameter!");
68 | }
69 | currentVariable.setValue(
70 | values.get(valueIndex));
71 | }
72 | }
73 |
74 | private List getParametersNamesFromParameters(List parameters) {
75 | List names = new ArrayList();
76 | for (ProcedureParameter parameter : parameters) {
77 | names.add(parameter.getName());
78 | }
79 | return names;
80 | }
81 |
82 | private List getVariablesFromProcedureByNames(List names, Procedure procedure) throws KadetException {
83 | List variables = new ArrayList();
84 | for (String name : names) {
85 | variables.add(VariableUtils.getVariableFromProcedure(name, procedure));
86 | }
87 | return variables;
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/ChoiceEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.Choice;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | import java.util.List;
9 |
10 | /**
11 | * Date: 29.04.14
12 | * Time: 21:58
13 | *
14 | * @author SarokaA
15 | */
16 | public abstract class ChoiceEvaluator implements StatementEvaluator {
17 |
18 |
19 | protected boolean checkChoiceExpression(Choice choice) throws KadetException {
20 | Value expressionResult = choice.getExpression().calculate();
21 | if (!ValueUtils.isBoolean(expressionResult)) {
22 | throw new KadetException("Not Boolean expression!");
23 | }
24 | return ValueUtils.getBooleanFromValue(expressionResult);
25 | }
26 |
27 | protected void evaluateChoice(Choice choice) throws KadetException {
28 | List statementEvaluators = choice.getStatementEvaluators();
29 | for (StatementEvaluator evaluator : statementEvaluators) {
30 | evaluator.evaluate();
31 | }
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/Evaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.util.KadetException;
4 |
5 | /**
6 | * Date: 30.03.14
7 | * Time: 12:53
8 | *
9 | * @author Кадет
10 | */
11 | public interface Evaluator {
12 |
13 | void evaluate () throws KadetException;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/ForEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.Choice;
4 | import com.kadet.compiler.util.KadetException;
5 |
6 | /**
7 | * Date: 30.03.14
8 | * Time: 14:01
9 | *
10 | * @author Кадет
11 | */
12 | public class ForEvaluator extends ChoiceEvaluator {
13 |
14 | private AssignmentEvaluator initializeCounterEvaluator;
15 | private Choice forChoice;
16 | private AssignmentEvaluator increaseCounterEvaluator;
17 |
18 | public void setInitializeCounterEvaluator(AssignmentEvaluator initializeCounterEvaluator) {
19 | this.initializeCounterEvaluator = initializeCounterEvaluator;
20 | }
21 |
22 | public void setForChoice(Choice forChoice) {
23 | this.forChoice = forChoice;
24 | }
25 |
26 | public void setIncreaseCounterEvaluator(AssignmentEvaluator increaseCounterEvaluator) {
27 | this.increaseCounterEvaluator = increaseCounterEvaluator;
28 | }
29 |
30 | @Override
31 | public void evaluate() throws KadetException {
32 | System.out.println("For Evaluator Starts! (" + this + ")");
33 | if (forChoice == null) {
34 | throw new KadetException("No For expression!");
35 | }
36 | if (initializeCounterEvaluator != null) {
37 | initializeCounterEvaluator.evaluate();
38 | }
39 | while (checkChoiceExpression(forChoice)) {
40 | System.out.println("For is true!");
41 | evaluateChoice(forChoice);
42 | increaseCounterEvaluator.evaluate();
43 | }
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/FunctionEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.*;
4 | import com.kadet.compiler.util.KadetException;
5 | import com.kadet.compiler.util.ValueFactory;
6 |
7 | import java.util.List;
8 |
9 | /**
10 | * Date: 30.03.14
11 | * Time: 13:18
12 | *
13 | * @author Кадет
14 | */
15 | public class FunctionEvaluator extends ProcedureEvaluator{
16 |
17 | private Value returnValue = ValueFactory.createValue(Type.VALUE);
18 |
19 | public FunctionEvaluator (Function function) {
20 | super(function);
21 | }
22 |
23 | @Override
24 | protected void evaluateProcedureStatements(Procedure procedure) throws KadetException {
25 | for (StatementEvaluator evaluator : procedure.getStatementEvaluators()) {
26 | if (evaluator instanceof ReturnStatementEvaluator) {
27 | ReturnStatementEvaluator returnEvaluator
28 | = (ReturnStatementEvaluator) evaluator;
29 | returnEvaluator.evaluate();
30 | this.returnValue = returnEvaluator.getReturnValue();
31 | return;
32 | }
33 | evaluator.evaluate();
34 | }
35 | throw new KadetException("There is no return statement!");
36 | }
37 |
38 | public Value getReturnValue() {
39 | return returnValue;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/IfEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.Choice;
4 | import com.kadet.compiler.util.KadetException;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | /**
10 | * Date: 30.03.14
11 | * Time: 14:01
12 | *
13 | * @author Кадет
14 | */
15 | public class IfEvaluator extends ChoiceEvaluator {
16 |
17 | private Choice ifChoice = null;
18 |
19 | private List elsIfChoices = new ArrayList();
20 |
21 | private Choice elseChoice = null;
22 |
23 | public IfEvaluator() {
24 | }
25 |
26 | public void setIfChoice(Choice ifChoice) {
27 | this.ifChoice = ifChoice;
28 | }
29 |
30 | public void setElseChoice(Choice elseChoice) {
31 | this.elseChoice = elseChoice;
32 | }
33 |
34 | public void setElsIfChoices(List elsIfChoices) {
35 | this.elsIfChoices = elsIfChoices;
36 | }
37 |
38 | @Override
39 | public void evaluate() throws KadetException {
40 | System.out.println("If Evaluator Starts! (" + this + ")");
41 | if (ifChoice == null) {
42 | throw new KadetException("No If expression!");
43 | }
44 | if (checkChoiceExpression(ifChoice)) {
45 | evaluateChoice(ifChoice);
46 | System.out.println("If is true!");
47 | } else {
48 | System.out.println("If is false!");
49 | boolean hasTrueExpression = false;
50 | for (Choice elsIfChoice : elsIfChoices) {
51 | if (checkChoiceExpression(elsIfChoice)) {
52 | evaluateChoice(elsIfChoice);
53 | hasTrueExpression = true;
54 | System.out.println("ElsIf is true!");
55 | }
56 | }
57 | if (!hasTrueExpression) {
58 | if (elseChoice != null) {
59 | System.out.println("Else is evaluating");
60 | evaluateChoice(elseChoice);
61 | }
62 | }
63 | }
64 |
65 | }
66 |
67 |
68 | @Override
69 | public String toString() {
70 | return "IfEvaluator{" +
71 | "ifChoice=" + ifChoice +
72 | ", elsIfChoices=" + elsIfChoices +
73 | ", elseChoice=" + elseChoice +
74 | '}';
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/KadOutEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.expressions.Expression;
4 | import com.kadet.compiler.util.KadetException;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | /**
10 | * Date: 30.04.14
11 | * Time: 17:39
12 | *
13 | * @author SarokaA
14 | */
15 | public class KadOutEvaluator implements StatementEvaluator {
16 |
17 | private List expressions = new ArrayList();
18 |
19 | public void addExpression (Expression expression) {
20 | expressions.add(expression);
21 | }
22 |
23 | @Override
24 | public void evaluate() throws KadetException {
25 | for (Expression expression : expressions) {
26 | System.out.println("<=<" + expression.calculate());
27 | }
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/ProcedureCallEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.*;
4 | import com.kadet.compiler.expressions.Expression;
5 | import com.kadet.compiler.util.*;
6 |
7 | import java.util.ArrayList;
8 | import java.util.List;
9 |
10 | /**
11 | * Date: 30.03.14
12 | * Time: 14:01
13 | *
14 | * @author Кадет
15 | */
16 | public class ProcedureCallEvaluator extends CallEvaluator {
17 |
18 | public ProcedureCallEvaluator(String procedureName, List actualParameters) {
19 | super(procedureName, actualParameters);
20 | }
21 |
22 | @Override
23 | protected Procedure getProcedure(String procedureName, Procedure parentProcedure) throws KadetException {
24 | if (!ProcedureUtils.hasSuchProcedureName(procedureName, parentProcedure)) {
25 | throw new KadetException("No such procedure!");
26 | }
27 | return ProcedureUtils.getProcedureFromProcedure(procedureName, parentProcedure);
28 | }
29 |
30 | @Override
31 | protected Evaluator createCallEvaluator(Procedure procedure) {
32 | return new ProcedureEvaluator(procedure);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/ProcedureEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.Procedure;
4 | import com.kadet.compiler.entities.Program;
5 | import com.kadet.compiler.initializers.Initializer;
6 | import com.kadet.compiler.initializers.ProcedureInitializer;
7 | import com.kadet.compiler.util.KadetException;
8 |
9 | /**
10 | * Date: 30.03.14
11 | * Time: 13:20
12 | *
13 | * @author Кадет
14 | */
15 | public class ProcedureEvaluator implements Evaluator {
16 |
17 | private Initializer initializer = new ProcedureInitializer();
18 |
19 | protected Procedure procedure = null;
20 |
21 | /*private String name;
22 | private Program program = Program.getInstance();
23 | private List parameters = new ArrayList();
24 | private List statementEvaluators = new ArrayList();
25 | */
26 |
27 | public ProcedureEvaluator() {
28 | }
29 |
30 | public ProcedureEvaluator(Procedure procedure) {
31 | this.procedure = procedure;
32 | }
33 |
34 |
35 | public void setProcedure(Procedure procedure) {
36 | this.procedure = procedure;
37 | }
38 |
39 |
40 | @Override
41 | public void evaluate() throws KadetException {
42 | if (procedure == null) {
43 | throw new KadetException("No procedure to evaluate!");
44 | }
45 | initializer.initialize(procedure);
46 | Program.getInstance().setCurrentProcedure(procedure);
47 | evaluateProcedureStatements(procedure);
48 | if (procedure.getParentProcedure() != null) {
49 | Program.getInstance().setCurrentProcedure(procedure.getParentProcedure());
50 | }
51 | }
52 |
53 | protected void evaluateProcedureStatements(Procedure procedure) throws KadetException {
54 | for (StatementEvaluator statementEvaluator : procedure.getStatementEvaluators()) {
55 | statementEvaluator.evaluate();
56 | }
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/ProgramEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.Program;
4 | import com.kadet.compiler.util.Errors;
5 | import com.kadet.compiler.util.KadetError;
6 | import com.kadet.compiler.util.KadetException;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 12:53
11 | *
12 | * @author Кадет
13 | */
14 | public class ProgramEvaluator implements Evaluator {
15 |
16 | private ProcedureEvaluator mainEvaluator;
17 |
18 | public ProgramEvaluator() {
19 | }
20 |
21 | public void setMainEvaluator(ProcedureEvaluator mainEvaluator) {
22 | this.mainEvaluator = mainEvaluator;
23 | }
24 |
25 | @Override
26 | public void evaluate() throws KadetException {
27 | System.out.println("Program " + Program.getInstance().getProgramName() + " Starts!");
28 | if (mainEvaluator == null) {
29 | Errors.addError(
30 | new KadetError("No Main Method!"));
31 | return;
32 | }
33 | mainEvaluator.evaluate();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/ReturnStatementEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.Type;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.expressions.Expression;
6 | import com.kadet.compiler.util.KadetException;
7 | import com.kadet.compiler.util.ValueFactory;
8 |
9 | /**
10 | * Date: 31.03.14
11 | * Time: 23:48
12 | *
13 | * @author Кадет
14 | */
15 | public class ReturnStatementEvaluator implements StatementEvaluator {
16 |
17 | private Expression expression;
18 | private Value returnValue = ValueFactory.createValue(Type.VALUE);
19 |
20 | public ReturnStatementEvaluator(Expression expression) {
21 | this.expression = expression;
22 | }
23 |
24 | @Override
25 | public void evaluate() throws KadetException {
26 | this.returnValue = expression.calculate();
27 | }
28 |
29 | public Value getReturnValue() {
30 | return returnValue;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/StatementEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 30.03.14
5 | * Time: 13:54
6 | *
7 | * @author Кадет
8 | */
9 | public interface StatementEvaluator extends Evaluator{
10 |
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/evaluators/WhileEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | import com.kadet.compiler.entities.Choice;
4 | import com.kadet.compiler.util.KadetException;
5 |
6 | /**
7 | * Date: 30.03.14
8 | * Time: 14:01
9 | *
10 | * @author Кадет
11 | */
12 | public class WhileEvaluator extends ChoiceEvaluator {
13 |
14 | private Choice whileChoice;
15 |
16 | public void setWhileChoice(Choice whileChoice) {
17 | this.whileChoice = whileChoice;
18 | }
19 |
20 | @Override
21 | public void evaluate() throws KadetException {
22 | System.out.println("While Evaluator Starts! ");
23 | if (whileChoice == null) {
24 | throw new KadetException("No While expression!");
25 | }
26 | while (checkChoiceExpression(whileChoice)) {
27 | System.out.println("While is true!");
28 | evaluateChoice(whileChoice);
29 | }
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/AddToListExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Element;
4 | import com.kadet.compiler.entities.List;
5 | import com.kadet.compiler.entities.Value;
6 | import com.kadet.compiler.util.KadetException;
7 | import com.kadet.compiler.util.ValueUtils;
8 |
9 | import java.util.ArrayList;
10 |
11 | /**
12 | * Date: 30.03.14
13 | * Time: 19:09
14 | *
15 | * @author Кадет
16 | */
17 | public class AddToListExpression extends BinaryExpression {
18 |
19 | public AddToListExpression (Expression expression1, Expression expression2) {
20 | super(expression1, expression2);
21 | }
22 |
23 | @Override
24 | public Value calculate () throws KadetException {
25 | Value value1 = expression1.calculate();
26 | Value value2 = expression2.calculate();
27 | if (ValueUtils.isElementAndElement(value1, value2)) {
28 | return createListFromElements((Element) value1, (Element) value2);
29 | }
30 | if (ValueUtils.isElementAndList(value1, value2)) {
31 | return createNewListWithListElementAndElement((List) value2, (Element) value1);
32 | }
33 | if (ValueUtils.isListAndElement(value1, value2)) {
34 | return createNewListWithListElementAndElement((List) value1, (Element) value2);
35 | }
36 | if (ValueUtils.isListAndList(value1, value2)) {
37 | return uniteLists((List) value1, (List) value2);
38 | }
39 | throw new KadetException("+ Operation Error!");
40 | }
41 |
42 | private List createListFromElements (Element element1, Element element2) {
43 | java.util.List values = new ArrayList();
44 | values.add(element1);
45 | values.add(element2);
46 | return new List(values);
47 | }
48 |
49 | private List createNewListWithListElementAndElement (List list, Element element) {
50 | List newList = (List)list.copy();
51 | newList.addElement(element);
52 | return newList;
53 | }
54 |
55 | private List uniteLists (List list1, List list2) {
56 | List newList = (List)list1.copy();
57 | newList.addElementsFromOtherList(list2);
58 | return newList;
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/AndExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.*;
4 | import com.kadet.compiler.entities.Bool;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 17:33
11 | *
12 | * @author Кадет
13 | */
14 | public class AndExpression extends BinaryExpression {
15 |
16 | public AndExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | Value value1 = expression1.calculate();
23 | Value value2 = expression2.calculate();
24 | if (ValueUtils.isBoolean(value1) && ValueUtils.isBoolean(value2)) {
25 | if (andBetweenBooleanValues(value1, value2)) {
26 | return new Bool(true);
27 | }
28 | }
29 | throw new KadetException("AND Operation Error!");
30 | }
31 |
32 |
33 | private boolean andBetweenBooleanValues (Value value1, Value value2) {
34 | return ValueUtils.getBooleanFromValue(value1) && ValueUtils.getBooleanFromValue(value2);
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/BinaryExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | /**
4 | * Date: 30.03.14
5 | * Time: 17:43
6 | *
7 | * @author Кадет
8 | */
9 | public abstract class BinaryExpression implements Expression {
10 |
11 | protected Expression expression1;
12 | protected Expression expression2;
13 |
14 | public BinaryExpression (Expression expression1, Expression expression2) {
15 | this.expression1 = expression1;
16 | this.expression2 = expression2;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/ConstantOrVariableValueExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.*;
4 | import com.kadet.compiler.util.KadetException;
5 | import com.kadet.compiler.util.ValueUtils;
6 | import com.kadet.compiler.util.VariableUtils;
7 | import sun.dc.pr.PRError;
8 |
9 | /**
10 | * Date: 29.04.14
11 | * Time: 21:11
12 | *
13 | * @author SarokaA
14 | */
15 | public class ConstantOrVariableValueExpression implements Expression{
16 |
17 | private String name;
18 |
19 | public ConstantOrVariableValueExpression(String name) {
20 | this.name = name;
21 | }
22 |
23 | @Override
24 | public Value calculate() throws KadetException {
25 | Procedure procedure = Program.getInstance().getCurrentProcedure();
26 | if (procedure == null) {
27 | throw new KadetException("There are no executing procedure!");
28 | }
29 | Variable variable = VariableUtils.getConstantOrVariableFromProcedure(name, procedure);
30 | Value value = variable.getValue();
31 | if (ValueUtils.isList(value)) {
32 | value = ((List)value).copy();
33 | }
34 | return variable.getValue();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/DivideExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Int;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 19:08
11 | *
12 | * @author Кадет
13 | */
14 | public class DivideExpression extends BinaryExpression {
15 |
16 | public DivideExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | Value value1 = expression1.calculate();
23 | Value value2 = expression2.calculate();
24 | if (ValueUtils.isInteger(value1) && ValueUtils.isInteger(value2)) {
25 | return integerDivideInteger(value1, value2);
26 | }
27 | throw new KadetException("DIVIDE Operation Error!");
28 | }
29 |
30 | private Value integerDivideInteger (Value value1, Value value2) {
31 | Integer integer1 = ValueUtils.getIntegerFromValue(value1);
32 | Integer integer2 = ValueUtils.getIntegerFromValue(value2);
33 | return new Int(integer1 / integer2);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/ElementFromListExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Value;
4 | import com.kadet.compiler.util.KadetException;
5 | import com.kadet.compiler.util.ValueUtils;
6 |
7 | /**
8 | * Date: 31.03.14
9 | * Time: 11:53
10 | *
11 | * @author Кадет
12 | */
13 | public class ElementFromListExpression extends ConstantOrVariableValueExpression {
14 |
15 | private Expression expression;
16 |
17 | public ElementFromListExpression(String varName, Expression expression) {
18 | super(varName);
19 | this.expression = expression;
20 | }
21 |
22 | @Override
23 | public Value calculate () throws KadetException {
24 | Value value = expression.calculate();
25 | if (value == null || !ValueUtils.isInteger(value)) {
26 | throw new KadetException("Non Integer Index");
27 | }
28 | int elementIndex = ValueUtils.getIntegerFromValue(value);
29 | Value list = super.calculate();
30 | java.util.List values = ValueUtils.getListFromValue(list);
31 | if (elementIndex < 0 || elementIndex >= values.size()) {
32 | throw new KadetException("Argument out of list range!");
33 | }
34 | return values.get(elementIndex);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/EqualExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Bool;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 |
7 | /**
8 | * Date: 30.03.14
9 | * Time: 18:35
10 | *
11 | * @author Кадет
12 | */
13 | public class EqualExpression extends BinaryExpression {
14 |
15 | public EqualExpression (Expression expression1, Expression expression2) {
16 | super(expression1, expression2);
17 | }
18 |
19 | @Override
20 | public Value calculate () throws KadetException {
21 | Value value1 = expression1.calculate();
22 | Value value2 = expression2.calculate();
23 | return (value1.equals(value2)) ? new Bool(true) : new Bool(false);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/Expression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Value;
4 | import com.kadet.compiler.util.KadetException;
5 |
6 | /**
7 | * Date: 30.03.14
8 | * Time: 17:48
9 | *
10 | * @author Кадет
11 | */
12 | public interface Expression {
13 |
14 | Value calculate () throws KadetException;
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/FunctionCallExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Function;
4 | import com.kadet.compiler.entities.Procedure;
5 | import com.kadet.compiler.entities.Value;
6 | import com.kadet.compiler.evaluators.CallEvaluator;
7 | import com.kadet.compiler.evaluators.Evaluator;
8 | import com.kadet.compiler.evaluators.FunctionEvaluator;
9 | import com.kadet.compiler.util.KadetException;
10 | import com.kadet.compiler.util.ProcedureUtils;
11 |
12 | import java.util.List;
13 |
14 | /**
15 | * Date: 30.04.14
16 | * Time: 14:29
17 | *
18 | * @author SarokaA
19 | */
20 | public class FunctionCallExpression extends CallEvaluator implements Expression {
21 |
22 | private FunctionEvaluator functionEvaluator;
23 |
24 | public FunctionCallExpression(String procedureName, List actualParameters) {
25 | super(procedureName, actualParameters);
26 | }
27 |
28 | @Override
29 | protected Procedure getProcedure(String procedureName, Procedure parentProcedure) throws KadetException {
30 | if (!ProcedureUtils.hasSuchFunctionName(procedureName, parentProcedure)) {
31 | System.out.println("procedureName" + procedureName + "parentProcedure Functions : " + parentProcedure.getFunctions());
32 | throw new KadetException("No such function!");
33 | }
34 | return ProcedureUtils.getFunctionFromProcedure(procedureName, parentProcedure);
35 | }
36 |
37 | @Override
38 | public Value calculate() throws KadetException {
39 | evaluate();
40 | return functionEvaluator.getReturnValue();
41 | }
42 |
43 | @Override
44 | protected Evaluator createCallEvaluator(Procedure procedure) {
45 | functionEvaluator = new FunctionEvaluator((Function) procedure);
46 | return functionEvaluator;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/GreaterExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Bool;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 18:39
11 | *
12 | * @author Кадет
13 | */
14 | public class GreaterExpression extends BinaryExpression {
15 |
16 | public GreaterExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | Value value1 = expression1.calculate();
23 | Value value2 = expression2.calculate();
24 | if (!ValueUtils.isInteger(value1) || !ValueUtils.isInteger(value2)) {
25 | throw new KadetException("Not Integer Values in Greater Expression!");
26 | }
27 | return (ValueUtils.getIntegerFromValue(value1) > ValueUtils.getIntegerFromValue(value2)) ? new Bool(true) : new Bool(false);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/GreaterOrEqualExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Bool;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 18:39
11 | *
12 | * @author Кадет
13 | */
14 | public class GreaterOrEqualExpression extends BinaryExpression {
15 |
16 | public GreaterOrEqualExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | Value value1 = expression1.calculate();
23 | Value value2 = expression2.calculate();
24 | if (!ValueUtils.isInteger(value1) || !ValueUtils.isInteger(value2)) {
25 | throw new KadetException("Not Integer Values in Greater Or Equal Expression!");
26 | }
27 | return (ValueUtils.getIntegerFromValue(value1) >= ValueUtils.getIntegerFromValue(value2)) ? new Bool(true) : new Bool(false);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/KadInExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Bool;
4 | import com.kadet.compiler.entities.Int;
5 | import com.kadet.compiler.entities.List;
6 | import com.kadet.compiler.entities.Value;
7 | import com.kadet.compiler.util.KadetException;
8 |
9 | import javax.print.DocFlavor;
10 | import java.io.BufferedReader;
11 | import java.io.IOException;
12 | import java.io.InputStream;
13 | import java.io.InputStreamReader;
14 | import java.util.ArrayList;
15 | import java.util.Scanner;
16 |
17 | /**
18 | * Date: 30.04.14
19 | * Time: 18:36
20 | *
21 | * @author SarokaA
22 | */
23 | public class KadInExpression implements Expression {
24 |
25 | private final static String TRUE = "true";
26 | private final static String FALSE = "false";
27 |
28 | private InputStream inputStream;
29 |
30 | public KadInExpression(InputStream inputStream) {
31 | this.inputStream = inputStream;
32 | }
33 |
34 | @Override
35 | public Value calculate() throws KadetException {
36 | Scanner scanner = new Scanner(inputStream);
37 | String text = scanner.nextLine();
38 | System.out.println(text);
39 | return getValueFromText(text);
40 | }
41 |
42 | private Value getValueFromText (String text) throws KadetException{
43 | text = text.trim();
44 | if (text.length() == 0) {
45 | throw new KadetException("Bad Input Text!");
46 | }
47 | if (TRUE.equalsIgnoreCase(text) || ('@' + TRUE).equalsIgnoreCase(text) ) {
48 | return new Bool(true);
49 | }
50 | if (FALSE.equalsIgnoreCase(text) || ('@' + FALSE).equalsIgnoreCase(text)) {
51 | return new Bool(false);
52 | }
53 | try {
54 | int value = Integer.parseInt(text);
55 | return new Int(value);
56 | } catch (NumberFormatException nfe) {
57 | if(('<' != text.charAt(0) || '>' != text.charAt(text.length() - 1))) {
58 | throw new KadetException("Bad Input Text!");
59 | }
60 | text = text.substring(1, text.length() - 1);
61 | System.out.println(text);
62 | String []textElements = text.split(",");
63 | List list = new List();
64 | for (String textElement : textElements) {
65 | list.addElement(getValueFromText(textElement));
66 | }
67 | return list;
68 | }
69 | }
70 |
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/LessExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Bool;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.kadetLexer;
6 | import com.kadet.compiler.util.KadetException;
7 | import com.kadet.compiler.util.ValueUtils;
8 |
9 | /**
10 | * Date: 30.03.14
11 | * Time: 18:38
12 | *
13 | * @author Кадет
14 | */
15 | public class LessExpression extends BinaryExpression {
16 |
17 | public LessExpression (Expression expression1, Expression expression2) {
18 | super(expression1, expression2);
19 | }
20 |
21 | @Override
22 | public Value calculate () throws KadetException {
23 | Value value1 = expression1.calculate();
24 | Value value2 = expression2.calculate();
25 | if (!ValueUtils.isInteger(value1) || !ValueUtils.isInteger(value2)) {
26 | throw new KadetException("Not Integer Values in Less Expression!");
27 | }
28 | return (ValueUtils.getIntegerFromValue(value1) < ValueUtils.getIntegerFromValue(value2)) ? new Bool(true) : new Bool(false);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/LessOrEqualExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Bool;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 18:38
11 | *
12 | * @author Кадет
13 | */
14 | public class LessOrEqualExpression extends BinaryExpression {
15 |
16 | public LessOrEqualExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | Value value1 = expression1.calculate();
23 | Value value2 = expression2.calculate();
24 | if (!ValueUtils.isInteger(value1) || !ValueUtils.isInteger(value2)) {
25 | throw new KadetException("Not Integer Values in Less Or Equal Expression!");
26 | }
27 | return (ValueUtils.getIntegerFromValue(value1) <= ValueUtils.getIntegerFromValue(value2)) ? new Bool(true) : new Bool(false);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/ListExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.List;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 |
7 | import java.util.ArrayList;
8 |
9 | /**
10 | * Date: 31.03.14
11 | * Time: 11:23
12 | *
13 | * @author Кадет
14 | */
15 | public class ListExpression implements Expression {
16 |
17 | private java.util.List expressions = new ArrayList();
18 |
19 | public ListExpression (java.util.List expressions) {
20 | this.expressions = expressions;
21 | }
22 |
23 | @Override
24 | public Value calculate () throws KadetException {
25 | java.util.List values = new ArrayList();
26 | for (Expression expression : expressions) {
27 | values.add(expression.calculate());
28 | }
29 | System.out.println("\nList Calculation :" + values);
30 | return new List(values);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/MinusExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Int;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 19:08
11 | *
12 | * @author Кадет
13 | */
14 | public class MinusExpression extends BinaryExpression {
15 |
16 | public MinusExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | Value value1 = expression1.calculate();
23 | Value value2 = expression2.calculate();
24 | if (ValueUtils.isInteger(value1) && ValueUtils.isInteger(value2)) {
25 | return integerMinusInteger(value1, value2);
26 | }
27 | throw new KadetException("MINUS Operation Error!");
28 | }
29 |
30 | private Value integerMinusInteger (Value value1, Value value2) {
31 | Integer integer1 = ValueUtils.getIntegerFromValue(value1);
32 | Integer integer2 = ValueUtils.getIntegerFromValue(value2);
33 | return new Int(integer1 - integer2);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/MultipleExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Int;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 19:08
11 | *
12 | * @author Кадет
13 | */
14 | public class MultipleExpression extends BinaryExpression {
15 |
16 | public MultipleExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | Value value1 = expression1.calculate();
23 | Value value2 = expression2.calculate();
24 | if (ValueUtils.isInteger(value1) && ValueUtils.isInteger(value2)) {
25 | return integerMultiplyInteger(value1, value2);
26 | }
27 | throw new KadetException("MULTIPLE Operation Error!");
28 | }
29 |
30 | private Value integerMultiplyInteger (Value value1, Value value2) {
31 | Integer integer1 = ValueUtils.getIntegerFromValue(value1);
32 | Integer integer2 = ValueUtils.getIntegerFromValue(value2);
33 | return new Int(integer1 * integer2);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/NotEqualExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Bool;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 18:38
11 | *
12 | * @author Кадет
13 | */
14 | public class NotEqualExpression extends BinaryExpression {
15 |
16 | public NotEqualExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | Value value1 = expression1.calculate();
23 | Value value2 = expression2.calculate();
24 | return (!value1.equals(value2)) ? new Bool(true) : new Bool(false);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/OrExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Bool;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 17:33
11 | *
12 | * @author Кадет
13 | */
14 | public class OrExpression extends BinaryExpression {
15 |
16 | public OrExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 | @Override
20 | public Value calculate () throws KadetException {
21 | Value value1 = expression1.calculate();
22 | Value value2 = expression2.calculate();
23 | if (ValueUtils.isBoolean(value1) && ValueUtils.isBoolean(value2)) {
24 | if (orBetweenBooleanValues(value1, value2)) {
25 | return new Bool(true);
26 | }
27 | }
28 | throw new KadetException("Or Operation Error!");
29 | }
30 |
31 |
32 | private boolean orBetweenBooleanValues(Value value1, Value value2) {
33 | return ValueUtils.getBooleanFromValue(value1) || ValueUtils.getBooleanFromValue(value2);
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/OverListExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.List;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 |
7 | import java.util.ArrayList;
8 |
9 | /**
10 | * Date: 30.03.14
11 | * Time: 19:10
12 | *
13 | * @author Кадет
14 | */
15 | public class OverListExpression extends BinaryExpression {
16 |
17 | public OverListExpression (Expression expression1, Expression expression2) {
18 | super(expression1, expression2);
19 | }
20 |
21 | @Override
22 | public Value calculate () throws KadetException {
23 | Value value1 = expression1.calculate();
24 | Value value2 = expression2.calculate();
25 | return createOverList(value1, value2);
26 | }
27 |
28 | private List createOverList (Value value1, Value value2) {
29 | java.util.List values = new ArrayList();
30 | values.add(value1);
31 | values.add(value2);
32 | return new List(values);
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/PlusExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Int;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 | import com.kadet.compiler.util.ValueUtils;
7 |
8 | /**
9 | * Date: 30.03.14
10 | * Time: 19:07
11 | *
12 | * @author Кадет
13 | */
14 | public class PlusExpression extends BinaryExpression {
15 |
16 | public PlusExpression (Expression expression1, Expression expression2) {
17 | super(expression1, expression2);
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | Value value1 = expression1.calculate();
23 | Value value2 = expression2.calculate();
24 | if (ValueUtils.isInteger(value1) && ValueUtils.isInteger(value2)) {
25 | return integerPlusInteger(value1, value2);
26 | }
27 | throw new KadetException("PLUS Operation Error!");
28 | }
29 |
30 | private Value integerPlusInteger (Value value1, Value value2) {
31 | Integer integer1 = ValueUtils.getIntegerFromValue(value1);
32 | Integer integer2 = ValueUtils.getIntegerFromValue(value2);
33 | return new Int(integer1 + integer2);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/RemoveAllElementEntriesExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.List;
4 | import com.kadet.compiler.entities.Value;
5 | import com.kadet.compiler.util.KadetException;
6 |
7 | /**
8 | * Date: 30.03.14
9 | * Time: 19:10
10 | *
11 | * @author Кадет
12 | */
13 | public class RemoveAllElementEntriesExpression extends RemoveFromListExpression {
14 |
15 | public RemoveAllElementEntriesExpression (Expression expression1, Expression expression2) {
16 | super(expression1, expression2);
17 | }
18 |
19 | @Override
20 | protected List createNewListFromListWithoutElement (List list, Value value) {
21 | List newList = (List)list.copy();
22 | newList.removeAllElementEntries(value);
23 | return newList;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/RemoveFromListExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Element;
4 | import com.kadet.compiler.entities.List;
5 | import com.kadet.compiler.entities.Value;
6 | import com.kadet.compiler.util.KadetException;
7 | import com.kadet.compiler.util.ValueUtils;
8 |
9 | /**
10 | * Date: 30.03.14
11 | * Time: 19:09
12 | *
13 | * @author Кадет
14 | */
15 | public class RemoveFromListExpression extends BinaryExpression {
16 |
17 | public RemoveFromListExpression (Expression expression1, Expression expression2) {
18 | super(expression1, expression2);
19 | }
20 |
21 | @Override
22 | public Value calculate () throws KadetException {
23 | Value value1 = expression1.calculate();
24 | Value value2 = expression2.calculate();
25 | if (ValueUtils.isListAndElement(value1, value2)
26 | || ValueUtils.isListAndList(value1, value2)) {
27 | return createNewListFromListWithoutElement((List) value1, value2);
28 | }
29 | throw new KadetException("- Operation Error!");
30 | }
31 |
32 | protected List createNewListFromListWithoutElement (List list, Value value) {
33 | List newList = (List)list.copy();
34 | newList.removeElement(value);
35 | return newList;
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/UnaryOperation.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.evaluators.Evaluator;
4 |
5 | /**
6 | * Date: 30.03.14
7 | * Time: 17:44
8 | *
9 | * @author Кадет
10 | */
11 | public abstract class UnaryOperation implements Evaluator {
12 |
13 | protected Expression expression;
14 |
15 | public UnaryOperation (Expression expression) {
16 | this.expression = expression;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/expressions/ValueExpression.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.expressions;
2 |
3 | import com.kadet.compiler.entities.Value;
4 | import com.kadet.compiler.util.KadetException;
5 |
6 | /**
7 | * Date: 30.03.14
8 | * Time: 18:01
9 | *
10 | * @author Кадет
11 | */
12 | public class ValueExpression implements Expression {
13 |
14 | private Value value;
15 |
16 | public ValueExpression (Value value) {
17 | this.value = value;
18 | }
19 |
20 | @Override
21 | public Value calculate () throws KadetException {
22 | return value;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/initializers/Initializer.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.initializers;
2 |
3 | import com.kadet.compiler.util.KadetException;
4 |
5 | /**
6 | * Date: 30.04.14
7 | * Time: 16:53
8 | *
9 | * @author SarokaA
10 | */
11 | public interface Initializer {
12 |
13 | public void initialize(T t) throws KadetException;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/initializers/ProcedureInitializer.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.initializers;
2 |
3 | import com.kadet.compiler.entities.Constant;
4 | import com.kadet.compiler.entities.Procedure;
5 | import com.kadet.compiler.util.KadetException;
6 |
7 | /**
8 | * Date: 30.03.14
9 | * Time: 14:20
10 | *
11 | * @author Кадет
12 | */
13 | public class ProcedureInitializer implements Initializer {
14 |
15 | public ProcedureInitializer() {
16 | }
17 |
18 | public void initialize (Procedure procedure) throws KadetException {
19 | for (Constant constant: procedure.getConstants()) {
20 | constant.initialize();
21 | }
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/util/Errors.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.util;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Date: 30.03.14
8 | * Time: 12:38
9 | *
10 | * @author Кадет
11 | */
12 | public class Errors {
13 |
14 | private static List errors = new ArrayList();
15 |
16 | public static void addError (KadetError error) {
17 | errors.add(error);
18 | }
19 |
20 | public static boolean hasErrors () {
21 | return errors.size() == 0;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/util/KadetError.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.util;
2 |
3 | /**
4 | * Date: 30.03.14
5 | * Time: 13:28
6 | *
7 | * @author Кадет
8 | */
9 | public class KadetError {
10 |
11 | private int lineNumber;
12 | private String errorText;
13 |
14 | public KadetError (int lineNumber, String errorText) {
15 | this.lineNumber = lineNumber;
16 | this.errorText = errorText;
17 | }
18 |
19 | public KadetError (String errorText) {
20 | this.errorText = errorText;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/util/KadetException.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.util;
2 |
3 | /**
4 | * Date: 31.03.14
5 | * Time: 0:49
6 | *
7 | * @author Кадет
8 | */
9 | public class KadetException extends Exception {
10 |
11 | public KadetException (String message) {
12 | super(message);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/util/ProcedureUtils.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.util;
2 |
3 | import com.kadet.compiler.entities.Function;
4 | import com.kadet.compiler.entities.Procedure;
5 | import com.kadet.compiler.entities.Variable;
6 |
7 | import java.util.ArrayList;
8 | import java.util.List;
9 |
10 | /**
11 | * Date: 29.04.14
12 | * Time: 23:05
13 | *
14 | * @author SarokaA
15 | */
16 | public final class ProcedureUtils {
17 |
18 |
19 | public static boolean hasSuchProcedureName(String name, Procedure procedure) {
20 | boolean hasName = false;
21 | for (Procedure currentProcedure : procedure.getProcedures()) {
22 | if (currentProcedure.hasSuchName(name)) {
23 | hasName = true;
24 | }
25 | }
26 | Procedure parentProcedure = procedure.getParentProcedure();
27 | while (parentProcedure != null) {
28 | for (Procedure currentProcedure : parentProcedure.getProcedures()) {
29 | if (currentProcedure.hasSuchName(name)) {
30 | hasName = true;
31 | }
32 | }
33 | parentProcedure = parentProcedure.getParentProcedure();
34 | }
35 | return hasName;
36 | }
37 |
38 | public static List getProceduresFromProcedure (Procedure procedure) {
39 | List procedures = new ArrayList();
40 | for (Procedure currentProcedure : procedure.getProcedures()) {
41 | procedures.add(currentProcedure);
42 | }
43 | Procedure parentProcedure = procedure.getParentProcedure();
44 | while (parentProcedure != null) {
45 | for (Procedure currentProcedure : parentProcedure.getProcedures()) {
46 | procedures.add(currentProcedure);
47 | }
48 | parentProcedure = parentProcedure.getParentProcedure();
49 | }
50 | return procedures;
51 | }
52 |
53 | public static Procedure getProcedureFromProcedure(String name, Procedure procedure) throws KadetException {
54 | for (Procedure currentProcedure : ProcedureUtils.getProceduresFromProcedure(procedure)) {
55 | if (currentProcedure.hasSuchName(name)) {
56 | return currentProcedure;
57 | }
58 | }
59 | throw new KadetException("There are no such procedure!");
60 | }
61 |
62 |
63 | public static boolean hasSuchFunctionName(String name, Procedure procedure) {
64 | boolean hasName = false;
65 | for (Function currentFunction : procedure.getFunctions()) {
66 | if (currentFunction.hasSuchName(name)) {
67 | hasName = true;
68 | }
69 | }
70 | Procedure parentProcedure = procedure.getParentProcedure();
71 | while (parentProcedure != null) {
72 | for (Function currentFunction : parentProcedure.getFunctions()) {
73 | if (currentFunction.hasSuchName(name)) {
74 | hasName = true;
75 | }
76 | }
77 | parentProcedure = parentProcedure.getParentProcedure();
78 | }
79 | return hasName;
80 | }
81 |
82 | public static List getFunctionsFromProcedure (Procedure procedure) {
83 | List functions = new ArrayList();
84 | for (Function currentFunction : procedure.getFunctions()) {
85 | functions.add(currentFunction);
86 | }
87 | Procedure parentProcedure = procedure.getParentProcedure();
88 | while (parentProcedure != null) {
89 | for (Function currentFunction : parentProcedure.getFunctions()) {
90 | functions.add(currentFunction);
91 | }
92 | parentProcedure = parentProcedure.getParentProcedure();
93 | }
94 | return functions;
95 | }
96 |
97 | public static Function getFunctionFromProcedure(String name, Procedure procedure) throws KadetException {
98 | for (Function currentFunction : ProcedureUtils.getFunctionsFromProcedure(procedure)) {
99 | if (currentFunction.hasSuchName(name)) {
100 | return currentFunction;
101 | }
102 | }
103 | throw new KadetException("There are no such procedure!");
104 | }
105 |
106 |
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/util/ValueFactory.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.util;
2 |
3 | import com.kadet.compiler.entities.Type;
4 | import com.kadet.compiler.entities.*;
5 |
6 | import java.util.ArrayList;
7 |
8 | /**
9 | * Date: 31.03.14
10 | * Time: 2:00
11 | *
12 | * @author Кадет
13 | */
14 | public final class ValueFactory {
15 |
16 | public static Value createValue (Type type) {
17 | switch (type) {
18 | case BOOLEAN: {
19 | return new Bool(false);
20 | }
21 | case ELEMENT: {
22 | return new Element(new Object());
23 | }
24 | case INTEGER: {
25 | return new Int(0);
26 | }
27 | case LIST: {
28 | return new List(new ArrayList());
29 | }
30 | case VALUE: {
31 | return new Value();
32 | }
33 | default: {
34 | return new Value();
35 | }
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/main/java/com/kadet/compiler/util/ValueUtils.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.util;
2 |
3 | import com.kadet.compiler.entities.Type;
4 | import com.kadet.compiler.entities.Bool;
5 | import com.kadet.compiler.entities.Int;
6 | import com.kadet.compiler.entities.List;
7 | import com.kadet.compiler.entities.Value;
8 |
9 | /**
10 | * Date: 31.03.14
11 | * Time: 0:34
12 | *
13 | * @author Кадет
14 | */
15 | public final class ValueUtils {
16 |
17 | public static boolean isBoolean (Value value) {
18 | try {
19 | Bool boolValue = (Bool)value;
20 | Object content = boolValue.getContent();
21 | if (!(content instanceof Boolean)) {
22 | return false;
23 | }
24 | return true;
25 | } catch (Exception e) {
26 | return false;
27 | }
28 | }
29 |
30 | public static Boolean getBooleanFromValue (Value value) {
31 | if (!isBoolean(value)) {
32 | throw new RuntimeException("Value is not Boolean!");
33 | }
34 | return ((java.lang.Boolean)((Bool)value).getContent());
35 | }
36 |
37 | public static boolean isElement (Value value) {
38 | return value.getType() == Type.ELEMENT
39 | || value.getType() == Type.INTEGER
40 | || value.getType() == Type.BOOLEAN;
41 | }
42 |
43 | public static boolean isInteger (Value value) {
44 | try {
45 | Int intValue = (Int)value;
46 | Object content = intValue.getContent();
47 | if (!(content instanceof Integer)) {
48 | return false;
49 | }
50 | return true;
51 | } catch (Exception e) {
52 | return false;
53 | }
54 | }
55 |
56 | public static Integer getIntegerFromValue (Value value) {
57 | if (!isInteger(value)) {
58 | throw new RuntimeException("Value is not Integer!");
59 | }
60 | return ((Integer)((Int)value).getContent());
61 | }
62 |
63 | public static boolean isList (Value value) {
64 | try {
65 | List listValue = (List)value;
66 | java.util.List values = listValue.getValues();
67 | return true;
68 | } catch (Exception e) {
69 | return false;
70 | }
71 | }
72 |
73 | public static java.util.List getListFromValue (Value value) {
74 | if (!isList(value)) {
75 | throw new RuntimeException("Value is not List!");
76 | }
77 | return (((List)value).getValues());
78 | }
79 |
80 | public static boolean isElementAndList (Value value1, Value value2) {
81 | return (isElement(value1) && isList(value2));
82 | }
83 |
84 | public static boolean isListAndElement (Value value1, Value value2) {
85 | return (isList(value1) && isElement(value2));
86 | }
87 |
88 | public static boolean isListAndList (Value value1, Value value2) {
89 | return (isList(value1) && isList(value2));
90 | }
91 |
92 | public static boolean isElementAndElement (Value value1, Value value2) {
93 | return (isElement(value1) && isElement(value2));
94 | }
95 |
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/1 Compiler/version4/src/test/java/com/kadet/compiler/Main.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import com.kadet.compiler.evaluators.Evaluator;
4 | import com.kadet.compiler.util.KadetException;
5 |
6 | /**
7 | * Date: 29.04.14
8 | * Time: 20:42
9 | *
10 | * @author SarokaA
11 | */
12 | public class Main {
13 |
14 | public static void main(String[] args) throws KadetException {
15 | KadetCompiler compiler = new KadetCompiler();
16 | Evaluator evaluator = compiler.compile("program XLSample = " +
17 | "\n var x : Boolean;" +
18 | "\n" +
19 | "\nbegin " +
20 | "\n x := >=>;" +
21 | "\n x := >=>;" +
22 | "\n x := >=>;" +
23 | "\n x := >=>;" +
24 | "\nend XLSample.");
25 | evaluator.evaluate();
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/Errors.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import java.util.List;
4 |
5 | public class Errors {
6 |
7 | public void DuplicateError(String name_var, int line) {
8 | System.out.println("ERROR : Duplicate local variable '" + name_var
9 | + "' in line " + line);
10 | }
11 |
12 | public void UndefinedVar(String name_var, int line) {
13 | System.out.println("ERROR : The var '" + name_var
14 | + "' is undefined in line " + line);
15 | }
16 |
17 | public void UndefinedMethod(String name_func, int line) {
18 | System.out.println("ERROR : The method '" + name_func
19 | + "' is undefined in line " + line);
20 | }
21 |
22 | public void DuplicateMethod(String name_funcElse, int line) {
23 | System.out.println("ERROR : Duplicate local method '" + name_funcElse
24 | + "' in line " + line);
25 | }
26 |
27 | public void MethodWithoutParams(String name_func, int line) {
28 | System.out.println("ERROR : Method '" + name_func
29 | + "' must't have any parametrs in line " + line);
30 | }
31 |
32 | public void MethodWithParams(String name_func, int line, int kol_params) {
33 | System.out.println("ERROR : Method '" + name_func + "' must have "
34 | + kol_params + " parametrs in line " + line);
35 | }
36 |
37 | public void MethodWithErrorsParams(String name_func, int line,
38 | List params) {
39 | System.out.println("ERROR : Method '" + name_func + "' must have "
40 | + params + " parametrs in line " + line);
41 | }
42 |
43 | public void WrongType(String type1, String type2, int line) {
44 | System.out.println("ERROR : Types '" + type1
45 | + "' and '" + type2 + "' must be casts in line " + line);
46 | }
47 |
48 | public void BadRetType(String type, String prevType, int line) {
49 | System.out.println("ERROR : Return type must be '" + type
50 | + "' first return has '" + prevType + "' in line " + line);
51 | }
52 |
53 | public void NotReturnFunc(String name, int line) {
54 | System.out.println("ERROR : Function '" + name
55 | + "' can't return smth in line " + line);
56 | }
57 |
58 | public void ReturnFunc(String name, int line) {
59 | System.out.println("ERROR : Function '" + name
60 | + "' must have a return value in line " + line);
61 | }
62 |
63 | public void CheckOnRet(int line) {
64 | System.out.println("ERROR : Function must be returnble " + line);
65 | }
66 |
67 | public void LastRet(int line) {
68 | System.out.println("ERROR : Function must have last return " + line);
69 | }
70 |
71 | ////
72 |
73 | public static void BadAfterRet(int line) {
74 | System.out.println("ERROR : instraction can't be after return in line " + line);
75 | }
76 |
77 | public void RetDontNeed(int line) {
78 | System.out.println("ERROR : Return don't need in this func in line " + line);
79 | }
80 |
81 | public void VarDontInit(String name, int line) {
82 | System.out.println("ERROR : Variable '" + name
83 | + "' must be initialize in line " + line);
84 | }
85 |
86 | public static void BadBlockLine(int line) {
87 | System.out.println("ERROR : Block line have uncorrect tab number in line " + line);
88 | }
89 |
90 | public static void WrongStageVar(int line) {
91 | System.out.println("ERROR : wrong stage for define global var in line " + line);
92 | }
93 |
94 | public static void WrongStageFun(int line) {
95 | System.out.println("ERROR : wrong stage for define global fun in line " + line);
96 | }
97 |
98 | public static void WrongStageMain(int line) {
99 | System.out.println("ERROR : wrong stage for define global main in line " + line);
100 | }
101 |
102 | public static void WrongIfElse(int line) {
103 | System.out.println("ERROR : wrong If Else operator in line " + line);
104 | }
105 | }
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/Function.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import java.util.LinkedList;
4 | import java.util.List;
5 |
6 | public class Function {
7 | private String name ;
8 | private Type type = Type.NON;
9 | private List params = new LinkedList();
10 | private boolean hasLastRet = false;
11 |
12 |
13 | public Function(String name) {
14 | super();
15 | this.name = name;
16 | }
17 |
18 | public Function(String name, Type type) {
19 | super();
20 | this.name = name;
21 | this.type = type;
22 | if(type!=null && !Type.NON.equals(type)) setHasLastRet(true);
23 | }
24 |
25 | public String getName() {
26 | return name;
27 | }
28 |
29 | public void setName(String name) {
30 | this.name = name;
31 | }
32 |
33 | public Type getType() {
34 | return type;
35 | }
36 |
37 | public void setType(Type type) {
38 | this.type = type;
39 | if(type!=null && !Type.NON.equals(type)) setHasLastRet(true);
40 | }
41 |
42 | public List getParams() {
43 | return params;
44 | }
45 |
46 | public void setParams(List params) {
47 | this.params = params;
48 | }
49 |
50 | public boolean isHasLastRet() {
51 | return hasLastRet;
52 | }
53 |
54 | public void setHasLastRet(boolean hasLastRet) {
55 | this.hasLastRet = hasLastRet;
56 | }
57 |
58 | public boolean equals(Object other) {
59 | if (this.getClass() != other.getClass())
60 | return false;
61 | Function otherObj = (Function) other;
62 | return this.name.equals(otherObj.getName());
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/GggCompiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 |
9 | public class GggCompiler extends AbstractCompiler{
10 |
11 |
12 | @Override
13 | public CommonTree compile (String expression) {
14 | return null;
15 | }
16 |
17 | public void compileCode(String code) {
18 |
19 | try {
20 | System.out.println("Code: " + code);
21 |
22 | //lexer splits input into tokens
23 | ANTLRStringStream input = new ANTLRStringStream(code);
24 | gggggLexer lexer = new gggggLexer(input);
25 | TokenStream tokens = new CommonTokenStream(lexer);
26 |
27 | //parser generates abstract syntax tree
28 | gggggParser parser = new gggggParser(tokens);
29 | gggggParser.program_return programReturn = parser.program();
30 |
31 | System.out.println("start = " + programReturn.start);
32 |
33 | //acquire parse result
34 | CommonTree ast = (CommonTree) programReturn.tree;
35 | printTree(ast);
36 |
37 | } catch (RecognitionException e) {
38 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
39 | }
40 |
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/Sample3.g:
--------------------------------------------------------------------------------
1 | grammar Sample3;
2 |
3 | options {
4 |
5 | // java lexer and parser
6 | language = Java;
7 |
8 | // abstract syntax tree
9 | output = AST;
10 |
11 | }
12 |
13 | @lexer::header {
14 | package com.kadet.compiler;
15 |
16 | import com.kadet.compiler.evaluators.*;
17 | }
18 |
19 | @parser::header {
20 | package com.kadet.compiler;
21 |
22 | import com.kadet.compiler.evaluators.*;
23 | }
24 |
25 |
26 | evaluator returns [Evaluator e]
27 | : expression EOF { $e = $expression.e; }
28 | ;
29 |
30 |
31 | // expressions fun time
32 |
33 | term returns [Evaluator e]
34 | : IDENT { $e = new IntEvaluator(0); }
35 | | '(' expression ')' { $e = $expression.e; }
36 | | INTEGER { $e = new IntEvaluator(Integer.parseInt($INTEGER.text)); }
37 | ;
38 |
39 |
40 | unary returns [Evaluator e]
41 | : { boolean positive = true;}
42 | ( '+'
43 | | '-' { positive = !positive; }
44 | )* term {
45 | $e = $term.e;
46 | if (!positive)
47 | $e = new NegationEvaluator($e);
48 | }
49 | ;
50 |
51 | mult returns [Evaluator e]
52 | : op1 = unary { $e = $op1.e; }
53 | ( '*' op2 = unary { $e = new TimesEvaluator($e, $op2.e); }
54 | | '/' op2 = unary { $e = new DivideEvaluator($e, $op2.e); }
55 | | 'mod' op2 = unary { $e = new ModEvaluator($e, $op2.e); }
56 | )*
57 | ;
58 |
59 | expression returns [Evaluator e]
60 | : op1 = mult { $e = $op1.e;}
61 | ( '+' op2 = mult { $e = new PlusEvaluator($e, $op2.e); }
62 | | '-' op2 = mult { $e = new MinusEvaluator($e, $op2.e); }
63 | )*
64 | ;
65 |
66 | fragment LETTER
67 | : ('a'..'z' | 'A'..'Z')
68 | ;
69 |
70 | fragment DIGIT
71 | : '0'..'9'
72 | ;
73 |
74 | IDENT
75 | : ( LETTER )( LETTER | DIGIT )*
76 | ;
77 |
78 | INTEGER
79 | : DIGIT+
80 | ;
81 |
82 | STRING_LITERAL
83 | : '"'
84 | {
85 | StringBuilder b = new StringBuilder();
86 | }
87 | (
88 | ('\\' '"') { b.appendCodePoint('"');}
89 | |
90 | c = ~( '"' | '\r' | '\n' ) { b.appendCodePoint(c);}
91 | )*
92 | '"'
93 | { setText (b.toString());}
94 | ;
95 |
96 | CHAR_LITERAL
97 | : '\'' . '\'' {setText(getText().substring(1, 2));}
98 | ;
99 |
100 | WS
101 | : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}
102 | ;
103 |
104 | COMMENT
105 | : '//' .* ('\n' | '\r') {$channel = HIDDEN;}
106 | ;
107 |
108 | MULTIPLE_COMMENT
109 | : '/*' .* '*/' {$channel = HIDDEN;}
110 | ;
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/Sample3Compiler.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.antlr.runtime.ANTLRStringStream;
4 | import org.antlr.runtime.CommonTokenStream;
5 | import org.antlr.runtime.RecognitionException;
6 | import org.antlr.runtime.TokenStream;
7 | import org.antlr.runtime.tree.CommonTree;
8 |
9 | public class Sample3Compiler extends AbstractCompiler{
10 |
11 |
12 | public CommonTree compile(String expression) {
13 | try {
14 | System.out.println("expression: " + expression);
15 |
16 | //lexer splits input into tokens
17 | ANTLRStringStream input = new ANTLRStringStream(expression);
18 | Sample3Lexer lexer = new Sample3Lexer(input);
19 | TokenStream tokens = new CommonTokenStream(lexer);
20 |
21 | //parser generates abstract syntax tree
22 | Sample3Parser parser = new com.kadet.compiler.Sample3Parser(tokens);
23 | Sample3Parser.evaluator_return programReturn = parser.evaluator();
24 |
25 | System.out.println("result = " + programReturn.e.evaluate());
26 |
27 | //acquire parse result
28 | CommonTree ast = (CommonTree) programReturn.tree;
29 | printTree(ast);
30 | return ast;
31 |
32 | } catch (RecognitionException e) {
33 | throw new IllegalStateException("Recognition exception is never thrown, only declared.");
34 | }
35 |
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/Sample3Test.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.junit.Test;
4 |
5 | public class Sample3Test {
6 |
7 | @Test
8 | public void Void () {
9 |
10 | }
11 |
12 | /*@Test
13 | public void expressionEvaluation () {
14 | Sample3Compiler sample3Compiler = new Sample3Compiler();
15 | sample3Compiler.compile("4 * 3\n\r");
16 | }
17 |
18 | @Test
19 | public void bigExpressionEvaluation () {
20 | Sample3Compiler sample3Compiler = new Sample3Compiler();
21 | sample3Compiler.compile("3 * (4 + 2) - 3\n\r");
22 | }*/
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/Type.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | public enum Type {
4 |
5 | INT("int"), FLOAT("float"),BOOL ("bool"), NON("none");
6 |
7 | private String name;
8 |
9 | Type(String name) {
10 | this.name = name;
11 | }
12 |
13 | public String getName() {
14 | return name;
15 | }
16 | }
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/Variable.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | public class Variable {
4 |
5 | public Variable(String name,String funName) {
6 | super();
7 | this.name = name;
8 | this.funcName = funName;
9 | }
10 |
11 | private String name;
12 | private Type type = Type.NON;
13 | private String funcName;
14 |
15 | public Type getType() {
16 | return type;
17 | }
18 |
19 | public void setType(Type type) {
20 | this.type = type;
21 | }
22 |
23 | public String getFuncName() {
24 | return funcName;
25 | }
26 |
27 | public void setFuncName(String funcName) {
28 | this.funcName = funcName;
29 | }
30 |
31 | public String getName() {
32 | return name;
33 | }
34 |
35 | public void setName(String name) {
36 | this.name = name;
37 | }
38 |
39 | public boolean equals(Object other) {
40 | if (this.getClass() != other.getClass())
41 | return false;
42 | Variable otherObj = (Variable) other;
43 | return this.name.equals(otherObj.getName());
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/evaluators/DivideEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class DivideEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public DivideEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() / op2.evaluate(); //To change body of implemented methods use File | Settings | File Templates.
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/evaluators/Evaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:22
6 | *
7 | * @author Кадет
8 | */
9 | public interface Evaluator {
10 |
11 | int evaluate ();
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/evaluators/IntEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:25
6 | *
7 | * @author Кадет
8 | */
9 | public class IntEvaluator implements Evaluator {
10 |
11 | private int value;
12 |
13 | public IntEvaluator (int value) {
14 | this.value = value;
15 | }
16 |
17 | @Override
18 | public int evaluate () {
19 | return value; //To change body of implemented methods use File | Settings | File Templates.
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/evaluators/MinusEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class MinusEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public MinusEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() - op2.evaluate(); //To change body of implemented methods use File | Settings | File Templates.
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/evaluators/ModEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class ModEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public ModEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() % op2.evaluate(); //To change body of implemented methods use File | Settings | File Templates.
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/evaluators/NegationEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class NegationEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 |
13 | public NegationEvaluator (Evaluator op1) {
14 | this.op1 = op1;
15 | }
16 |
17 | @Override
18 | public int evaluate () {
19 | return -op1.evaluate();
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/evaluators/PlusEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class PlusEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public PlusEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() + op2.evaluate(); //To change body of implemented methods use File | Settings | File Templates.
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/evaluators/TimesEvaluator.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.evaluators;
2 |
3 | /**
4 | * Date: 11.03.14
5 | * Time: 2:26
6 | *
7 | * @author Кадет
8 | */
9 | public class TimesEvaluator implements Evaluator {
10 |
11 | private Evaluator op1;
12 | private Evaluator op2;
13 |
14 | public TimesEvaluator (Evaluator op1, Evaluator op2) {
15 | this.op1 = op1;
16 | this.op2 = op2;
17 | }
18 |
19 | @Override
20 | public int evaluate () {
21 | return op1.evaluate() * op2.evaluate();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/gggTest.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Date: 29.03.14
7 | * Time: 23:30
8 | *
9 | * @author Кадет
10 | */
11 | public class gggTest {
12 |
13 | @Test
14 | public void gggSampleTest () {
15 | GggCompiler gggCompiler = new GggCompiler();
16 | gggCompiler.compileCode("var1 = 12;\n" +
17 | "var2 = 13;\n" +
18 | "\n" +
19 | "\n" +
20 | "\n" +
21 | "Alenamain" +
22 | "\n\t" +
23 | "" +
24 | "\n"
25 | );
26 | }
27 |
28 |
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/test.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler;
2 |
3 |
4 | import java.io.IOException;
5 | import org.antlr.runtime.*;
6 |
7 | public class test {
8 |
9 | public static void main(String[] arg) throws IOException, RecognitionException {
10 |
11 | CharStream input = new ANTLRFileStream("test");
12 |
13 | gggggLexer lexer = new gggggLexer(input);
14 |
15 | CommonTokenStream tokens = new CommonTokenStream(lexer);
16 |
17 |
18 |
19 | gggggParser pars = new gggggParser(tokens);
20 | pars.program();
21 | System.out.println("done!!!");
22 |
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/tokens/Errors.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.tokens;
2 |
3 | /**
4 | * Date: 23.03.14
5 | * Time: 18:16
6 | *
7 | * @author Кадет
8 | */
9 | public class Errors {
10 | }
11 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/tokens/Function.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.tokens;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Date: 23.03.14
8 | * Time: 18:14
9 | *
10 | * @author Кадет
11 | */
12 | public class Function {
13 |
14 | private String name;
15 | private Type type = Type.VOID;
16 | private List params = new ArrayList();
17 | private boolean hasReturn = false;
18 |
19 |
20 | public Function (String name) {
21 | super();
22 | this.name = name;
23 | }
24 |
25 | public Function (String name, Type type) {
26 | super();
27 | this.name = name;
28 | this.type = type;
29 | if (type != null && !Type.VOID.equals(type)) {
30 | setHasReturn(true);
31 | }
32 | }
33 |
34 | public String getName () {
35 | return name;
36 | }
37 |
38 | public void setName (String name) {
39 | this.name = name;
40 | }
41 |
42 | public Type getType () {
43 | return type;
44 | }
45 |
46 | public void setType (Type type) {
47 | this.type = type;
48 | if (type != null && !Type.VOID.equals(type)) {
49 | setHasReturn(true);
50 | }
51 | }
52 |
53 | public List getParams () {
54 | return params;
55 | }
56 |
57 | public void setParams (List params) {
58 | this.params = params;
59 | }
60 |
61 | public boolean isHasReturn () {
62 | return hasReturn;
63 | }
64 |
65 | public void setHasReturn (boolean hasReturn) {
66 | this.hasReturn = hasReturn;
67 | }
68 |
69 | public boolean equals (Object other) {
70 | if (this.getClass() != other.getClass()) {
71 | return false;
72 | }
73 | Function otherObj = (Function) other;
74 | return this.name.equals(otherObj.getName());
75 | }
76 |
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/tokens/Program.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.tokens;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Date: 23.03.14
8 | * Time: 18:13
9 | *
10 | * @author Кадет
11 | */
12 | public class Program {
13 |
14 | private List globalVariables = new ArrayList();
15 | private List functions = new ArrayList();
16 |
17 |
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/tokens/Type.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.tokens;
2 |
3 | /**
4 | * Date: 23.03.14
5 | * Time: 18:20
6 | *
7 | * @author Кадет
8 | */
9 | public enum Type {
10 |
11 | ELEMENT("Element"), LIST("List"), VOID("void");
12 |
13 | private String name;
14 |
15 | Type(String name) {
16 | this.name = name;
17 | }
18 |
19 | public String getName() {
20 | return name;
21 | }
22 |
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/1 Compiler/version4Old/old/tokens/Variable.java:
--------------------------------------------------------------------------------
1 | package com.kadet.compiler.tokens;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Date: 23.03.14
8 | * Time: 18:14
9 | *
10 | * @author Кадет
11 | */
12 | public class Variable {
13 |
14 | private String name;
15 |
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/.gitignore:
--------------------------------------------------------------------------------
1 | tmp/
2 | build/
3 | jasmin.jar
4 |
5 | # generated files
6 | src/llcompiler/ListLangLexer.py
7 | src/llcompiler/ListLangParser.py
8 | src/llcompiler/ListLangWalker.py
9 | src/llcompiler/*.tokens
10 |
11 | ######################## Python
12 | *.py[cod]
13 |
14 | # C extensions
15 | *.so
16 |
17 | # Packages
18 | *.egg
19 | *.egg-info
20 | dist
21 | build
22 | eggs
23 | parts
24 | bin
25 | var
26 | sdist
27 | develop-eggs
28 | .installed.cfg
29 | lib
30 | lib64
31 |
32 | # Installer logs
33 | pip-log.txt
34 |
35 | # Unit test / coverage reports
36 | .coverage
37 | .tox
38 | nosetests.xml
39 |
40 | # Translations
41 | *.mo
42 |
43 | # Mr Developer
44 | .mr.developer.cfg
45 | .project
46 | .pydevproject
47 |
48 |
49 | ########################### PyCharm
50 | *.iml
51 | *.ipr
52 | *.iws
53 | .idea/
54 |
55 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/README.md:
--------------------------------------------------------------------------------
1 | ListLang
2 | ========
3 |
4 | Compiler for developed programming language ListLang based on antlr3.
5 |
6 | Описание языка
7 | --------
8 | Язык для работы со списковыми структурами.
9 |
10 | 1. Встроенные типы
11 | 1. Element: хранит одно значение, которым может быть целое число, список или является пустым.
12 | 2. List: хранит набор элементов.
13 | 2. Переменные
14 | 1. Объявление переменных: не явное
15 | 2. Возможность инициализация переменных всех типов при объявлении: <тип> <имя_переменной> = <выражение>
16 | 3. Инициализирующее выражение может быть константным
17 | 4. Оператор присваивания: одноцелевой, например, a = b
18 | 5. Преобразование типов: явное, например, a = (int) b
19 | 3. Встроенные операции
20 | 4. Встроенные функции
21 | 1. Встроенные функции ввода\вывода для работы со встроенными типами
22 | 5. Использование сложных выражений (составных и со скобками)
23 | 6. Блочный оператор
24 | 1. Маркер блочного оператора: явный, { }
25 | 2. Структуры, ограничивающие область видимости: подпрограммы
26 | 7. Управляющие структуры
27 | 1. Условный оператор (if-then-else)
28 | 2. Операторы цикла (while и until)
29 | 3. Оператор цикла с итерациями (for)
30 | 8. Пользовательские подпрограммы
31 | 1. Передача и возврат параметров
32 | 2. Задание локальной и глобальной области видимости для имен переменных
33 | 3. Перегрузка подпрограмм: отсутствует
34 | 4. Передача параметров в подпрограмму: только по значению и возвращаемому значению
35 | 5. Допустимое место объявления подпрограмм: В любом месте программы, также и внутри другой подпрограммы.
36 |
37 |
38 | Целевой код компилятора: байт-код JVM, формат промежуточного кода ассемблер для JVM.
39 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/examples/error_lexer.ll:
--------------------------------------------------------------------------------
1 | 3a = 1
2 |
3 | bва = [1, 2, 3]
4 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/examples/error_parser.ll:
--------------------------------------------------------------------------------
1 | if not 1 {
2 | print 0
3 | }}
4 |
5 | print 1
--------------------------------------------------------------------------------
/Foreign/ListLang-master/examples/error_semantic.ll:
--------------------------------------------------------------------------------
1 |
2 | [] > 1
3 |
4 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/examples/merge_sorted_lists.ll:
--------------------------------------------------------------------------------
1 | // Отсортировать и объединить списки в сортированный список
2 | define mergeSortedLists(List l1, List l2) {
3 | define quickSort(List l) {
4 |
5 | if not l {
6 | return []
7 | }
8 |
9 | pivot = l[0]
10 |
11 | low = []
12 | high = []
13 | if len(l) > 1 {
14 | for x in l[1:len(l)] {
15 | if x < pivot {
16 | low = low + x
17 | } else {
18 | high = high + x
19 | }
20 | }
21 | }
22 |
23 | lesser = quickSort(low)
24 | greater = quickSort(high)
25 |
26 | return lesser + [pivot] + greater
27 | }
28 |
29 | l1 = quickSort(l1)
30 | l2 = quickSort(l2)
31 |
32 | result = []
33 |
34 | while 1 {
35 | if not l1 {
36 | return result + l2
37 | } elif not l2 {
38 | return result + l1
39 | } else {
40 | if l1[0] < l2[0] {
41 | result = result + l1[0]
42 | --l1
43 | } else {
44 | result = result + l2[0]
45 | --l2
46 | }
47 | }
48 | }
49 |
50 | return result
51 | }
52 |
53 | list1 = read_list()
54 | list2 = read_list()
55 | result = [1, 2, 3, 3, 5, 6, 6, 8, 9]
56 |
57 | print mergeSortedLists(list1, list2)
58 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/examples/quicksort.ll:
--------------------------------------------------------------------------------
1 | define quickSort(List l) {
2 |
3 | if not l {
4 | return []
5 | }
6 |
7 | pivot = l[0]
8 |
9 | low = []
10 | high = []
11 | if len(l) > 1 {
12 | for x in l[1:len(l)] {
13 | if x < pivot {
14 | low = low + x
15 | } else {
16 | high = high + x
17 | }
18 | }
19 | }
20 |
21 | lesser = quickSort(low)
22 | greater = quickSort(high)
23 |
24 | return lesser + [pivot] + greater
25 | }
26 |
27 | l = [6, 4, 8, 8, 1, 4, 6, 3, 5, 1]
28 |
29 | print quickSort(l) == [1, 1, 3, 4, 4, 5, 6, 6, 8, 8]
30 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/examples/recursion.ll:
--------------------------------------------------------------------------------
1 | i = 0
2 | define f() {
3 | global i
4 | i = i + 1
5 | print i
6 | if i < 5 {
7 | f()
8 | }
9 | }
10 |
11 | f()
--------------------------------------------------------------------------------
/Foreign/ListLang-master/examples/reverse.ll:
--------------------------------------------------------------------------------
1 | define reverse(List l) {
2 | result = []
3 | while l {
4 | result = l[0] + result
5 | --l
6 | }
7 | return result
8 | }
9 |
10 | list = [1, 2, 3, 4, 5]
11 |
12 | print reverse(list) == [5, 4, 3, 2, 1]
13 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/examples/simple.ll:
--------------------------------------------------------------------------------
1 |
2 | x = read_list()
3 |
4 | print x + 1
--------------------------------------------------------------------------------
/Foreign/ListLang-master/rebuild.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | SET ANTLR_JAR_FILE=C:\antlr\antlr-3.1.3.jar
4 | SET JDK_HOME=c:\Program Files\Java\jdk1.7.0_07\bin\
5 |
6 | rmdir /s /q build
7 | mkdir build\adds build\examples build\llcompiler build\tmp
8 |
9 | ECHO rebuild: antlr grammar
10 | java -jar %ANTLR_JAR_FILE% -fo src\llcompiler -make src\ListLang.g
11 | java -jar %ANTLR_JAR_FILE% -fo src\llcompiler -make src\ListLangWalker.g
12 |
13 | ECHO rebuild: java List
14 | CALL "%JDK_HOME%javac.exe" -d build\adds src\List.java
15 |
16 | ECHO rebuild: make llcompiler
17 | copy jasmin.jar build\
18 | copy src\listlang.py build\
19 | copy src\readme.txt build\
20 | xcopy src\adds build\adds\ /e /y
21 | IF ERRORLEVEL 1 GOTO EXIT
22 | for /R src\llcompiler %%f in (*.py) do copy "%%f" build\llcompiler\
23 |
24 | ECHO rebuild: copy examples
25 | for /R examples %%f in (*.ll) do copy "%%f" build\examples\
26 |
27 | :EXIT
--------------------------------------------------------------------------------
/Foreign/ListLang-master/run.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | SET JASMIN_JAR_FILE=tmp\jasmin.jar
4 | SET PYTHON_HOME=
5 |
6 | CALL "%PYTHON_HOME%python.exe" src\listlang.py %1 tmp\target.j
7 | IF ERRORLEVEL 1 GOTO EXIT
8 | @java -jar %JASMIN_JAR_FILE% -d tmp\ tmp\target.j
9 | IF ERRORLEVEL 1 GOTO EXIT
10 | java -cp tmp\ LLMain
11 | IF ERRORLEVEL 1 GOTO EXIT
12 | :EXIT
--------------------------------------------------------------------------------
/Foreign/ListLang-master/src/List.java:
--------------------------------------------------------------------------------
1 | package listlang.objects;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.util.regex.Matcher;
7 | import java.util.regex.Pattern;
8 |
9 | import java.util.LinkedList;
10 |
11 | public class List {
12 |
13 | static final Pattern listPattern = Pattern.compile(" *\\[ *\\d+(, *\\d+ *)* *\\] *");
14 | static final Pattern numberPattern = Pattern.compile("\\d+");
15 |
16 | public static List read() {
17 | List readedList = new List();
18 |
19 | // read line from stdin
20 | BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
21 | String line = "";
22 | try {
23 | line = bufferedreader.readLine();
24 | } catch (IOException e) {
25 | e.printStackTrace();
26 | }
27 |
28 | // parse readed line
29 | Matcher listMatcher = listPattern.matcher(line);
30 | if(listMatcher.matches()) {
31 | Matcher numberMatcher = numberPattern.matcher(line);
32 |
33 | while (numberMatcher.find()) {
34 | readedList.addLast(Integer.parseInt(numberMatcher.group()));
35 | }
36 | }
37 |
38 | return readedList;
39 | }
40 |
41 | private LinkedList mList = new LinkedList();
42 |
43 | public List() {
44 | }
45 |
46 | public void print() {
47 | String str = "";
48 | if(!mList.isEmpty()) {
49 | str = mList.get(0).toString();
50 | for(int i = 1; i < mList.size(); i++) {
51 | str += ", " + mList.get(i).toString();
52 | }
53 | }
54 | System.out.print("[" + str + "]");
55 | }
56 |
57 | public int count(int n) {
58 | int n_count = 0;
59 | for(int val : mList) {
60 | if(val == n) {
61 | n_count++;
62 | }
63 | }
64 | return n_count;
65 | }
66 |
67 | @SuppressWarnings("unchecked")
68 | public List(LinkedList linkedList) {
69 | mList = (LinkedList) linkedList.clone();
70 | }
71 |
72 | public List clone() {
73 | return new List(this.getLinkedList());
74 | }
75 |
76 | public LinkedList getLinkedList() {
77 | return mList;
78 | }
79 |
80 | public void addFirst(int n) {
81 | mList.addFirst(new Integer(n));
82 | }
83 |
84 | public void addLast(int n) {
85 | mList.addLast(new Integer(n));
86 | }
87 |
88 | public void removeFirst() {
89 | mList.remove(0);
90 | }
91 |
92 | public void removeLast() {
93 | mList.remove(mList.size() - 1);
94 | }
95 |
96 | public void delete(int i) {
97 | mList.remove(i);
98 | }
99 |
100 | public boolean boolean_value() {
101 | return !mList.isEmpty();
102 | }
103 |
104 | public int to_int() {
105 | return boolean_value() ? 1 : 0;
106 | }
107 |
108 | // expressions
109 |
110 | public int get(int i) {
111 | return mList.get(i).intValue();
112 | }
113 |
114 | public List slice(int begin, int end) {
115 | LinkedList slicingLinkedList = this.getLinkedList();
116 | for(int i = slicingLinkedList.size() - end; i > 0; i--) {
117 | slicingLinkedList.remove(end);
118 | }
119 | for(int i = 0; i < begin; i++) {
120 | slicingLinkedList.remove(0);
121 | }
122 | return new List(slicingLinkedList);
123 | }
124 |
125 | public int len() {
126 | return mList.size();
127 | }
128 |
129 | public int equal(List second) {
130 | if(second.getLinkedList().equals(mList)) {
131 | return 1;
132 | } else {
133 | return 0;
134 | }
135 | }
136 |
137 | public List concat(List second) {
138 | List resList = this.clone();
139 | for(int i = 0; i < second.len(); i++) {
140 | resList.addLast(second.get(i));
141 | }
142 | return resList;
143 | }
144 |
145 | public List multiply(int times) {
146 | List result = this;
147 | for(int i = 1; i < times; i++) {
148 | result = result.concat(this);
149 | }
150 | return result;
151 | }
152 |
153 | public List removeEvery(int n) {
154 | List result = clone();
155 | int i = 0;
156 | while(i < result.len()) {
157 | if(result.get(i) == n) {
158 | result.delete(i);
159 | } else {
160 | i++;
161 | }
162 | }
163 | return result;
164 | }
165 |
166 | public List pre_incr() {
167 | addFirst(0);
168 | return this;
169 | }
170 |
171 | public List pre_decr() {
172 | delete(0);
173 | return this;
174 | }
175 |
176 | public List post_incr() {
177 | addLast(0);
178 | return this;
179 | }
180 |
181 | public List post_decr() {
182 | delete(len() - 1);
183 | return this;
184 | }
185 | }
186 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/src/adds/META-INF/MANIFEST.MF:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 | Main-Class: listlang/program/LLMain
3 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/src/listlang.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | from llcompiler import error_processor, ListLangParser, ListLangWalker, ListLangLexer
4 |
5 | __author__ = 'Oleg Beloglazov'
6 |
7 |
8 | import sys
9 | import os
10 | import argparse
11 | import subprocess
12 | import shutil
13 | import zipfile
14 |
15 | import antlr3
16 | import antlr3.tree
17 |
18 |
19 | def tokens_out(tokens, tokens_filename):
20 | dir_name = os.path.dirname(tokens_filename)
21 | if not os.path.exists(dir_name):
22 | os.makedirs(dir_name)
23 | tokens_file = open(tokens_filename, 'w')
24 |
25 | for token in tokens:
26 | tokens_file.write('%3s |%3s: %s\n' %
27 | (str(token.getTokenIndex()),
28 | str(token.getType()),
29 | repr(token.getText()))
30 | )
31 | tokens_file.close()
32 |
33 |
34 | def make_jasmin_file(src_filename, dest_filename, tokens_filename=''):
35 | # Run lexer
36 | char_stream = antlr3.ANTLRFileStream(src_filename, encoding='utf8')
37 | lexer = ListLangLexer.ListLangLexer(char_stream)
38 | tokens = antlr3.CommonTokenStream(lexer)
39 |
40 | if tokens_filename:
41 | tokens_out(tokens.getTokens(), tokens_filename)
42 |
43 | # Get AST tree
44 | parser = ListLangParser.ListLangParser(tokens)
45 | ast = parser.program().tree
46 |
47 | #print ast.toStringTree()
48 |
49 | errors = error_processor.get_all_errors()
50 | if errors:
51 | sys.stderr.write('\n'.join(errors))
52 | sys.exit(1)
53 |
54 | nodes = antlr3.tree.CommonTreeNodeStream(ast)
55 | nodes.setTokenStream(tokens)
56 |
57 | walker = ListLangWalker.ListLangWalker(nodes)
58 |
59 | try:
60 | target_code = walker.program()
61 | except error_processor.SemanticException as e:
62 | error_processor.add_error(error_processor.SEMANTIC, e.line, e.pos_in_line, e.message)
63 |
64 | errors = error_processor.get_all_errors()
65 | if errors:
66 | sys.stderr.write('\n'.join(errors))
67 | sys.exit(1)
68 |
69 | if target_code:
70 | target_file = open(dest_filename, 'w')
71 | target_file.write(target_code)
72 | target_file.close()
73 |
74 |
75 | def get_dir_files_paths(dir_path, recursive=False):
76 | child_paths = [os.path.join(dir_path, file) for file in os.listdir(dir_path)]
77 |
78 | files_paths = []
79 | if child_paths:
80 | for path in child_paths:
81 | if os.path.isdir(path) and recursive:
82 | files_paths += get_dir_files_paths(path, recursive)
83 | elif os.path.isfile(path):
84 | files_paths.append(path)
85 | else:
86 | pass
87 |
88 | return files_paths
89 |
90 |
91 | def cmd(args):
92 | try:
93 | output = subprocess.check_output(args, stderr=subprocess.STDOUT, shell=True)
94 | except subprocess.CalledProcessError as e:
95 | output = e.output
96 | return output
97 |
98 |
99 | def zipfile_add_directory(zip_file, target_dir):
100 | rootlen = len(target_dir)
101 | for base, dirs, files in os.walk(target_dir):
102 | for file in files:
103 | fn = os.path.join(base, file)
104 | zip_file.write(fn, fn[rootlen:])
105 |
106 | def main():
107 | # Parse command line arguments
108 | args_parser = argparse.ArgumentParser(description='Compile listlang source files.')
109 | args_parser.add_argument('src_filename', type=str, help='path to source file')
110 | args_parser.add_argument('dest_filename', type=str, help='path to output compiled file')
111 | args_parser.add_argument('--tokens', '-t', dest='tokens_filename', help='get file with tokens')
112 | args = args_parser.parse_args()
113 |
114 | BUILDING_DIR = 'tmp/lljar/'
115 | JFILENAME = BUILDING_DIR + 'target.j'
116 |
117 | # prepare building directory
118 | if os.path.exists(BUILDING_DIR):
119 | shutil.rmtree(BUILDING_DIR)
120 | shutil.copytree('adds', BUILDING_DIR)
121 |
122 | # make target file with jasmin code
123 | make_jasmin_file(args.src_filename, JFILENAME, args.tokens_filename)
124 |
125 | # compile jasmin file
126 | cmd(r'java -jar jasmin.jar -d %s %s' % (BUILDING_DIR, JFILENAME))
127 | os.remove(JFILENAME)
128 |
129 | # make jar file
130 | print 'creating jar file'
131 | zf = zipfile.ZipFile(args.dest_filename, mode='w')
132 | zipfile_add_directory(zf, BUILDING_DIR)
133 | zf.close()
134 |
135 |
136 | if __name__ == "__main__":
137 | main()
--------------------------------------------------------------------------------
/Foreign/ListLang-master/src/llcompiler/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/Foreign/ListLang-master/src/llcompiler/__init__.py
--------------------------------------------------------------------------------
/Foreign/ListLang-master/src/llcompiler/error_processor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | __author__ = 'Oleg Beloglazov'
5 |
6 |
7 | # Error types
8 | LEXICAL = 'lexical'
9 | SYNTAX = 'syntax'
10 | SEMANTIC = 'semantic'
11 |
12 | lexical_errors = []
13 | syntax_errors = []
14 | semantic_errors = []
15 |
16 |
17 | def add_error(error_type, line, pos_in_line, message):
18 | complete_message = '%i:%i %s error: %s' % (line, pos_in_line, error_type, message)
19 | if error_type == LEXICAL:
20 | lexical_errors.append(complete_message)
21 | elif error_type == SYNTAX:
22 | syntax_errors.append(complete_message)
23 | elif error_type == SEMANTIC:
24 | semantic_errors.append(complete_message)
25 |
26 |
27 | def get_all_errors():
28 | return lexical_errors + syntax_errors + semantic_errors
29 |
30 |
31 | class SemanticException(Exception):
32 | def __init__(self, position, message):
33 | self.line = position[0]
34 | self.pos_in_line = position[1]
35 | self.message = message
36 |
37 |
38 | class UndefinedIDException(SemanticException): pass
39 | class UnsupportedOperation(SemanticException): pass
40 | class FunctionUnfoundException(SemanticException): pass
41 | class BuiltinConflictException(SemanticException): pass
42 | class FunctionConflictException(SemanticException): pass
43 | class GlobalOperationException(SemanticException): pass
44 | class ReturnTypeException(SemanticException): pass
45 |
--------------------------------------------------------------------------------
/Foreign/ListLang-master/src/llcompiler/globals.py:
--------------------------------------------------------------------------------
1 |
2 | ELEMENT = 'Element'
3 | LIST = 'List'
4 |
5 | # JTYPES
6 | VOID_JTYPE = 'V'
7 | INTEGER_JTYPE = 'I'
8 | STRING_JTYPE = 'Ljava/lang/String;'
9 |
10 | INTEGER_LIST_CLASS = 'listlang/objects/List'
11 | INTEGER_LIST_JTYPE = 'L%s;' % INTEGER_LIST_CLASS
12 |
13 | type_map = {ELEMENT: INTEGER_JTYPE, LIST: INTEGER_LIST_JTYPE}
14 |
15 | RESERVED_LOCALS = 10
16 |
17 | TEMPORARY_STORE_VAR_1 = 0
18 | TEMPORARY_STORE_VAR_2 = 1
19 |
20 | TARGET_CLASS_NAME = 'listlang/program/LLMain'
--------------------------------------------------------------------------------
/Foreign/ListLang-master/src/llcompiler/ll_scope.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | __author__ = 'Oleg Beloglazov'
5 |
6 | import jcodemaker
7 |
8 | class Scope:
9 |
10 | total_scopes_number = 0
11 |
12 | def __init__(self, scope_name='main', global_scope=None):
13 | """ global_scope - scope that global for this scope, None if this scope is global """
14 |
15 | self.scope_number = self.total_scopes_number
16 | Scope.total_scopes_number += 1
17 |
18 | self.scope_name = scope_name
19 |
20 | self.vars = []
21 | self.var_types = {} # dict {var_id: var_type}
22 | self.funcs = {} # {function_id: (function_type, function_params_types, function_scope, ...)}
23 | self.code_maker = jcodemaker.JCodeMaker()
24 | if global_scope:
25 | self.global_scope = global_scope
26 | self.global_vars = []
27 | else:
28 | self.global_scope = self
29 | self.global_vars = None
30 |
31 | def is_global(self):
32 | return self.global_scope is self
33 |
34 | def add_function(self, f_params, f_scope):
35 | f_id = f_scope.scope_name
36 | f_params_types = [param[1] for param in f_params]
37 | self.funcs[f_id] = (None, f_params_types, f_scope)
38 |
39 | def add_var(self, var_id, var_type):
40 | self.vars.append(var_id)
41 | self.var_types[var_id] = var_type
42 |
43 | def add_global_var(self, var_id):
44 | self.global_vars.append(var_id)
45 |
46 | def get_function_code_name(self, name):
47 | return 's%i_%s' % (self.scope_number, name)
48 |
49 | def set_function_return_type(self, functoin_id, return_type):
50 | function_params_types, function_scope = self.funcs[functoin_id][1:3]
51 | self.funcs[functoin_id] = (return_type, function_params_types, function_scope)
52 |
53 | def contains_var(self, var_id):
54 | return var_id in self.vars or (not self.is_global() and var_id in self.global_vars)
--------------------------------------------------------------------------------
/Foreign/ListLang-master/src/readme.txt:
--------------------------------------------------------------------------------
1 | required:
2 | python 2.7.x
3 | java
4 |
5 | get help:
6 | python listlang.py -h
7 |
8 | compile example:
9 | python listlang.py examples\merge_sorted_lists.ll tmp\target.jar
10 |
11 | run compiled example:
12 | java -jar tmp\target.jar
--------------------------------------------------------------------------------
/books/Terence Parr - The Definitive ANTLR Reference.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/books/Terence Parr - The Definitive ANTLR Reference.pdf
--------------------------------------------------------------------------------
/books/Ахо, Сети, Ульман. Компиляторы. Принципы, технологии, инструменты.2ed.2008.djvu:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/books/Ахо, Сети, Ульман. Компиляторы. Принципы, технологии, инструменты.2ed.2008.djvu
--------------------------------------------------------------------------------
/books/Ахо, Сети, Ульман. Компиляторы. Принципы, технологии, инструменты.2ed.2008.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/books/Ахо, Сети, Ульман. Компиляторы. Принципы, технологии, инструменты.2ed.2008.pdf
--------------------------------------------------------------------------------
/books/Ахо, Сети, Ульман. Компиляторы. Принципы, технологии, инструменты.djvu:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/books/Ахо, Сети, Ульман. Компиляторы. Принципы, технологии, инструменты.djvu
--------------------------------------------------------------------------------
/books/Дополнительная литература/Примеры языков/www.engin.umd.umich.edu.chm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/books/Дополнительная литература/Примеры языков/www.engin.umd.umich.edu.chm
--------------------------------------------------------------------------------
/books/Дополнительная литература/Примеры языков/www.ntecs.de.chm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/books/Дополнительная литература/Примеры языков/www.ntecs.de.chm
--------------------------------------------------------------------------------
/books/Пратт, Зелковиц. Языки программирования Разработка и реализация.djvu:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/books/Пратт, Зелковиц. Языки программирования Разработка и реализация.djvu
--------------------------------------------------------------------------------
/books/Себеста. Основные копцепции языков программирования.djvu:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/books/Себеста. Основные копцепции языков программирования.djvu
--------------------------------------------------------------------------------
/exam/YaPIS.quest.end-2010.doc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lehaSVV2009/Compiler/3b02f36670620279d494fa140ab8e9ab9484d175/exam/YaPIS.quest.end-2010.doc
--------------------------------------------------------------------------------